RegisterCoalescer: Improve previous fix for wrong def after.
[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 #include "RegisterCoalescer.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
22 #include "llvm/CodeGen/LiveRangeEdit.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/RegisterClassInfo.h"
29 #include "llvm/CodeGen/VirtRegMap.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 #include <algorithm>
42 #include <cmath>
43 using namespace llvm;
44
45 #define DEBUG_TYPE "regalloc"
46
47 STATISTIC(numJoins    , "Number of interval joins performed");
48 STATISTIC(numCrossRCs , "Number of cross class joins performed");
49 STATISTIC(numCommutes , "Number of instruction commuting performed");
50 STATISTIC(numExtends  , "Number of copies extended");
51 STATISTIC(NumReMats   , "Number of instructions re-materialized");
52 STATISTIC(NumInflated , "Number of register classes inflated");
53 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
54 STATISTIC(NumLaneResolves,  "Number of dead lane conflicts resolved");
55
56 static cl::opt<bool>
57 EnableJoining("join-liveintervals",
58               cl::desc("Coalesce copies (default=true)"),
59               cl::init(true));
60
61 /// Temporary flag to test critical edge unsplitting.
62 static cl::opt<bool>
63 EnableJoinSplits("join-splitedges",
64   cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
65
66 /// Temporary flag to test global copy optimization.
67 static cl::opt<cl::boolOrDefault>
68 EnableGlobalCopies("join-globalcopies",
69   cl::desc("Coalesce copies that span blocks (default=subtarget)"),
70   cl::init(cl::BOU_UNSET), 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     const MachineLoopInfo* Loops;
87     AliasAnalysis *AA;
88     RegisterClassInfo RegClassInfo;
89
90     /// A LaneMask to remember on which subregister live ranges we need to call
91     /// shrinkToUses() later.
92     unsigned ShrinkMask;
93
94     /// True if the main range of the currently coalesced intervals should be
95     /// checked for smaller live intervals.
96     bool ShrinkMainRange;
97
98     /// \brief True if the coalescer should aggressively coalesce global copies
99     /// in favor of keeping local copies.
100     bool JoinGlobalCopies;
101
102     /// \brief True if the coalescer should aggressively coalesce fall-thru
103     /// blocks exclusively containing copies.
104     bool JoinSplitEdges;
105
106     /// Copy instructions yet to be coalesced.
107     SmallVector<MachineInstr*, 8> WorkList;
108     SmallVector<MachineInstr*, 8> LocalWorkList;
109
110     /// Set of instruction pointers that have been erased, and
111     /// that may be present in WorkList.
112     SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
113
114     /// Dead instructions that are about to be deleted.
115     SmallVector<MachineInstr*, 8> DeadDefs;
116
117     /// Virtual registers to be considered for register class inflation.
118     SmallVector<unsigned, 8> InflateRegs;
119
120     /// Recursively eliminate dead defs in DeadDefs.
121     void eliminateDeadDefs();
122
123     /// LiveRangeEdit callback for eliminateDeadDefs().
124     void LRE_WillEraseInstruction(MachineInstr *MI) override;
125
126     /// Coalesce the LocalWorkList.
127     void coalesceLocals();
128
129     /// Join compatible live intervals
130     void joinAllIntervals();
131
132     /// Coalesce copies in the specified MBB, putting
133     /// copies that cannot yet be coalesced into WorkList.
134     void copyCoalesceInMBB(MachineBasicBlock *MBB);
135
136     /// Tries to coalesce all copies in CurrList. Returns true if any progress
137     /// was made.
138     bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
139
140     /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
141     /// src/dst of the copy instruction CopyMI.  This returns true if the copy
142     /// was successfully coalesced away. If it is not currently possible to
143     /// coalesce this interval, but it may be possible if other things get
144     /// coalesced, then it returns true by reference in 'Again'.
145     bool joinCopy(MachineInstr *TheCopy, bool &Again);
146
147     /// Attempt to join these two intervals.  On failure, this
148     /// returns false.  The output "SrcInt" will not have been modified, so we
149     /// can use this information below to update aliases.
150     bool joinIntervals(CoalescerPair &CP);
151
152     /// Attempt joining two virtual registers. Return true on success.
153     bool joinVirtRegs(CoalescerPair &CP);
154
155     /// Attempt joining with a reserved physreg.
156     bool joinReservedPhysReg(CoalescerPair &CP);
157
158     /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
159     /// Subranges in @p LI which only partially interfere with the desired
160     /// LaneMask are split as necessary. @p LaneMask are the lanes that
161     /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
162     /// lanemasks already adjusted to the coalesced register.
163     void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
164                            unsigned LaneMask, CoalescerPair &CP);
165
166     /// Join the liveranges of two subregisters. Joins @p RRange into
167     /// @p LRange, @p RRange may be invalid afterwards.
168     void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
169                           unsigned LaneMask, const CoalescerPair &CP);
170
171     /// We found a non-trivially-coalescable copy. If the source value number is
172     /// defined by a copy from the destination reg see if we can merge these two
173     /// destination reg valno# into a single value number, eliminating a copy.
174     /// This returns true if an interval was modified.
175     bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
176
177     /// Return true if there are definitions of IntB
178     /// other than BValNo val# that can reach uses of AValno val# of IntA.
179     bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
180                               VNInfo *AValNo, VNInfo *BValNo);
181
182     /// We found a non-trivially-coalescable copy.
183     /// If the source value number is defined by a commutable instruction and
184     /// its other operand is coalesced to the copy dest register, see if we
185     /// can transform the copy into a noop by commuting the definition.
186     /// This returns true if an interval was modified.
187     bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
188
189     /// If the source of a copy is defined by a
190     /// trivial computation, replace the copy by rematerialize the definition.
191     bool reMaterializeTrivialDef(CoalescerPair &CP, MachineInstr *CopyMI,
192                                  bool &IsDefCopy);
193
194     /// Return true if a copy involving a physreg should be joined.
195     bool canJoinPhys(const CoalescerPair &CP);
196
197     /// Replace all defs and uses of SrcReg to DstReg and update the subregister
198     /// number if it is not zero. If DstReg is a physical register and the
199     /// existing subregister number of the def / use being updated is not zero,
200     /// make sure to set it to the correct physical subregister.
201     void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
202
203     /// Handle copies of undef values.
204     /// Returns true if @p CopyMI was a copy of an undef value and eliminated.
205     bool eliminateUndefCopy(MachineInstr *CopyMI);
206
207   public:
208     static char ID; ///< Class identification, replacement for typeinfo
209     RegisterCoalescer() : MachineFunctionPass(ID) {
210       initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
211     }
212
213     void getAnalysisUsage(AnalysisUsage &AU) const override;
214
215     void releaseMemory() override;
216
217     /// This is the pass entry point.
218     bool runOnMachineFunction(MachineFunction&) override;
219
220     /// Implement the dump method.
221     void print(raw_ostream &O, const Module* = nullptr) const override;
222   };
223 } // end anonymous namespace
224
225 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
226
227 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
228                       "Simple Register Coalescing", false, false)
229 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
230 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
231 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
232 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
233 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
234                     "Simple Register Coalescing", false, false)
235
236 char RegisterCoalescer::ID = 0;
237
238 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
239                         unsigned &Src, unsigned &Dst,
240                         unsigned &SrcSub, unsigned &DstSub) {
241   if (MI->isCopy()) {
242     Dst = MI->getOperand(0).getReg();
243     DstSub = MI->getOperand(0).getSubReg();
244     Src = MI->getOperand(1).getReg();
245     SrcSub = MI->getOperand(1).getSubReg();
246   } else if (MI->isSubregToReg()) {
247     Dst = MI->getOperand(0).getReg();
248     DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
249                                       MI->getOperand(3).getImm());
250     Src = MI->getOperand(2).getReg();
251     SrcSub = MI->getOperand(2).getSubReg();
252   } else
253     return false;
254   return true;
255 }
256
257 /// Return true if this block should be vacated by the coalescer to eliminate
258 /// branches. The important cases to handle in the coalescer are critical edges
259 /// split during phi elimination which contain only copies. Simple blocks that
260 /// contain non-branches should also be vacated, but this can be handled by an
261 /// earlier pass similar to early if-conversion.
262 static bool isSplitEdge(const MachineBasicBlock *MBB) {
263   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
264     return false;
265
266   for (const auto &MI : *MBB) {
267     if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
268       return false;
269   }
270   return true;
271 }
272
273 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
274   SrcReg = DstReg = 0;
275   SrcIdx = DstIdx = 0;
276   NewRC = nullptr;
277   Flipped = CrossClass = false;
278
279   unsigned Src, Dst, SrcSub, DstSub;
280   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
281     return false;
282   Partial = SrcSub || DstSub;
283
284   // If one register is a physreg, it must be Dst.
285   if (TargetRegisterInfo::isPhysicalRegister(Src)) {
286     if (TargetRegisterInfo::isPhysicalRegister(Dst))
287       return false;
288     std::swap(Src, Dst);
289     std::swap(SrcSub, DstSub);
290     Flipped = true;
291   }
292
293   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
294
295   if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
296     // Eliminate DstSub on a physreg.
297     if (DstSub) {
298       Dst = TRI.getSubReg(Dst, DstSub);
299       if (!Dst) return false;
300       DstSub = 0;
301     }
302
303     // Eliminate SrcSub by picking a corresponding Dst superregister.
304     if (SrcSub) {
305       Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
306       if (!Dst) return false;
307     } else if (!MRI.getRegClass(Src)->contains(Dst)) {
308       return false;
309     }
310   } else {
311     // Both registers are virtual.
312     const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
313     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
314
315     // Both registers have subreg indices.
316     if (SrcSub && DstSub) {
317       // Copies between different sub-registers are never coalescable.
318       if (Src == Dst && SrcSub != DstSub)
319         return false;
320
321       NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
322                                          SrcIdx, DstIdx);
323       if (!NewRC)
324         return false;
325     } else if (DstSub) {
326       // SrcReg will be merged with a sub-register of DstReg.
327       SrcIdx = DstSub;
328       NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
329     } else if (SrcSub) {
330       // DstReg will be merged with a sub-register of SrcReg.
331       DstIdx = SrcSub;
332       NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
333     } else {
334       // This is a straight copy without sub-registers.
335       NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
336     }
337
338     // The combined constraint may be impossible to satisfy.
339     if (!NewRC)
340       return false;
341
342     // Prefer SrcReg to be a sub-register of DstReg.
343     // FIXME: Coalescer should support subregs symmetrically.
344     if (DstIdx && !SrcIdx) {
345       std::swap(Src, Dst);
346       std::swap(SrcIdx, DstIdx);
347       Flipped = !Flipped;
348     }
349
350     CrossClass = NewRC != DstRC || NewRC != SrcRC;
351   }
352   // Check our invariants
353   assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
354   assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
355          "Cannot have a physical SubIdx");
356   SrcReg = Src;
357   DstReg = Dst;
358   return true;
359 }
360
361 bool CoalescerPair::flip() {
362   if (TargetRegisterInfo::isPhysicalRegister(DstReg))
363     return false;
364   std::swap(SrcReg, DstReg);
365   std::swap(SrcIdx, DstIdx);
366   Flipped = !Flipped;
367   return true;
368 }
369
370 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
371   if (!MI)
372     return false;
373   unsigned Src, Dst, SrcSub, DstSub;
374   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
375     return false;
376
377   // Find the virtual register that is SrcReg.
378   if (Dst == SrcReg) {
379     std::swap(Src, Dst);
380     std::swap(SrcSub, DstSub);
381   } else if (Src != SrcReg) {
382     return false;
383   }
384
385   // Now check that Dst matches DstReg.
386   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
387     if (!TargetRegisterInfo::isPhysicalRegister(Dst))
388       return false;
389     assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
390     // DstSub could be set for a physreg from INSERT_SUBREG.
391     if (DstSub)
392       Dst = TRI.getSubReg(Dst, DstSub);
393     // Full copy of Src.
394     if (!SrcSub)
395       return DstReg == Dst;
396     // This is a partial register copy. Check that the parts match.
397     return TRI.getSubReg(DstReg, SrcSub) == Dst;
398   } else {
399     // DstReg is virtual.
400     if (DstReg != Dst)
401       return false;
402     // Registers match, do the subregisters line up?
403     return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
404            TRI.composeSubRegIndices(DstIdx, DstSub);
405   }
406 }
407
408 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
409   AU.setPreservesCFG();
410   AU.addRequired<AliasAnalysis>();
411   AU.addRequired<LiveIntervals>();
412   AU.addPreserved<LiveIntervals>();
413   AU.addPreserved<SlotIndexes>();
414   AU.addRequired<MachineLoopInfo>();
415   AU.addPreserved<MachineLoopInfo>();
416   AU.addPreservedID(MachineDominatorsID);
417   MachineFunctionPass::getAnalysisUsage(AU);
418 }
419
420 void RegisterCoalescer::eliminateDeadDefs() {
421   SmallVector<unsigned, 8> NewRegs;
422   LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
423                 nullptr, this).eliminateDeadDefs(DeadDefs);
424 }
425
426 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
427   // MI may be in WorkList. Make sure we don't visit it.
428   ErasedInstrs.insert(MI);
429 }
430
431 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
432                                              MachineInstr *CopyMI) {
433   assert(!CP.isPartial() && "This doesn't work for partial copies.");
434   assert(!CP.isPhys() && "This doesn't work for physreg copies.");
435
436   LiveInterval &IntA =
437     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
438   LiveInterval &IntB =
439     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
440   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
441
442   // We have a non-trivially-coalescable copy with IntA being the source and
443   // IntB being the dest, thus this defines a value number in IntB.  If the
444   // source value number (in IntA) is defined by a copy from B, see if we can
445   // merge these two pieces of B into a single value number, eliminating a copy.
446   // For example:
447   //
448   //  A3 = B0
449   //    ...
450   //  B1 = A3      <- this copy
451   //
452   // In this case, B0 can be extended to where the B1 copy lives, allowing the
453   // B1 value number to be replaced with B0 (which simplifies the B
454   // liveinterval).
455
456   // BValNo is a value number in B that is defined by a copy from A.  'B1' in
457   // the example above.
458   LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
459   if (BS == IntB.end()) return false;
460   VNInfo *BValNo = BS->valno;
461
462   // Get the location that B is defined at.  Two options: either this value has
463   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
464   // can't process it.
465   if (BValNo->def != CopyIdx) return false;
466
467   // AValNo is the value number in A that defines the copy, A3 in the example.
468   SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
469   LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
470   // The live segment might not exist after fun with physreg coalescing.
471   if (AS == IntA.end()) return false;
472   VNInfo *AValNo = AS->valno;
473
474   // If AValNo is defined as a copy from IntB, we can potentially process this.
475   // Get the instruction that defines this value number.
476   MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
477   // Don't allow any partial copies, even if isCoalescable() allows them.
478   if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
479     return false;
480
481   // Get the Segment in IntB that this value number starts with.
482   LiveInterval::iterator ValS =
483     IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
484   if (ValS == IntB.end())
485     return false;
486
487   // Make sure that the end of the live segment is inside the same block as
488   // CopyMI.
489   MachineInstr *ValSEndInst =
490     LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
491   if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
492     return false;
493
494   // Okay, we now know that ValS ends in the same block that the CopyMI
495   // live-range starts.  If there are no intervening live segments between them
496   // in IntB, we can merge them.
497   if (ValS+1 != BS) return false;
498
499   DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
500
501   SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
502   // We are about to delete CopyMI, so need to remove it as the 'instruction
503   // that defines this value #'. Update the valnum with the new defining
504   // instruction #.
505   BValNo->def = FillerStart;
506
507   // Okay, we can merge them.  We need to insert a new liverange:
508   // [ValS.end, BS.begin) of either value number, then we merge the
509   // two value numbers.
510   IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
511
512   // Okay, merge "B1" into the same value number as "B0".
513   if (BValNo != ValS->valno)
514     IntB.MergeValueNumberInto(BValNo, ValS->valno);
515
516   // Do the same for the subregister segments.
517   for (LiveInterval::SubRange &S : IntB.subranges()) {
518     VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
519     S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
520     VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
521     if (SubBValNo != SubValSNo)
522       S.MergeValueNumberInto(SubBValNo, SubValSNo);
523   }
524
525   DEBUG(dbgs() << "   result = " << IntB << '\n');
526
527   // If the source instruction was killing the source register before the
528   // merge, unset the isKill marker given the live range has been extended.
529   int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
530   if (UIdx != -1) {
531     ValSEndInst->getOperand(UIdx).setIsKill(false);
532   }
533
534   // Rewrite the copy. If the copy instruction was killing the destination
535   // register before the merge, find the last use and trim the live range. That
536   // will also add the isKill marker.
537   CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
538   if (AS->end == CopyIdx)
539     LIS->shrinkToUses(&IntA);
540
541   ++numExtends;
542   return true;
543 }
544
545 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
546                                              LiveInterval &IntB,
547                                              VNInfo *AValNo,
548                                              VNInfo *BValNo) {
549   // If AValNo has PHI kills, conservatively assume that IntB defs can reach
550   // the PHI values.
551   if (LIS->hasPHIKill(IntA, AValNo))
552     return true;
553
554   for (LiveRange::Segment &ASeg : IntA.segments) {
555     if (ASeg.valno != AValNo) continue;
556     LiveInterval::iterator BI =
557       std::upper_bound(IntB.begin(), IntB.end(), ASeg.start);
558     if (BI != IntB.begin())
559       --BI;
560     for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
561       if (BI->valno == BValNo)
562         continue;
563       if (BI->start <= ASeg.start && BI->end > ASeg.start)
564         return true;
565       if (BI->start > ASeg.start && BI->start < ASeg.end)
566         return true;
567     }
568   }
569   return false;
570 }
571
572 /// Copy segements with value number @p SrcValNo from liverange @p Src to live
573 /// range @Dst and use value number @p DstValNo there.
574 static void addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo,
575                                  const LiveRange &Src, const VNInfo *SrcValNo)
576 {
577   for (const LiveRange::Segment &S : Src.segments) {
578     if (S.valno != SrcValNo)
579       continue;
580     Dst.addSegment(LiveRange::Segment(S.start, S.end, DstValNo));
581   }
582 }
583
584 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
585                                                  MachineInstr *CopyMI) {
586   assert(!CP.isPhys());
587
588   LiveInterval &IntA =
589       LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
590   LiveInterval &IntB =
591       LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
592
593   // We found a non-trivially-coalescable copy with IntA being the source and
594   // IntB being the dest, thus this defines a value number in IntB.  If the
595   // source value number (in IntA) is defined by a commutable instruction and
596   // its other operand is coalesced to the copy dest register, see if we can
597   // transform the copy into a noop by commuting the definition. For example,
598   //
599   //  A3 = op A2 B0<kill>
600   //    ...
601   //  B1 = A3      <- this copy
602   //    ...
603   //     = op A3   <- more uses
604   //
605   // ==>
606   //
607   //  B2 = op B0 A2<kill>
608   //    ...
609   //  B1 = B2      <- now an identity copy
610   //    ...
611   //     = op B2   <- more uses
612
613   // BValNo is a value number in B that is defined by a copy from A. 'B1' in
614   // the example above.
615   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
616   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
617   assert(BValNo != nullptr && BValNo->def == CopyIdx);
618
619   // AValNo is the value number in A that defines the copy, A3 in the example.
620   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
621   assert(AValNo && !AValNo->isUnused() && "COPY source not live");
622   if (AValNo->isPHIDef())
623     return false;
624   MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
625   if (!DefMI)
626     return false;
627   if (!DefMI->isCommutable())
628     return false;
629   // If DefMI is a two-address instruction then commuting it will change the
630   // destination register.
631   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
632   assert(DefIdx != -1);
633   unsigned UseOpIdx;
634   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
635     return false;
636   unsigned Op1, Op2, NewDstIdx;
637   if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
638     return false;
639   if (Op1 == UseOpIdx)
640     NewDstIdx = Op2;
641   else if (Op2 == UseOpIdx)
642     NewDstIdx = Op1;
643   else
644     return false;
645
646   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
647   unsigned NewReg = NewDstMO.getReg();
648   if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
649     return false;
650
651   // Make sure there are no other definitions of IntB that would reach the
652   // uses which the new definition can reach.
653   if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
654     return false;
655
656   // If some of the uses of IntA.reg is already coalesced away, return false.
657   // It's not possible to determine whether it's safe to perform the coalescing.
658   for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) {
659     MachineInstr *UseMI = MO.getParent();
660     unsigned OpNo = &MO - &UseMI->getOperand(0);
661     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
662     LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
663     if (US == IntA.end() || US->valno != AValNo)
664       continue;
665     // If this use is tied to a def, we can't rewrite the register.
666     if (UseMI->isRegTiedToDefOperand(OpNo))
667       return false;
668   }
669
670   DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
671                << *DefMI);
672
673   // At this point we have decided that it is legal to do this
674   // transformation.  Start by commuting the instruction.
675   MachineBasicBlock *MBB = DefMI->getParent();
676   MachineInstr *NewMI = TII->commuteInstruction(DefMI);
677   if (!NewMI)
678     return false;
679   if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
680       TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
681       !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
682     return false;
683   if (NewMI != DefMI) {
684     LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
685     MachineBasicBlock::iterator Pos = DefMI;
686     MBB->insert(Pos, NewMI);
687     MBB->erase(DefMI);
688   }
689
690   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
691   // A = or A, B
692   // ...
693   // B = A
694   // ...
695   // C = A<kill>
696   // ...
697   //   = B
698
699   // Update uses of IntA of the specific Val# with IntB.
700   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
701                                          UE = MRI->use_end();
702        UI != UE; /* ++UI is below because of possible MI removal */) {
703     MachineOperand &UseMO = *UI;
704     ++UI;
705     if (UseMO.isUndef())
706       continue;
707     MachineInstr *UseMI = UseMO.getParent();
708     if (UseMI->isDebugValue()) {
709       // FIXME These don't have an instruction index.  Not clear we have enough
710       // info to decide whether to do this replacement or not.  For now do it.
711       UseMO.setReg(NewReg);
712       continue;
713     }
714     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
715     LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
716     assert(US != IntA.end() && "Use must be live");
717     if (US->valno != AValNo)
718       continue;
719     // Kill flags are no longer accurate. They are recomputed after RA.
720     UseMO.setIsKill(false);
721     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
722       UseMO.substPhysReg(NewReg, *TRI);
723     else
724       UseMO.setReg(NewReg);
725     if (UseMI == CopyMI)
726       continue;
727     if (!UseMI->isCopy())
728       continue;
729     if (UseMI->getOperand(0).getReg() != IntB.reg ||
730         UseMI->getOperand(0).getSubReg())
731       continue;
732
733     // This copy will become a noop. If it's defining a new val#, merge it into
734     // BValNo.
735     SlotIndex DefIdx = UseIdx.getRegSlot();
736     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
737     if (!DVNI)
738       continue;
739     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
740     assert(DVNI->def == DefIdx);
741     BValNo = IntB.MergeValueNumberInto(DVNI, BValNo);
742     for (LiveInterval::SubRange &S : IntB.subranges()) {
743       VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
744       if (!SubDVNI)
745         continue;
746       VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
747       assert(SubBValNo->def == CopyIdx);
748       S.MergeValueNumberInto(SubDVNI, SubBValNo);
749     }
750
751     ErasedInstrs.insert(UseMI);
752     LIS->RemoveMachineInstrFromMaps(UseMI);
753     UseMI->eraseFromParent();
754   }
755
756   // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
757   // is updated.
758   BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
759   if (IntB.hasSubRanges()) {
760     if (!IntA.hasSubRanges()) {
761       unsigned Mask = MRI->getMaxLaneMaskForVReg(IntA.reg);
762       IntA.createSubRangeFrom(Allocator, Mask, IntA);
763     }
764     SlotIndex AIdx = CopyIdx.getRegSlot(true);
765     for (LiveInterval::SubRange &SA : IntA.subranges()) {
766       VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
767       assert(ASubValNo != nullptr);
768
769       unsigned AMask = SA.LaneMask;
770       for (LiveInterval::SubRange &SB : IntB.subranges()) {
771         unsigned BMask = SB.LaneMask;
772         unsigned Common = BMask & AMask;
773         if (Common == 0)
774           continue;
775
776         DEBUG(
777             dbgs() << format("\t\tCopy+Merge %04X into %04X\n", BMask, Common));
778         unsigned BRest = BMask & ~AMask;
779         LiveInterval::SubRange *CommonRange;
780         if (BRest != 0) {
781           SB.LaneMask = BRest;
782           DEBUG(dbgs() << format("\t\tReduce Lane to %04X\n", BRest));
783           // Duplicate SubRange for newly merged common stuff.
784           CommonRange = IntB.createSubRangeFrom(Allocator, Common, SB);
785         } else {
786           // We van reuse the L SubRange.
787           SB.LaneMask = Common;
788           CommonRange = &SB;
789         }
790         LiveRange RangeCopy(SB, Allocator);
791
792         VNInfo *BSubValNo = CommonRange->getVNInfoAt(CopyIdx);
793         assert(BSubValNo->def == CopyIdx);
794         BSubValNo->def = ASubValNo->def;
795         addSegmentsWithValNo(*CommonRange, BSubValNo, SA, ASubValNo);
796         AMask &= ~BMask;
797       }
798       if (AMask != 0) {
799         DEBUG(dbgs() << format("\t\tNew Lane %04X\n", AMask));
800         LiveRange *NewRange = IntB.createSubRange(Allocator, AMask);
801         VNInfo *BSubValNo = NewRange->getNextValue(CopyIdx, Allocator);
802         addSegmentsWithValNo(*NewRange, BSubValNo, SA, ASubValNo);
803       }
804     }
805   }
806
807   BValNo->def = AValNo->def;
808   addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
809   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
810
811   LIS->removeVRegDefAt(IntA, AValNo->def);
812
813   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
814   ++numCommutes;
815   return true;
816 }
817
818 bool RegisterCoalescer::reMaterializeTrivialDef(CoalescerPair &CP,
819                                                 MachineInstr *CopyMI,
820                                                 bool &IsDefCopy) {
821   IsDefCopy = false;
822   unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
823   unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
824   unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
825   unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
826   if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
827     return false;
828
829   LiveInterval &SrcInt = LIS->getInterval(SrcReg);
830   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
831   VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
832   assert(ValNo && "CopyMI input register not live");
833   if (ValNo->isPHIDef() || ValNo->isUnused())
834     return false;
835   MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
836   if (!DefMI)
837     return false;
838   if (DefMI->isCopyLike()) {
839     IsDefCopy = true;
840     return false;
841   }
842   if (!TII->isAsCheapAsAMove(DefMI))
843     return false;
844   if (!TII->isTriviallyReMaterializable(DefMI, AA))
845     return false;
846   bool SawStore = false;
847   if (!DefMI->isSafeToMove(TII, AA, SawStore))
848     return false;
849   const MCInstrDesc &MCID = DefMI->getDesc();
850   if (MCID.getNumDefs() != 1)
851     return false;
852   // Only support subregister destinations when the def is read-undef.
853   MachineOperand &DstOperand = CopyMI->getOperand(0);
854   unsigned CopyDstReg = DstOperand.getReg();
855   if (DstOperand.getSubReg() && !DstOperand.isUndef())
856     return false;
857
858   // If both SrcIdx and DstIdx are set, correct rematerialization would widen
859   // the register substantially (beyond both source and dest size). This is bad
860   // for performance since it can cascade through a function, introducing many
861   // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
862   // around after a few subreg copies).
863   if (SrcIdx && DstIdx)
864     return false;
865
866   const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
867   if (!DefMI->isImplicitDef()) {
868     if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
869       unsigned NewDstReg = DstReg;
870
871       unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
872                                               DefMI->getOperand(0).getSubReg());
873       if (NewDstIdx)
874         NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
875
876       // Finally, make sure that the physical subregister that will be
877       // constructed later is permitted for the instruction.
878       if (!DefRC->contains(NewDstReg))
879         return false;
880     } else {
881       // Theoretically, some stack frame reference could exist. Just make sure
882       // it hasn't actually happened.
883       assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
884              "Only expect to deal with virtual or physical registers");
885     }
886   }
887
888   MachineBasicBlock *MBB = CopyMI->getParent();
889   MachineBasicBlock::iterator MII =
890     std::next(MachineBasicBlock::iterator(CopyMI));
891   TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, DefMI, *TRI);
892   MachineInstr *NewMI = std::prev(MII);
893
894   LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
895   CopyMI->eraseFromParent();
896   ErasedInstrs.insert(CopyMI);
897
898   // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
899   // We need to remember these so we can add intervals once we insert
900   // NewMI into SlotIndexes.
901   SmallVector<unsigned, 4> NewMIImplDefs;
902   for (unsigned i = NewMI->getDesc().getNumOperands(),
903          e = NewMI->getNumOperands(); i != e; ++i) {
904     MachineOperand &MO = NewMI->getOperand(i);
905     if (MO.isReg()) {
906       assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
907              TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
908       NewMIImplDefs.push_back(MO.getReg());
909     }
910   }
911
912   if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
913     const TargetRegisterClass *NewRC = CP.getNewRC();
914     unsigned NewIdx = NewMI->getOperand(0).getSubReg();
915
916     if (NewIdx)
917       NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
918     else
919       NewRC = TRI->getCommonSubClass(NewRC, DefRC);
920
921     assert(NewRC && "subreg chosen for remat incompatible with instruction");
922     MRI->setRegClass(DstReg, NewRC);
923
924     updateRegDefsUses(DstReg, DstReg, DstIdx);
925     NewMI->getOperand(0).setSubReg(NewIdx);
926   } else if (NewMI->getOperand(0).getReg() != CopyDstReg) {
927     // The New instruction may be defining a sub-register of what's actually
928     // been asked for. If so it must implicitly define the whole thing.
929     assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
930            "Only expect virtual or physical registers in remat");
931     NewMI->getOperand(0).setIsDead(true);
932     NewMI->addOperand(MachineOperand::CreateReg(CopyDstReg,
933                                                 true  /*IsDef*/,
934                                                 true  /*IsImp*/,
935                                                 false /*IsKill*/));
936     // Record small dead def live-ranges for all the subregisters
937     // of the destination register.
938     // Otherwise, variables that live through may miss some
939     // interferences, thus creating invalid allocation.
940     // E.g., i386 code:
941     // vreg1 = somedef ; vreg1 GR8
942     // vreg2 = remat ; vreg2 GR32
943     // CL = COPY vreg2.sub_8bit
944     // = somedef vreg1 ; vreg1 GR8
945     // =>
946     // vreg1 = somedef ; vreg1 GR8
947     // ECX<def, dead> = remat ; CL<imp-def>
948     // = somedef vreg1 ; vreg1 GR8
949     // vreg1 will see the inteferences with CL but not with CH since
950     // no live-ranges would have been created for ECX.
951     // Fix that!
952     SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
953     for (MCRegUnitIterator Units(NewMI->getOperand(0).getReg(), TRI);
954          Units.isValid(); ++Units)
955       if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
956         LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
957   }
958
959   if (NewMI->getOperand(0).getSubReg())
960     NewMI->getOperand(0).setIsUndef();
961
962   // CopyMI may have implicit operands, transfer them over to the newly
963   // rematerialized instruction. And update implicit def interval valnos.
964   for (unsigned i = CopyMI->getDesc().getNumOperands(),
965          e = CopyMI->getNumOperands(); i != e; ++i) {
966     MachineOperand &MO = CopyMI->getOperand(i);
967     if (MO.isReg()) {
968       assert(MO.isImplicit() && "No explicit operands after implict operands.");
969       // Discard VReg implicit defs.
970       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
971         NewMI->addOperand(MO);
972       }
973     }
974   }
975
976   SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
977   for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
978     unsigned Reg = NewMIImplDefs[i];
979     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
980       if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
981         LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
982   }
983
984   DEBUG(dbgs() << "Remat: " << *NewMI);
985   ++NumReMats;
986
987   // The source interval can become smaller because we removed a use.
988   LIS->shrinkToUses(&SrcInt, &DeadDefs);
989   if (!DeadDefs.empty()) {
990     // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
991     // to describe DstReg instead.
992     for (MachineOperand &UseMO : MRI->use_operands(SrcReg)) {
993       MachineInstr *UseMI = UseMO.getParent();
994       if (UseMI->isDebugValue()) {
995         UseMO.setReg(DstReg);
996         DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
997       }
998     }
999     eliminateDeadDefs();
1000   }
1001
1002   return true;
1003 }
1004
1005 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
1006   // ProcessImpicitDefs may leave some copies of <undef> values, it only removes
1007   // local variables. When we have a copy like:
1008   //
1009   //   %vreg1 = COPY %vreg2<undef>
1010   //
1011   // We delete the copy and remove the corresponding value number from %vreg1.
1012   // Any uses of that value number are marked as <undef>.
1013
1014   // Note that we do not query CoalescerPair here but redo isMoveInstr as the
1015   // CoalescerPair may have a new register class with adjusted subreg indices
1016   // at this point.
1017   unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1018   isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
1019
1020   SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
1021   const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
1022   // CopyMI is undef iff SrcReg is not live before the instruction.
1023   if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
1024     unsigned SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
1025     for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
1026       if ((SR.LaneMask & SrcMask) == 0)
1027         continue;
1028       if (SR.liveAt(Idx))
1029         return false;
1030     }
1031   } else if (SrcLI.liveAt(Idx))
1032     return false;
1033
1034   DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
1035
1036   // Remove any DstReg segments starting at the instruction.
1037   LiveInterval &DstLI = LIS->getInterval(DstReg);
1038   SlotIndex RegIndex = Idx.getRegSlot();
1039   // Remove value or merge with previous one in case of a subregister def.
1040   if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
1041     VNInfo *VNI = DstLI.getVNInfoAt(RegIndex);
1042     DstLI.MergeValueNumberInto(VNI, PrevVNI);
1043
1044     // The affected subregister segments can be removed.
1045     unsigned DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
1046     for (LiveInterval::SubRange &SR : DstLI.subranges()) {
1047       if ((SR.LaneMask & DstMask) == 0)
1048         continue;
1049
1050       VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
1051       assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex));
1052       SR.removeValNo(SVNI);
1053     }
1054     DstLI.removeEmptySubRanges();
1055   } else
1056     LIS->removeVRegDefAt(DstLI, RegIndex);
1057
1058   // Mark uses as undef.
1059   for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
1060     if (MO.isDef() /*|| MO.isUndef()*/)
1061       continue;
1062     const MachineInstr &MI = *MO.getParent();
1063     SlotIndex UseIdx = LIS->getInstructionIndex(&MI);
1064     unsigned UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
1065     bool isLive;
1066     if (UseMask != ~0u && DstLI.hasSubRanges()) {
1067       isLive = false;
1068       for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
1069         if ((SR.LaneMask & UseMask) == 0)
1070           continue;
1071         if (SR.liveAt(UseIdx)) {
1072           isLive = true;
1073           break;
1074         }
1075       }
1076     } else
1077       isLive = DstLI.liveAt(UseIdx);
1078     if (isLive)
1079       continue;
1080     MO.setIsUndef(true);
1081     DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
1082   }
1083   return true;
1084 }
1085
1086 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
1087                                           unsigned DstReg,
1088                                           unsigned SubIdx) {
1089   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1090   LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
1091
1092   SmallPtrSet<MachineInstr*, 8> Visited;
1093   for (MachineRegisterInfo::reg_instr_iterator
1094        I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
1095        I != E; ) {
1096     MachineInstr *UseMI = &*(I++);
1097
1098     // Each instruction can only be rewritten once because sub-register
1099     // composition is not always idempotent. When SrcReg != DstReg, rewriting
1100     // the UseMI operands removes them from the SrcReg use-def chain, but when
1101     // SrcReg is DstReg we could encounter UseMI twice if it has multiple
1102     // operands mentioning the virtual register.
1103     if (SrcReg == DstReg && !Visited.insert(UseMI).second)
1104       continue;
1105
1106     SmallVector<unsigned,8> Ops;
1107     bool Reads, Writes;
1108     std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
1109
1110     // If SrcReg wasn't read, it may still be the case that DstReg is live-in
1111     // because SrcReg is a sub-register.
1112     if (DstInt && !Reads && SubIdx)
1113       Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
1114
1115     // Replace SrcReg with DstReg in all UseMI operands.
1116     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1117       MachineOperand &MO = UseMI->getOperand(Ops[i]);
1118
1119       // Adjust <undef> flags in case of sub-register joins. We don't want to
1120       // turn a full def into a read-modify-write sub-register def and vice
1121       // versa.
1122       if (SubIdx && MO.isDef())
1123         MO.setIsUndef(!Reads);
1124
1125       // A subreg use of a partially undef (super) register may be a complete
1126       // undef use now and then has to be marked that way.
1127       if (SubIdx != 0 && MO.isUse() && MRI->tracksSubRegLiveness()) {
1128         if (!DstInt->hasSubRanges()) {
1129           BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
1130           unsigned Mask = MRI->getMaxLaneMaskForVReg(DstInt->reg);
1131           DstInt->createSubRangeFrom(Allocator, Mask, *DstInt);
1132         }
1133         unsigned Mask = TRI->getSubRegIndexLaneMask(SubIdx);
1134         bool IsUndef = true;
1135         SlotIndex MIIdx = UseMI->isDebugValue()
1136           ? LIS->getSlotIndexes()->getIndexBefore(UseMI)
1137           : LIS->getInstructionIndex(UseMI);
1138         SlotIndex UseIdx = MIIdx.getRegSlot(true);
1139         for (LiveInterval::SubRange &S : DstInt->subranges()) {
1140           if ((S.LaneMask & Mask) == 0)
1141             continue;
1142           if (S.liveAt(UseIdx)) {
1143             IsUndef = false;
1144             break;
1145           }
1146         }
1147         if (IsUndef) {
1148           MO.setIsUndef(true);
1149           // We found out some subregister use is actually reading an undefined
1150           // value. In some cases the whole vreg has become undefined at this
1151           // point so we have to potentially shrink the main range if the
1152           // use was ending a live segment there.
1153           LiveQueryResult Q = DstInt->Query(MIIdx);
1154           if (Q.valueOut() == nullptr)
1155             ShrinkMainRange = true;
1156         }
1157       }
1158
1159       if (DstIsPhys)
1160         MO.substPhysReg(DstReg, *TRI);
1161       else
1162         MO.substVirtReg(DstReg, SubIdx, *TRI);
1163     }
1164
1165     DEBUG({
1166         dbgs() << "\t\tupdated: ";
1167         if (!UseMI->isDebugValue())
1168           dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
1169         dbgs() << *UseMI;
1170       });
1171   }
1172 }
1173
1174 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
1175   // Always join simple intervals that are defined by a single copy from a
1176   // reserved register. This doesn't increase register pressure, so it is
1177   // always beneficial.
1178   if (!MRI->isReserved(CP.getDstReg())) {
1179     DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1180     return false;
1181   }
1182
1183   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1184   if (JoinVInt.containsOneValue())
1185     return true;
1186
1187   DEBUG(dbgs() << "\tCannot join complex intervals into reserved register.\n");
1188   return false;
1189 }
1190
1191 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1192
1193   Again = false;
1194   DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1195
1196   CoalescerPair CP(*TRI);
1197   if (!CP.setRegisters(CopyMI)) {
1198     DEBUG(dbgs() << "\tNot coalescable.\n");
1199     return false;
1200   }
1201
1202   if (CP.getNewRC()) {
1203     auto SrcRC = MRI->getRegClass(CP.getSrcReg());
1204     auto DstRC = MRI->getRegClass(CP.getDstReg());
1205     unsigned SrcIdx = CP.getSrcIdx();
1206     unsigned DstIdx = CP.getDstIdx();
1207     if (CP.isFlipped()) {
1208       std::swap(SrcIdx, DstIdx);
1209       std::swap(SrcRC, DstRC);
1210     }
1211     if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
1212                             CP.getNewRC())) {
1213       DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
1214       return false;
1215     }
1216   }
1217
1218   // Dead code elimination. This really should be handled by MachineDCE, but
1219   // sometimes dead copies slip through, and we can't generate invalid live
1220   // ranges.
1221   if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1222     DEBUG(dbgs() << "\tCopy is dead.\n");
1223     DeadDefs.push_back(CopyMI);
1224     eliminateDeadDefs();
1225     return true;
1226   }
1227
1228   // Eliminate undefs.
1229   if (!CP.isPhys() && eliminateUndefCopy(CopyMI)) {
1230     LIS->RemoveMachineInstrFromMaps(CopyMI);
1231     CopyMI->eraseFromParent();
1232     return false;  // Not coalescable.
1233   }
1234
1235   // Coalesced copies are normally removed immediately, but transformations
1236   // like removeCopyByCommutingDef() can inadvertently create identity copies.
1237   // When that happens, just join the values and remove the copy.
1238   if (CP.getSrcReg() == CP.getDstReg()) {
1239     LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
1240     DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
1241     const SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
1242     LiveQueryResult LRQ = LI.Query(CopyIdx);
1243     if (VNInfo *DefVNI = LRQ.valueDefined()) {
1244       VNInfo *ReadVNI = LRQ.valueIn();
1245       assert(ReadVNI && "No value before copy and no <undef> flag.");
1246       assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
1247       LI.MergeValueNumberInto(DefVNI, ReadVNI);
1248
1249       // Process subregister liveranges.
1250       for (LiveInterval::SubRange &S : LI.subranges()) {
1251         LiveQueryResult SLRQ = S.Query(CopyIdx);
1252         if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
1253           VNInfo *SReadVNI = SLRQ.valueIn();
1254           S.MergeValueNumberInto(SDefVNI, SReadVNI);
1255         }
1256       }
1257       DEBUG(dbgs() << "\tMerged values:          " << LI << '\n');
1258     }
1259     LIS->RemoveMachineInstrFromMaps(CopyMI);
1260     CopyMI->eraseFromParent();
1261     return true;
1262   }
1263
1264   // Enforce policies.
1265   if (CP.isPhys()) {
1266     DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1267                  << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1268                  << '\n');
1269     if (!canJoinPhys(CP)) {
1270       // Before giving up coalescing, if definition of source is defined by
1271       // trivial computation, try rematerializing it.
1272       bool IsDefCopy;
1273       if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1274         return true;
1275       if (IsDefCopy)
1276         Again = true;  // May be possible to coalesce later.
1277       return false;
1278     }
1279   } else {
1280     // When possible, let DstReg be the larger interval.
1281     if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
1282                            LIS->getInterval(CP.getDstReg()).size())
1283       CP.flip();
1284
1285     DEBUG({
1286       dbgs() << "\tConsidering merging to "
1287              << TRI->getRegClassName(CP.getNewRC()) << " with ";
1288       if (CP.getDstIdx() && CP.getSrcIdx())
1289         dbgs() << PrintReg(CP.getDstReg()) << " in "
1290                << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1291                << PrintReg(CP.getSrcReg()) << " in "
1292                << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1293       else
1294         dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1295                << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1296     });
1297   }
1298
1299   ShrinkMask = 0;
1300   ShrinkMainRange = false;
1301
1302   // Okay, attempt to join these two intervals.  On failure, this returns false.
1303   // Otherwise, if one of the intervals being joined is a physreg, this method
1304   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1305   // been modified, so we can use this information below to update aliases.
1306   if (!joinIntervals(CP)) {
1307     // Coalescing failed.
1308
1309     // If definition of source is defined by trivial computation, try
1310     // rematerializing it.
1311     bool IsDefCopy;
1312     if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1313       return true;
1314
1315     // If we can eliminate the copy without merging the live segments, do so
1316     // now.
1317     if (!CP.isPartial() && !CP.isPhys()) {
1318       if (adjustCopiesBackFrom(CP, CopyMI) ||
1319           removeCopyByCommutingDef(CP, CopyMI)) {
1320         LIS->RemoveMachineInstrFromMaps(CopyMI);
1321         CopyMI->eraseFromParent();
1322         DEBUG(dbgs() << "\tTrivial!\n");
1323         return true;
1324       }
1325     }
1326
1327     // Otherwise, we are unable to join the intervals.
1328     DEBUG(dbgs() << "\tInterference!\n");
1329     Again = true;  // May be possible to coalesce later.
1330     return false;
1331   }
1332
1333   // Coalescing to a virtual register that is of a sub-register class of the
1334   // other. Make sure the resulting register is set to the right register class.
1335   if (CP.isCrossClass()) {
1336     ++numCrossRCs;
1337     MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1338   }
1339
1340   // Removing sub-register copies can ease the register class constraints.
1341   // Make sure we attempt to inflate the register class of DstReg.
1342   if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1343     InflateRegs.push_back(CP.getDstReg());
1344
1345   // CopyMI has been erased by joinIntervals at this point. Remove it from
1346   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1347   // to the work list. This keeps ErasedInstrs from growing needlessly.
1348   ErasedInstrs.erase(CopyMI);
1349
1350   // Rewrite all SrcReg operands to DstReg.
1351   // Also update DstReg operands to include DstIdx if it is set.
1352   if (CP.getDstIdx())
1353     updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1354   updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1355
1356   // Shrink subregister ranges if necessary.
1357   if (ShrinkMask != 0) {
1358     LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1359     for (LiveInterval::SubRange &S : LI.subranges()) {
1360       if ((S.LaneMask & ShrinkMask) == 0)
1361         continue;
1362       DEBUG(dbgs() << "Shrink LaneUses (Lane "
1363                    << format("%04X", S.LaneMask) << ")\n");
1364       LIS->shrinkToUses(S, LI.reg);
1365     }
1366   }
1367   if (ShrinkMainRange) {
1368     LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1369     LIS->shrinkToUses(&LI);
1370   }
1371
1372   // SrcReg is guaranteed to be the register whose live interval that is
1373   // being merged.
1374   LIS->removeInterval(CP.getSrcReg());
1375
1376   // Update regalloc hint.
1377   TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1378
1379   DEBUG({
1380     dbgs() << "\tSuccess: " << PrintReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
1381            << " -> " << PrintReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
1382     dbgs() << "\tResult = ";
1383     if (CP.isPhys())
1384       dbgs() << PrintReg(CP.getDstReg(), TRI);
1385     else
1386       dbgs() << LIS->getInterval(CP.getDstReg());
1387     dbgs() << '\n';
1388   });
1389
1390   ++numJoins;
1391   return true;
1392 }
1393
1394 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1395   unsigned DstReg = CP.getDstReg();
1396   assert(CP.isPhys() && "Must be a physreg copy");
1397   assert(MRI->isReserved(DstReg) && "Not a reserved register");
1398   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1399   DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
1400
1401   assert(RHS.containsOneValue() && "Invalid join with reserved register");
1402
1403   // Optimization for reserved registers like ESP. We can only merge with a
1404   // reserved physreg if RHS has a single value that is a copy of DstReg.
1405   // The live range of the reserved register will look like a set of dead defs
1406   // - we don't properly track the live range of reserved registers.
1407
1408   // Deny any overlapping intervals.  This depends on all the reserved
1409   // register live ranges to look like dead defs.
1410   for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI)
1411     if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1412       DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1413       return false;
1414     }
1415
1416   // Skip any value computations, we are not adding new values to the
1417   // reserved register.  Also skip merging the live ranges, the reserved
1418   // register live range doesn't need to be accurate as long as all the
1419   // defs are there.
1420
1421   // Delete the identity copy.
1422   MachineInstr *CopyMI;
1423   if (CP.isFlipped()) {
1424     CopyMI = MRI->getVRegDef(RHS.reg);
1425   } else {
1426     if (!MRI->hasOneNonDBGUse(RHS.reg)) {
1427       DEBUG(dbgs() << "\t\tMultiple vreg uses!\n");
1428       return false;
1429     }
1430
1431     MachineInstr *DestMI = MRI->getVRegDef(RHS.reg);
1432     CopyMI = &*MRI->use_instr_nodbg_begin(RHS.reg);
1433     const SlotIndex CopyRegIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
1434     const SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot();
1435
1436     // We checked above that there are no interfering defs of the physical
1437     // register. However, for this case, where we intent to move up the def of
1438     // the physical register, we also need to check for interfering uses.
1439     SlotIndexes *Indexes = LIS->getSlotIndexes();
1440     for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx);
1441          SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) {
1442       MachineInstr *MI = LIS->getInstructionFromIndex(SI);
1443       if (MI->readsRegister(DstReg, TRI)) {
1444         DEBUG(dbgs() << "\t\tInterference (read): " << *MI);
1445         return false;
1446       }
1447     }
1448
1449     // We're going to remove the copy which defines a physical reserved
1450     // register, so remove its valno, etc.
1451     DEBUG(dbgs() << "\t\tRemoving phys reg def of " << DstReg << " at "
1452           << CopyRegIdx << "\n");
1453
1454     LIS->removePhysRegDefAt(DstReg, CopyRegIdx);
1455     // Create a new dead def at the new def location.
1456     for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
1457       LiveRange &LR = LIS->getRegUnit(*UI);
1458       LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
1459     }
1460   }
1461
1462   LIS->RemoveMachineInstrFromMaps(CopyMI);
1463   CopyMI->eraseFromParent();
1464
1465   // We don't track kills for reserved registers.
1466   MRI->clearKillFlags(CP.getSrcReg());
1467
1468   return true;
1469 }
1470
1471 //===----------------------------------------------------------------------===//
1472 //                 Interference checking and interval joining
1473 //===----------------------------------------------------------------------===//
1474 //
1475 // In the easiest case, the two live ranges being joined are disjoint, and
1476 // there is no interference to consider. It is quite common, though, to have
1477 // overlapping live ranges, and we need to check if the interference can be
1478 // resolved.
1479 //
1480 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1481 // This means that two SSA values overlap if and only if the def of one value
1482 // is contained in the live range of the other value. As a special case, the
1483 // overlapping values can be defined at the same index.
1484 //
1485 // The interference from an overlapping def can be resolved in these cases:
1486 //
1487 // 1. Coalescable copies. The value is defined by a copy that would become an
1488 //    identity copy after joining SrcReg and DstReg. The copy instruction will
1489 //    be removed, and the value will be merged with the source value.
1490 //
1491 //    There can be several copies back and forth, causing many values to be
1492 //    merged into one. We compute a list of ultimate values in the joined live
1493 //    range as well as a mappings from the old value numbers.
1494 //
1495 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1496 //    predecessors have a live out value. It doesn't cause real interference,
1497 //    and can be merged into the value it overlaps. Like a coalescable copy, it
1498 //    can be erased after joining.
1499 //
1500 // 3. Copy of external value. The overlapping def may be a copy of a value that
1501 //    is already in the other register. This is like a coalescable copy, but
1502 //    the live range of the source register must be trimmed after erasing the
1503 //    copy instruction:
1504 //
1505 //      %src = COPY %ext
1506 //      %dst = COPY %ext  <-- Remove this COPY, trim the live range of %ext.
1507 //
1508 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1509 //    defining one lane at a time:
1510 //
1511 //      %dst:ssub0<def,read-undef> = FOO
1512 //      %src = BAR
1513 //      %dst:ssub1<def> = COPY %src
1514 //
1515 //    The live range of %src overlaps the %dst value defined by FOO, but
1516 //    merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1517 //    which was undef anyway.
1518 //
1519 //    The value mapping is more complicated in this case. The final live range
1520 //    will have different value numbers for both FOO and BAR, but there is no
1521 //    simple mapping from old to new values. It may even be necessary to add
1522 //    new PHI values.
1523 //
1524 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1525 //    is live, but never read. This can happen because we don't compute
1526 //    individual live ranges per lane.
1527 //
1528 //      %dst<def> = FOO
1529 //      %src = BAR
1530 //      %dst:ssub1<def> = COPY %src
1531 //
1532 //    This kind of interference is only resolved locally. If the clobbered
1533 //    lane value escapes the block, the join is aborted.
1534
1535 namespace {
1536 /// Track information about values in a single virtual register about to be
1537 /// joined. Objects of this class are always created in pairs - one for each
1538 /// side of the CoalescerPair (or one for each lane of a side of the coalescer
1539 /// pair)
1540 class JoinVals {
1541   /// Live range we work on.
1542   LiveRange &LR;
1543   /// (Main) register we work on.
1544   const unsigned Reg;
1545
1546   /// Reg (and therefore the values in this liverange) will end up as
1547   /// subregister SubIdx in the coalesced register. Either CP.DstIdx or
1548   /// CP.SrcIdx.
1549   const unsigned SubIdx;
1550   /// The LaneMask that this liverange will occupy the coalesced register. May
1551   /// be smaller than the lanemask produced by SubIdx when merging subranges.
1552   const unsigned LaneMask;
1553
1554   /// This is true when joining sub register ranges, false when joining main
1555   /// ranges.
1556   const bool SubRangeJoin;
1557   /// Whether the current LiveInterval tracks subregister liveness.
1558   const bool TrackSubRegLiveness;
1559
1560   /// Values that will be present in the final live range.
1561   SmallVectorImpl<VNInfo*> &NewVNInfo;
1562
1563   const CoalescerPair &CP;
1564   LiveIntervals *LIS;
1565   SlotIndexes *Indexes;
1566   const TargetRegisterInfo *TRI;
1567
1568   /// Value number assignments. Maps value numbers in LI to entries in
1569   /// NewVNInfo. This is suitable for passing to LiveInterval::join().
1570   SmallVector<int, 8> Assignments;
1571
1572   /// Conflict resolution for overlapping values.
1573   enum ConflictResolution {
1574     /// No overlap, simply keep this value.
1575     CR_Keep,
1576
1577     /// Merge this value into OtherVNI and erase the defining instruction.
1578     /// Used for IMPLICIT_DEF, coalescable copies, and copies from external
1579     /// values.
1580     CR_Erase,
1581
1582     /// Merge this value into OtherVNI but keep the defining instruction.
1583     /// This is for the special case where OtherVNI is defined by the same
1584     /// instruction.
1585     CR_Merge,
1586
1587     /// Keep this value, and have it replace OtherVNI where possible. This
1588     /// complicates value mapping since OtherVNI maps to two different values
1589     /// before and after this def.
1590     /// Used when clobbering undefined or dead lanes.
1591     CR_Replace,
1592
1593     /// Unresolved conflict. Visit later when all values have been mapped.
1594     CR_Unresolved,
1595
1596     /// Unresolvable conflict. Abort the join.
1597     CR_Impossible
1598   };
1599
1600   /// Per-value info for LI. The lane bit masks are all relative to the final
1601   /// joined register, so they can be compared directly between SrcReg and
1602   /// DstReg.
1603   struct Val {
1604     ConflictResolution Resolution;
1605
1606     /// Lanes written by this def, 0 for unanalyzed values.
1607     unsigned WriteLanes;
1608
1609     /// Lanes with defined values in this register. Other lanes are undef and
1610     /// safe to clobber.
1611     unsigned ValidLanes;
1612
1613     /// Value in LI being redefined by this def.
1614     VNInfo *RedefVNI;
1615
1616     /// Value in the other live range that overlaps this def, if any.
1617     VNInfo *OtherVNI;
1618
1619     /// Is this value an IMPLICIT_DEF that can be erased?
1620     ///
1621     /// IMPLICIT_DEF values should only exist at the end of a basic block that
1622     /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
1623     /// safely erased if they are overlapping a live value in the other live
1624     /// interval.
1625     ///
1626     /// Weird control flow graphs and incomplete PHI handling in
1627     /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
1628     /// longer live ranges. Such IMPLICIT_DEF values should be treated like
1629     /// normal values.
1630     bool ErasableImplicitDef;
1631
1632     /// True when the live range of this value will be pruned because of an
1633     /// overlapping CR_Replace value in the other live range.
1634     bool Pruned;
1635
1636     /// True once Pruned above has been computed.
1637     bool PrunedComputed;
1638
1639     Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1640             RedefVNI(nullptr), OtherVNI(nullptr), ErasableImplicitDef(false),
1641             Pruned(false), PrunedComputed(false) {}
1642
1643     bool isAnalyzed() const { return WriteLanes != 0; }
1644   };
1645
1646   /// One entry per value number in LI.
1647   SmallVector<Val, 8> Vals;
1648
1649   /// Compute the bitmask of lanes actually written by DefMI.
1650   /// Set Redef if there are any partial register definitions that depend on the
1651   /// previous value of the register.
1652   unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
1653
1654   /// Find the ultimate value that VNI was copied from.
1655   std::pair<const VNInfo*,unsigned> followCopyChain(const VNInfo *VNI) const;
1656
1657   bool valuesIdentical(VNInfo *Val0, VNInfo *Val1, const JoinVals &Other) const;
1658
1659   /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1660   /// Return a conflict resolution when possible, but leave the hard cases as
1661   /// CR_Unresolved.
1662   /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1663   /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1664   /// The recursion always goes upwards in the dominator tree, making loops
1665   /// impossible.
1666   ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1667
1668   /// Compute the value assignment for ValNo in RI.
1669   /// This may be called recursively by analyzeValue(), but never for a ValNo on
1670   /// the stack.
1671   void computeAssignment(unsigned ValNo, JoinVals &Other);
1672
1673   /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
1674   /// the extent of the tainted lanes in the block.
1675   ///
1676   /// Multiple values in Other.LR can be affected since partial redefinitions
1677   /// can preserve previously tainted lanes.
1678   ///
1679   ///   1 %dst = VLOAD           <-- Define all lanes in %dst
1680   ///   2 %src = FOO             <-- ValNo to be joined with %dst:ssub0
1681   ///   3 %dst:ssub1 = BAR       <-- Partial redef doesn't clear taint in ssub0
1682   ///   4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
1683   ///
1684   /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
1685   /// entry to TaintedVals.
1686   ///
1687   /// Returns false if the tainted lanes extend beyond the basic block.
1688   bool taintExtent(unsigned, unsigned, JoinVals&,
1689                    SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
1690
1691   /// Return true if MI uses any of the given Lanes from Reg.
1692   /// This does not include partial redefinitions of Reg.
1693   bool usesLanes(const MachineInstr *MI, unsigned, unsigned, unsigned) const;
1694
1695   /// Determine if ValNo is a copy of a value number in LR or Other.LR that will
1696   /// be pruned:
1697   ///
1698   ///   %dst = COPY %src
1699   ///   %src = COPY %dst  <-- This value to be pruned.
1700   ///   %dst = COPY %src  <-- This value is a copy of a pruned value.
1701   bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1702
1703 public:
1704   JoinVals(LiveRange &LR, unsigned Reg, unsigned SubIdx, unsigned LaneMask,
1705            SmallVectorImpl<VNInfo*> &newVNInfo, const CoalescerPair &cp,
1706            LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
1707            bool TrackSubRegLiveness)
1708     : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
1709       SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
1710       NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
1711       TRI(TRI), Assignments(LR.getNumValNums(), -1), Vals(LR.getNumValNums())
1712   {}
1713
1714   /// Analyze defs in LR and compute a value mapping in NewVNInfo.
1715   /// Returns false if any conflicts were impossible to resolve.
1716   bool mapValues(JoinVals &Other);
1717
1718   /// Try to resolve conflicts that require all values to be mapped.
1719   /// Returns false if any conflicts were impossible to resolve.
1720   bool resolveConflicts(JoinVals &Other);
1721
1722   /// Prune the live range of values in Other.LR where they would conflict with
1723   /// CR_Replace values in LR. Collect end points for restoring the live range
1724   /// after joining.
1725   void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
1726                    bool changeInstrs);
1727
1728   /// Removes subranges starting at copies that get removed. This sometimes
1729   /// happens when undefined subranges are copied around. These ranges contain
1730   /// no usefull information and can be removed.
1731   void pruneSubRegValues(LiveInterval &LI, unsigned &ShrinkMask);
1732
1733   /// Erase any machine instructions that have been coalesced away.
1734   /// Add erased instructions to ErasedInstrs.
1735   /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1736   /// the erased instrs.
1737   void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
1738                    SmallVectorImpl<unsigned> &ShrinkRegs);
1739
1740   /// Get the value assignments suitable for passing to LiveInterval::join.
1741   const int *getAssignments() const { return Assignments.data(); }
1742 };
1743 } // end anonymous namespace
1744
1745 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
1746   const {
1747   unsigned L = 0;
1748   for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1749     if (!MO->isReg() || MO->getReg() != Reg || !MO->isDef())
1750       continue;
1751     L |= TRI->getSubRegIndexLaneMask(
1752            TRI->composeSubRegIndices(SubIdx, MO->getSubReg()));
1753     if (MO->readsReg())
1754       Redef = true;
1755   }
1756   return L;
1757 }
1758
1759 std::pair<const VNInfo*, unsigned> JoinVals::followCopyChain(
1760     const VNInfo *VNI) const {
1761   unsigned Reg = this->Reg;
1762
1763   while (!VNI->isPHIDef()) {
1764     SlotIndex Def = VNI->def;
1765     MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1766     assert(MI && "No defining instruction");
1767     if (!MI->isFullCopy())
1768       return std::make_pair(VNI, Reg);
1769     unsigned SrcReg = MI->getOperand(1).getReg();
1770     if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1771       return std::make_pair(VNI, Reg);
1772
1773     const LiveInterval &LI = LIS->getInterval(SrcReg);
1774     const VNInfo *ValueIn;
1775     // No subrange involved.
1776     if (!SubRangeJoin || !LI.hasSubRanges()) {
1777       LiveQueryResult LRQ = LI.Query(Def);
1778       ValueIn = LRQ.valueIn();
1779     } else {
1780       // Query subranges. Pick the first matching one.
1781       ValueIn = nullptr;
1782       for (const LiveInterval::SubRange &S : LI.subranges()) {
1783         // Transform lanemask to a mask in the joined live interval.
1784         unsigned SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
1785         if ((SMask & LaneMask) == 0)
1786           continue;
1787         LiveQueryResult LRQ = S.Query(Def);
1788         ValueIn = LRQ.valueIn();
1789         break;
1790       }
1791     }
1792     if (ValueIn == nullptr)
1793       break;
1794     VNI = ValueIn;
1795     Reg = SrcReg;
1796   }
1797   return std::make_pair(VNI, Reg);
1798 }
1799
1800 bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
1801                                const JoinVals &Other) const {
1802   const VNInfo *Orig0;
1803   unsigned Reg0;
1804   std::tie(Orig0, Reg0) = followCopyChain(Value0);
1805   if (Orig0 == Value1)
1806     return true;
1807
1808   const VNInfo *Orig1;
1809   unsigned Reg1;
1810   std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
1811
1812   // The values are equal if they are defined at the same place and use the
1813   // same register. Note that we cannot compare VNInfos directly as some of
1814   // them might be from a copy created in mergeSubRangeInto()  while the other
1815   // is from the original LiveInterval.
1816   return Orig0->def == Orig1->def && Reg0 == Reg1;
1817 }
1818
1819 JoinVals::ConflictResolution
1820 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1821   Val &V = Vals[ValNo];
1822   assert(!V.isAnalyzed() && "Value has already been analyzed!");
1823   VNInfo *VNI = LR.getValNumInfo(ValNo);
1824   if (VNI->isUnused()) {
1825     V.WriteLanes = ~0u;
1826     return CR_Keep;
1827   }
1828
1829   // Get the instruction defining this value, compute the lanes written.
1830   const MachineInstr *DefMI = nullptr;
1831   if (VNI->isPHIDef()) {
1832     // Conservatively assume that all lanes in a PHI are valid.
1833     unsigned Lanes = SubRangeJoin ? 1 : TRI->getSubRegIndexLaneMask(SubIdx);
1834     V.ValidLanes = V.WriteLanes = Lanes;
1835   } else {
1836     DefMI = Indexes->getInstructionFromIndex(VNI->def);
1837     assert(DefMI != nullptr);
1838     if (SubRangeJoin) {
1839       // We don't care about the lanes when joining subregister ranges.
1840       V.ValidLanes = V.WriteLanes = 1;
1841     } else {
1842       bool Redef = false;
1843       V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1844
1845       // If this is a read-modify-write instruction, there may be more valid
1846       // lanes than the ones written by this instruction.
1847       // This only covers partial redef operands. DefMI may have normal use
1848       // operands reading the register. They don't contribute valid lanes.
1849       //
1850       // This adds ssub1 to the set of valid lanes in %src:
1851       //
1852       //   %src:ssub1<def> = FOO
1853       //
1854       // This leaves only ssub1 valid, making any other lanes undef:
1855       //
1856       //   %src:ssub1<def,read-undef> = FOO %src:ssub2
1857       //
1858       // The <read-undef> flag on the def operand means that old lane values are
1859       // not important.
1860       if (Redef) {
1861         V.RedefVNI = LR.Query(VNI->def).valueIn();
1862         assert((TrackSubRegLiveness || V.RedefVNI) &&
1863                "Instruction is reading nonexistent value");
1864         if (V.RedefVNI != nullptr) {
1865           computeAssignment(V.RedefVNI->id, Other);
1866           V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1867         }
1868       }
1869
1870       // An IMPLICIT_DEF writes undef values.
1871       if (DefMI->isImplicitDef()) {
1872         // We normally expect IMPLICIT_DEF values to be live only until the end
1873         // of their block. If the value is really live longer and gets pruned in
1874         // another block, this flag is cleared again.
1875         V.ErasableImplicitDef = true;
1876         V.ValidLanes &= ~V.WriteLanes;
1877       }
1878     }
1879   }
1880
1881   // Find the value in Other that overlaps VNI->def, if any.
1882   LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
1883
1884   // It is possible that both values are defined by the same instruction, or
1885   // the values are PHIs defined in the same block. When that happens, the two
1886   // values should be merged into one, but not into any preceding value.
1887   // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1888   if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1889     assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1890
1891     // One value stays, the other is merged. Keep the earlier one, or the first
1892     // one we see.
1893     if (OtherVNI->def < VNI->def)
1894       Other.computeAssignment(OtherVNI->id, *this);
1895     else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1896       // This is an early-clobber def overlapping a live-in value in the other
1897       // register. Not mergeable.
1898       V.OtherVNI = OtherLRQ.valueIn();
1899       return CR_Impossible;
1900     }
1901     V.OtherVNI = OtherVNI;
1902     Val &OtherV = Other.Vals[OtherVNI->id];
1903     // Keep this value, check for conflicts when analyzing OtherVNI.
1904     if (!OtherV.isAnalyzed())
1905       return CR_Keep;
1906     // Both sides have been analyzed now.
1907     // Allow overlapping PHI values. Any real interference would show up in a
1908     // predecessor, the PHI itself can't introduce any conflicts.
1909     if (VNI->isPHIDef())
1910       return CR_Merge;
1911     if (V.ValidLanes & OtherV.ValidLanes)
1912       // Overlapping lanes can't be resolved.
1913       return CR_Impossible;
1914     else
1915       return CR_Merge;
1916   }
1917
1918   // No simultaneous def. Is Other live at the def?
1919   V.OtherVNI = OtherLRQ.valueIn();
1920   if (!V.OtherVNI)
1921     // No overlap, no conflict.
1922     return CR_Keep;
1923
1924   assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1925
1926   // We have overlapping values, or possibly a kill of Other.
1927   // Recursively compute assignments up the dominator tree.
1928   Other.computeAssignment(V.OtherVNI->id, *this);
1929   Val &OtherV = Other.Vals[V.OtherVNI->id];
1930
1931   // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
1932   // This shouldn't normally happen, but ProcessImplicitDefs can leave such
1933   // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
1934   // technically.
1935   //
1936   // WHen it happens, treat that IMPLICIT_DEF as a normal value, and don't try
1937   // to erase the IMPLICIT_DEF instruction.
1938   if (OtherV.ErasableImplicitDef && DefMI &&
1939       DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
1940     DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
1941                  << " extends into BB#" << DefMI->getParent()->getNumber()
1942                  << ", keeping it.\n");
1943     OtherV.ErasableImplicitDef = false;
1944   }
1945
1946   // Allow overlapping PHI values. Any real interference would show up in a
1947   // predecessor, the PHI itself can't introduce any conflicts.
1948   if (VNI->isPHIDef())
1949     return CR_Replace;
1950
1951   // Check for simple erasable conflicts.
1952   if (DefMI->isImplicitDef()) {
1953     // We need the def for the subregister if there is nothing else live at the
1954     // subrange at this point.
1955     if (TrackSubRegLiveness
1956         && (V.WriteLanes & (OtherV.ValidLanes | OtherV.WriteLanes)) == 0)
1957       return CR_Replace;
1958     return CR_Erase;
1959   }
1960
1961   // Include the non-conflict where DefMI is a coalescable copy that kills
1962   // OtherVNI. We still want the copy erased and value numbers merged.
1963   if (CP.isCoalescable(DefMI)) {
1964     // Some of the lanes copied from OtherVNI may be undef, making them undef
1965     // here too.
1966     V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1967     return CR_Erase;
1968   }
1969
1970   // This may not be a real conflict if DefMI simply kills Other and defines
1971   // VNI.
1972   if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1973     return CR_Keep;
1974
1975   // Handle the case where VNI and OtherVNI can be proven to be identical:
1976   //
1977   //   %other = COPY %ext
1978   //   %this  = COPY %ext <-- Erase this copy
1979   //
1980   if (DefMI->isFullCopy() && !CP.isPartial()
1981       && valuesIdentical(VNI, V.OtherVNI, Other))
1982     return CR_Erase;
1983
1984   // If the lanes written by this instruction were all undef in OtherVNI, it is
1985   // still safe to join the live ranges. This can't be done with a simple value
1986   // mapping, though - OtherVNI will map to multiple values:
1987   //
1988   //   1 %dst:ssub0 = FOO                <-- OtherVNI
1989   //   2 %src = BAR                      <-- VNI
1990   //   3 %dst:ssub1 = COPY %src<kill>    <-- Eliminate this copy.
1991   //   4 BAZ %dst<kill>
1992   //   5 QUUX %src<kill>
1993   //
1994   // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
1995   // handles this complex value mapping.
1996   if ((V.WriteLanes & OtherV.ValidLanes) == 0)
1997     return CR_Replace;
1998
1999   // If the other live range is killed by DefMI and the live ranges are still
2000   // overlapping, it must be because we're looking at an early clobber def:
2001   //
2002   //   %dst<def,early-clobber> = ASM %src<kill>
2003   //
2004   // In this case, it is illegal to merge the two live ranges since the early
2005   // clobber def would clobber %src before it was read.
2006   if (OtherLRQ.isKill()) {
2007     // This case where the def doesn't overlap the kill is handled above.
2008     assert(VNI->def.isEarlyClobber() &&
2009            "Only early clobber defs can overlap a kill");
2010     return CR_Impossible;
2011   }
2012
2013   // VNI is clobbering live lanes in OtherVNI, but there is still the
2014   // possibility that no instructions actually read the clobbered lanes.
2015   // If we're clobbering all the lanes in OtherVNI, at least one must be read.
2016   // Otherwise Other.RI wouldn't be live here.
2017   if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
2018     return CR_Impossible;
2019
2020   // We need to verify that no instructions are reading the clobbered lanes. To
2021   // save compile time, we'll only check that locally. Don't allow the tainted
2022   // value to escape the basic block.
2023   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2024   if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
2025     return CR_Impossible;
2026
2027   // There are still some things that could go wrong besides clobbered lanes
2028   // being read, for example OtherVNI may be only partially redefined in MBB,
2029   // and some clobbered lanes could escape the block. Save this analysis for
2030   // resolveConflicts() when all values have been mapped. We need to know
2031   // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
2032   // that now - the recursive analyzeValue() calls must go upwards in the
2033   // dominator tree.
2034   return CR_Unresolved;
2035 }
2036
2037 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
2038   Val &V = Vals[ValNo];
2039   if (V.isAnalyzed()) {
2040     // Recursion should always move up the dominator tree, so ValNo is not
2041     // supposed to reappear before it has been assigned.
2042     assert(Assignments[ValNo] != -1 && "Bad recursion?");
2043     return;
2044   }
2045   switch ((V.Resolution = analyzeValue(ValNo, Other))) {
2046   case CR_Erase:
2047   case CR_Merge:
2048     // Merge this ValNo into OtherVNI.
2049     assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
2050     assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
2051     Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
2052     DEBUG(dbgs() << "\t\tmerge " << PrintReg(Reg) << ':' << ValNo << '@'
2053                  << LR.getValNumInfo(ValNo)->def << " into "
2054                  << PrintReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
2055                  << V.OtherVNI->def << " --> @"
2056                  << NewVNInfo[Assignments[ValNo]]->def << '\n');
2057     break;
2058   case CR_Replace:
2059   case CR_Unresolved: {
2060     // The other value is going to be pruned if this join is successful.
2061     assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
2062     Val &OtherV = Other.Vals[V.OtherVNI->id];
2063     // We cannot erase an IMPLICIT_DEF if we don't have valid values for all
2064     // its lanes.
2065     if ((OtherV.WriteLanes & ~V.ValidLanes) != 0 && TrackSubRegLiveness)
2066       OtherV.ErasableImplicitDef = false;
2067     OtherV.Pruned = true;
2068   }
2069     // Fall through.
2070   default:
2071     // This value number needs to go in the final joined live range.
2072     Assignments[ValNo] = NewVNInfo.size();
2073     NewVNInfo.push_back(LR.getValNumInfo(ValNo));
2074     break;
2075   }
2076 }
2077
2078 bool JoinVals::mapValues(JoinVals &Other) {
2079   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2080     computeAssignment(i, Other);
2081     if (Vals[i].Resolution == CR_Impossible) {
2082       DEBUG(dbgs() << "\t\tinterference at " << PrintReg(Reg) << ':' << i
2083                    << '@' << LR.getValNumInfo(i)->def << '\n');
2084       return false;
2085     }
2086   }
2087   return true;
2088 }
2089
2090 bool JoinVals::
2091 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
2092             SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
2093   VNInfo *VNI = LR.getValNumInfo(ValNo);
2094   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2095   SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
2096
2097   // Scan Other.LR from VNI.def to MBBEnd.
2098   LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
2099   assert(OtherI != Other.LR.end() && "No conflict?");
2100   do {
2101     // OtherI is pointing to a tainted value. Abort the join if the tainted
2102     // lanes escape the block.
2103     SlotIndex End = OtherI->end;
2104     if (End >= MBBEnd) {
2105       DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.Reg) << ':'
2106                    << OtherI->valno->id << '@' << OtherI->start << '\n');
2107       return false;
2108     }
2109     DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.Reg) << ':'
2110                  << OtherI->valno->id << '@' << OtherI->start
2111                  << " to " << End << '\n');
2112     // A dead def is not a problem.
2113     if (End.isDead())
2114       break;
2115     TaintExtent.push_back(std::make_pair(End, TaintedLanes));
2116
2117     // Check for another def in the MBB.
2118     if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
2119       break;
2120
2121     // Lanes written by the new def are no longer tainted.
2122     const Val &OV = Other.Vals[OtherI->valno->id];
2123     TaintedLanes &= ~OV.WriteLanes;
2124     if (!OV.RedefVNI)
2125       break;
2126   } while (TaintedLanes);
2127   return true;
2128 }
2129
2130 bool JoinVals::usesLanes(const MachineInstr *MI, unsigned Reg, unsigned SubIdx,
2131                          unsigned Lanes) const {
2132   if (MI->isDebugValue())
2133     return false;
2134   for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
2135     if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
2136       continue;
2137     if (!MO->readsReg())
2138       continue;
2139     if (Lanes & TRI->getSubRegIndexLaneMask(
2140                   TRI->composeSubRegIndices(SubIdx, MO->getSubReg())))
2141       return true;
2142   }
2143   return false;
2144 }
2145
2146 bool JoinVals::resolveConflicts(JoinVals &Other) {
2147   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2148     Val &V = Vals[i];
2149     assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
2150     if (V.Resolution != CR_Unresolved)
2151       continue;
2152     DEBUG(dbgs() << "\t\tconflict at " << PrintReg(Reg) << ':' << i
2153                  << '@' << LR.getValNumInfo(i)->def << '\n');
2154     if (SubRangeJoin)
2155       return false;
2156
2157     ++NumLaneConflicts;
2158     assert(V.OtherVNI && "Inconsistent conflict resolution.");
2159     VNInfo *VNI = LR.getValNumInfo(i);
2160     const Val &OtherV = Other.Vals[V.OtherVNI->id];
2161
2162     // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
2163     // join, those lanes will be tainted with a wrong value. Get the extent of
2164     // the tainted lanes.
2165     unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
2166     SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
2167     if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
2168       // Tainted lanes would extend beyond the basic block.
2169       return false;
2170
2171     assert(!TaintExtent.empty() && "There should be at least one conflict.");
2172
2173     // Now look at the instructions from VNI->def to TaintExtent (inclusive).
2174     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2175     MachineBasicBlock::iterator MI = MBB->begin();
2176     if (!VNI->isPHIDef()) {
2177       MI = Indexes->getInstructionFromIndex(VNI->def);
2178       // No need to check the instruction defining VNI for reads.
2179       ++MI;
2180     }
2181     assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
2182            "Interference ends on VNI->def. Should have been handled earlier");
2183     MachineInstr *LastMI =
2184       Indexes->getInstructionFromIndex(TaintExtent.front().first);
2185     assert(LastMI && "Range must end at a proper instruction");
2186     unsigned TaintNum = 0;
2187     for(;;) {
2188       assert(MI != MBB->end() && "Bad LastMI");
2189       if (usesLanes(MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
2190         DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
2191         return false;
2192       }
2193       // LastMI is the last instruction to use the current value.
2194       if (&*MI == LastMI) {
2195         if (++TaintNum == TaintExtent.size())
2196           break;
2197         LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
2198         assert(LastMI && "Range must end at a proper instruction");
2199         TaintedLanes = TaintExtent[TaintNum].second;
2200       }
2201       ++MI;
2202     }
2203
2204     // The tainted lanes are unused.
2205     V.Resolution = CR_Replace;
2206     ++NumLaneResolves;
2207   }
2208   return true;
2209 }
2210
2211 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
2212   Val &V = Vals[ValNo];
2213   if (V.Pruned || V.PrunedComputed)
2214     return V.Pruned;
2215
2216   if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
2217     return V.Pruned;
2218
2219   // Follow copies up the dominator tree and check if any intermediate value
2220   // has been pruned.
2221   V.PrunedComputed = true;
2222   V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
2223   return V.Pruned;
2224 }
2225
2226 void JoinVals::pruneValues(JoinVals &Other,
2227                            SmallVectorImpl<SlotIndex> &EndPoints,
2228                            bool changeInstrs) {
2229   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2230     SlotIndex Def = LR.getValNumInfo(i)->def;
2231     switch (Vals[i].Resolution) {
2232     case CR_Keep:
2233       break;
2234     case CR_Replace: {
2235       // This value takes precedence over the value in Other.LR.
2236       LIS->pruneValue(Other.LR, Def, &EndPoints);
2237       // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
2238       // instructions are only inserted to provide a live-out value for PHI
2239       // predecessors, so the instruction should simply go away once its value
2240       // has been replaced.
2241       Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
2242       bool EraseImpDef = OtherV.ErasableImplicitDef &&
2243                          OtherV.Resolution == CR_Keep;
2244       if (!Def.isBlock()) {
2245         if (changeInstrs) {
2246           // Remove <def,read-undef> flags. This def is now a partial redef.
2247           // Also remove <def,dead> flags since the joined live range will
2248           // continue past this instruction.
2249           for (MIOperands MO(Indexes->getInstructionFromIndex(Def));
2250                MO.isValid(); ++MO) {
2251             if (MO->isReg() && MO->isDef() && MO->getReg() == Reg) {
2252               MO->setIsUndef(EraseImpDef);
2253               MO->setIsDead(false);
2254             }
2255           }
2256         }
2257         // This value will reach instructions below, but we need to make sure
2258         // the live range also reaches the instruction at Def.
2259         if (!EraseImpDef)
2260           EndPoints.push_back(Def);
2261       }
2262       DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.Reg) << " at " << Def
2263                    << ": " << Other.LR << '\n');
2264       break;
2265     }
2266     case CR_Erase:
2267     case CR_Merge:
2268       if (isPrunedValue(i, Other)) {
2269         // This value is ultimately a copy of a pruned value in LR or Other.LR.
2270         // We can no longer trust the value mapping computed by
2271         // computeAssignment(), the value that was originally copied could have
2272         // been replaced.
2273         LIS->pruneValue(LR, Def, &EndPoints);
2274         DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(Reg) << " at "
2275                      << Def << ": " << LR << '\n');
2276       }
2277       break;
2278     case CR_Unresolved:
2279     case CR_Impossible:
2280       llvm_unreachable("Unresolved conflicts");
2281     }
2282   }
2283 }
2284
2285 void JoinVals::pruneSubRegValues(LiveInterval &LI, unsigned &ShrinkMask)
2286 {
2287   // Look for values being erased.
2288   bool DidPrune = false;
2289   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2290     if (Vals[i].Resolution != CR_Erase)
2291       continue;
2292
2293     // Check subranges at the point where the copy will be removed.
2294     SlotIndex Def = LR.getValNumInfo(i)->def;
2295     for (LiveInterval::SubRange &S : LI.subranges()) {
2296       LiveQueryResult Q = S.Query(Def);
2297
2298       // If a subrange starts at the copy then an undefined value has been
2299       // copied and we must remove that subrange value as well.
2300       VNInfo *ValueOut = Q.valueOutOrDead();
2301       if (ValueOut != nullptr && Q.valueIn() == nullptr) {
2302         DEBUG(dbgs() << "\t\tPrune sublane " << format("%04X", S.LaneMask)
2303                      << " at " << Def << "\n");
2304         LIS->pruneValue(S, Def, nullptr);
2305         DidPrune = true;
2306         // Mark value number as unused.
2307         ValueOut->markUnused();
2308         continue;
2309       }
2310       // If a subrange ends at the copy, then a value was copied but only
2311       // partially used later. Shrink the subregister range apropriately.
2312       if (Q.valueIn() != nullptr && Q.valueOut() == nullptr) {
2313         DEBUG(dbgs() << "\t\tDead uses at sublane "
2314                      << format("%04X", S.LaneMask) << " at " << Def << "\n");
2315         ShrinkMask |= S.LaneMask;
2316       }
2317     }
2318   }
2319   if (DidPrune)
2320     LI.removeEmptySubRanges();
2321 }
2322
2323 void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
2324                            SmallVectorImpl<unsigned> &ShrinkRegs) {
2325   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2326     // Get the def location before markUnused() below invalidates it.
2327     SlotIndex Def = LR.getValNumInfo(i)->def;
2328     switch (Vals[i].Resolution) {
2329     case CR_Keep: {
2330       // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
2331       // longer. The IMPLICIT_DEF instructions are only inserted by
2332       // PHIElimination to guarantee that all PHI predecessors have a value.
2333       if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
2334         break;
2335       // Remove value number i from LR.
2336       VNInfo *VNI = LR.getValNumInfo(i);
2337       LR.removeValNo(VNI);
2338       // Note that this VNInfo is reused and still referenced in NewVNInfo,
2339       // make it appear like an unused value number.
2340       VNI->markUnused();
2341       DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n');
2342       // FALL THROUGH.
2343     }
2344
2345     case CR_Erase: {
2346       MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2347       assert(MI && "No instruction to erase");
2348       if (MI->isCopy()) {
2349         unsigned Reg = MI->getOperand(1).getReg();
2350         if (TargetRegisterInfo::isVirtualRegister(Reg) &&
2351             Reg != CP.getSrcReg() && Reg != CP.getDstReg())
2352           ShrinkRegs.push_back(Reg);
2353       }
2354       ErasedInstrs.insert(MI);
2355       DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
2356       LIS->RemoveMachineInstrFromMaps(MI);
2357       MI->eraseFromParent();
2358       break;
2359     }
2360     default:
2361       break;
2362     }
2363   }
2364 }
2365
2366 void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
2367                                          unsigned LaneMask,
2368                                          const CoalescerPair &CP) {
2369   SmallVector<VNInfo*, 16> NewVNInfo;
2370   JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask,
2371                    NewVNInfo, CP, LIS, TRI, true, true);
2372   JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
2373                    NewVNInfo, CP, LIS, TRI, true, true);
2374
2375   // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
2376   // Conflicts should already be resolved so the mapping/resolution should
2377   // always succeed.
2378   if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
2379     llvm_unreachable("Can't join subrange although main ranges are compatible");
2380   if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
2381     llvm_unreachable("Can't join subrange although main ranges are compatible");
2382
2383   // The merging algorithm in LiveInterval::join() can't handle conflicting
2384   // value mappings, so we need to remove any live ranges that overlap a
2385   // CR_Replace resolution. Collect a set of end points that can be used to
2386   // restore the live range after joining.
2387   SmallVector<SlotIndex, 8> EndPoints;
2388   LHSVals.pruneValues(RHSVals, EndPoints, false);
2389   RHSVals.pruneValues(LHSVals, EndPoints, false);
2390
2391   LRange.verify();
2392   RRange.verify();
2393
2394   // Join RRange into LHS.
2395   LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
2396               NewVNInfo);
2397
2398   DEBUG(dbgs() << "\t\tjoined lanes: " << LRange << "\n");
2399   if (EndPoints.empty())
2400     return;
2401
2402   // Recompute the parts of the live range we had to remove because of
2403   // CR_Replace conflicts.
2404   DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2405                << " points: " << LRange << '\n');
2406   LIS->extendToIndices(LRange, EndPoints);
2407 }
2408
2409 void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
2410                                           const LiveRange &ToMerge,
2411                                           unsigned LaneMask, CoalescerPair &CP) {
2412   BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2413   for (LiveInterval::SubRange &R : LI.subranges()) {
2414     unsigned RMask = R.LaneMask;
2415     // LaneMask of subregisters common to subrange R and ToMerge.
2416     unsigned Common = RMask & LaneMask;
2417     // There is nothing to do without common subregs.
2418     if (Common == 0)
2419       continue;
2420
2421     DEBUG(dbgs() << format("\t\tCopy+Merge %04X into %04X\n", RMask, Common));
2422     // LaneMask of subregisters contained in the R range but not in ToMerge,
2423     // they have to split into their own subrange.
2424     unsigned LRest = RMask & ~LaneMask;
2425     LiveInterval::SubRange *CommonRange;
2426     if (LRest != 0) {
2427       R.LaneMask = LRest;
2428       DEBUG(dbgs() << format("\t\tReduce Lane to %04X\n", LRest));
2429       // Duplicate SubRange for newly merged common stuff.
2430       CommonRange = LI.createSubRangeFrom(Allocator, Common, R);
2431     } else {
2432       // Reuse the existing range.
2433       R.LaneMask = Common;
2434       CommonRange = &R;
2435     }
2436     LiveRange RangeCopy(ToMerge, Allocator);
2437     joinSubRegRanges(*CommonRange, RangeCopy, Common, CP);
2438     LaneMask &= ~RMask;
2439   }
2440
2441   if (LaneMask != 0) {
2442     DEBUG(dbgs() << format("\t\tNew Lane %04X\n", LaneMask));
2443     LI.createSubRangeFrom(Allocator, LaneMask, ToMerge);
2444   }
2445 }
2446
2447 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
2448   SmallVector<VNInfo*, 16> NewVNInfo;
2449   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
2450   LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
2451   bool TrackSubRegLiveness = MRI->tracksSubRegLiveness();
2452   JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), 0, NewVNInfo, CP, LIS,
2453                    TRI, false, TrackSubRegLiveness);
2454   JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), 0, NewVNInfo, CP, LIS,
2455                    TRI, false, TrackSubRegLiveness);
2456
2457   DEBUG(dbgs() << "\t\tRHS = " << RHS
2458                << "\n\t\tLHS = " << LHS
2459                << '\n');
2460
2461   // First compute NewVNInfo and the simple value mappings.
2462   // Detect impossible conflicts early.
2463   if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
2464     return false;
2465
2466   // Some conflicts can only be resolved after all values have been mapped.
2467   if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
2468     return false;
2469
2470   // All clear, the live ranges can be merged.
2471   if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
2472     BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2473
2474     // Transform lanemasks from the LHS to masks in the coalesced register and
2475     // create initial subranges if necessary.
2476     unsigned DstIdx = CP.getDstIdx();
2477     if (!LHS.hasSubRanges()) {
2478       unsigned Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
2479                                   : TRI->getSubRegIndexLaneMask(DstIdx);
2480       // LHS must support subregs or we wouldn't be in this codepath.
2481       assert(Mask != 0);
2482       LHS.createSubRangeFrom(Allocator, Mask, LHS);
2483     } else if (DstIdx != 0) {
2484       // Transform LHS lanemasks to new register class if necessary.
2485       for (LiveInterval::SubRange &R : LHS.subranges()) {
2486         unsigned Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
2487         R.LaneMask = Mask;
2488       }
2489     }
2490     DEBUG(dbgs() << "\t\tLHST = " << PrintReg(CP.getDstReg())
2491                  << ' ' << LHS << '\n');
2492
2493     // Determine lanemasks of RHS in the coalesced register and merge subranges.
2494     unsigned SrcIdx = CP.getSrcIdx();
2495     if (!RHS.hasSubRanges()) {
2496       unsigned Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
2497                                   : TRI->getSubRegIndexLaneMask(SrcIdx);
2498       mergeSubRangeInto(LHS, RHS, Mask, CP);
2499     } else {
2500       // Pair up subranges and merge.
2501       for (LiveInterval::SubRange &R : RHS.subranges()) {
2502         unsigned Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
2503         mergeSubRangeInto(LHS, R, Mask, CP);
2504       }
2505     }
2506
2507     DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
2508
2509     LHSVals.pruneSubRegValues(LHS, ShrinkMask);
2510     RHSVals.pruneSubRegValues(LHS, ShrinkMask);
2511   }
2512
2513   // The merging algorithm in LiveInterval::join() can't handle conflicting
2514   // value mappings, so we need to remove any live ranges that overlap a
2515   // CR_Replace resolution. Collect a set of end points that can be used to
2516   // restore the live range after joining.
2517   SmallVector<SlotIndex, 8> EndPoints;
2518   LHSVals.pruneValues(RHSVals, EndPoints, true);
2519   RHSVals.pruneValues(LHSVals, EndPoints, true);
2520
2521   // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
2522   // registers to require trimming.
2523   SmallVector<unsigned, 8> ShrinkRegs;
2524   LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2525   RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2526   while (!ShrinkRegs.empty())
2527     LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
2528
2529   // Join RHS into LHS.
2530   LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
2531
2532   // Kill flags are going to be wrong if the live ranges were overlapping.
2533   // Eventually, we should simply clear all kill flags when computing live
2534   // ranges. They are reinserted after register allocation.
2535   MRI->clearKillFlags(LHS.reg);
2536   MRI->clearKillFlags(RHS.reg);
2537
2538   if (!EndPoints.empty()) {
2539     // Recompute the parts of the live range we had to remove because of
2540     // CR_Replace conflicts.
2541     DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2542                  << " points: " << LHS << '\n');
2543     LIS->extendToIndices((LiveRange&)LHS, EndPoints);
2544   }
2545
2546   return true;
2547 }
2548
2549 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
2550   return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
2551 }
2552
2553 namespace {
2554 /// Information concerning MBB coalescing priority.
2555 struct MBBPriorityInfo {
2556   MachineBasicBlock *MBB;
2557   unsigned Depth;
2558   bool IsSplit;
2559
2560   MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
2561     : MBB(mbb), Depth(depth), IsSplit(issplit) {}
2562 };
2563 }
2564
2565 /// C-style comparator that sorts first based on the loop depth of the basic
2566 /// block (the unsigned), and then on the MBB number.
2567 ///
2568 /// EnableGlobalCopies assumes that the primary sort key is loop depth.
2569 static int compareMBBPriority(const MBBPriorityInfo *LHS,
2570                               const MBBPriorityInfo *RHS) {
2571   // Deeper loops first
2572   if (LHS->Depth != RHS->Depth)
2573     return LHS->Depth > RHS->Depth ? -1 : 1;
2574
2575   // Try to unsplit critical edges next.
2576   if (LHS->IsSplit != RHS->IsSplit)
2577     return LHS->IsSplit ? -1 : 1;
2578
2579   // Prefer blocks that are more connected in the CFG. This takes care of
2580   // the most difficult copies first while intervals are short.
2581   unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
2582   unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
2583   if (cl != cr)
2584     return cl > cr ? -1 : 1;
2585
2586   // As a last resort, sort by block number.
2587   return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
2588 }
2589
2590 /// \returns true if the given copy uses or defines a local live range.
2591 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
2592   if (!Copy->isCopy())
2593     return false;
2594
2595   if (Copy->getOperand(1).isUndef())
2596     return false;
2597
2598   unsigned SrcReg = Copy->getOperand(1).getReg();
2599   unsigned DstReg = Copy->getOperand(0).getReg();
2600   if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
2601       || TargetRegisterInfo::isPhysicalRegister(DstReg))
2602     return false;
2603
2604   return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
2605     || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
2606 }
2607
2608 bool RegisterCoalescer::
2609 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
2610   bool Progress = false;
2611   for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
2612     if (!CurrList[i])
2613       continue;
2614     // Skip instruction pointers that have already been erased, for example by
2615     // dead code elimination.
2616     if (ErasedInstrs.erase(CurrList[i])) {
2617       CurrList[i] = nullptr;
2618       continue;
2619     }
2620     bool Again = false;
2621     bool Success = joinCopy(CurrList[i], Again);
2622     Progress |= Success;
2623     if (Success || !Again)
2624       CurrList[i] = nullptr;
2625   }
2626   return Progress;
2627 }
2628
2629 void
2630 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2631   DEBUG(dbgs() << MBB->getName() << ":\n");
2632
2633   // Collect all copy-like instructions in MBB. Don't start coalescing anything
2634   // yet, it might invalidate the iterator.
2635   const unsigned PrevSize = WorkList.size();
2636   if (JoinGlobalCopies) {
2637     // Coalesce copies bottom-up to coalesce local defs before local uses. They
2638     // are not inherently easier to resolve, but slightly preferable until we
2639     // have local live range splitting. In particular this is required by
2640     // cmp+jmp macro fusion.
2641     for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2642          MII != E; ++MII) {
2643       if (!MII->isCopyLike())
2644         continue;
2645       if (isLocalCopy(&(*MII), LIS))
2646         LocalWorkList.push_back(&(*MII));
2647       else
2648         WorkList.push_back(&(*MII));
2649     }
2650   }
2651   else {
2652      for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2653           MII != E; ++MII)
2654        if (MII->isCopyLike())
2655          WorkList.push_back(MII);
2656   }
2657   // Try coalescing the collected copies immediately, and remove the nulls.
2658   // This prevents the WorkList from getting too large since most copies are
2659   // joinable on the first attempt.
2660   MutableArrayRef<MachineInstr*>
2661     CurrList(WorkList.begin() + PrevSize, WorkList.end());
2662   if (copyCoalesceWorkList(CurrList))
2663     WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2664                                (MachineInstr*)nullptr), WorkList.end());
2665 }
2666
2667 void RegisterCoalescer::coalesceLocals() {
2668   copyCoalesceWorkList(LocalWorkList);
2669   for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
2670     if (LocalWorkList[j])
2671       WorkList.push_back(LocalWorkList[j]);
2672   }
2673   LocalWorkList.clear();
2674 }
2675
2676 void RegisterCoalescer::joinAllIntervals() {
2677   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2678   assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
2679
2680   std::vector<MBBPriorityInfo> MBBs;
2681   MBBs.reserve(MF->size());
2682   for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2683     MachineBasicBlock *MBB = I;
2684     MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
2685                                    JoinSplitEdges && isSplitEdge(MBB)));
2686   }
2687   array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
2688
2689   // Coalesce intervals in MBB priority order.
2690   unsigned CurrDepth = UINT_MAX;
2691   for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
2692     // Try coalescing the collected local copies for deeper loops.
2693     if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
2694       coalesceLocals();
2695       CurrDepth = MBBs[i].Depth;
2696     }
2697     copyCoalesceInMBB(MBBs[i].MBB);
2698   }
2699   coalesceLocals();
2700
2701   // Joining intervals can allow other intervals to be joined.  Iteratively join
2702   // until we make no progress.
2703   while (copyCoalesceWorkList(WorkList))
2704     /* empty */ ;
2705 }
2706
2707 void RegisterCoalescer::releaseMemory() {
2708   ErasedInstrs.clear();
2709   WorkList.clear();
2710   DeadDefs.clear();
2711   InflateRegs.clear();
2712 }
2713
2714 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2715   MF = &fn;
2716   MRI = &fn.getRegInfo();
2717   TM = &fn.getTarget();
2718   const TargetSubtargetInfo &STI = fn.getSubtarget();
2719   TRI = STI.getRegisterInfo();
2720   TII = STI.getInstrInfo();
2721   LIS = &getAnalysis<LiveIntervals>();
2722   AA = &getAnalysis<AliasAnalysis>();
2723   Loops = &getAnalysis<MachineLoopInfo>();
2724   if (EnableGlobalCopies == cl::BOU_UNSET)
2725     JoinGlobalCopies = STI.useMachineScheduler();
2726   else
2727     JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
2728
2729   // The MachineScheduler does not currently require JoinSplitEdges. This will
2730   // either be enabled unconditionally or replaced by a more general live range
2731   // splitting optimization.
2732   JoinSplitEdges = EnableJoinSplits;
2733
2734   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2735                << "********** Function: " << MF->getName() << '\n');
2736
2737   if (VerifyCoalescing)
2738     MF->verify(this, "Before register coalescing");
2739
2740   RegClassInfo.runOnMachineFunction(fn);
2741
2742   // Join (coalesce) intervals if requested.
2743   if (EnableJoining)
2744     joinAllIntervals();
2745
2746   // After deleting a lot of copies, register classes may be less constrained.
2747   // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2748   // DPR inflation.
2749   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2750   InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2751                     InflateRegs.end());
2752   DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2753   for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2754     unsigned Reg = InflateRegs[i];
2755     if (MRI->reg_nodbg_empty(Reg))
2756       continue;
2757     if (MRI->recomputeRegClass(Reg)) {
2758       DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2759                    << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
2760       LiveInterval &LI = LIS->getInterval(Reg);
2761       unsigned MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
2762       if (MaxMask == 0) {
2763         // If the inflated register class does not support subregisters anymore
2764         // remove the subranges.
2765         LI.clearSubRanges();
2766       } else {
2767 #ifndef NDEBUG
2768         // If subranges are still supported, then the same subregs should still
2769         // be supported.
2770         for (LiveInterval::SubRange &S : LI.subranges()) {
2771           assert ((S.LaneMask & ~MaxMask) == 0);
2772         }
2773 #endif
2774       }
2775       ++NumInflated;
2776     }
2777   }
2778
2779   DEBUG(dump());
2780   if (VerifyCoalescing)
2781     MF->verify(this, "After register coalescing");
2782   return true;
2783 }
2784
2785 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
2786    LIS->print(O, m);
2787 }