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