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