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