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