xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/RegisterCoalescer.cpp (revision 52418fc2be8efa5172b90a3a9e617017173612c4)
10b57cec5SDimitry Andric //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface ------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the generic RegisterCoalescer interface which
100b57cec5SDimitry Andric // is used as the common interface used by all clients and
110b57cec5SDimitry Andric // implementations of register coalescing.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "RegisterCoalescer.h"
160b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
170b57cec5SDimitry Andric #include "llvm/ADT/BitVector.h"
180b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
220b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/LiveRangeEdit.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/RegisterClassInfo.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
410b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
420b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
43480093f4SDimitry Andric #include "llvm/InitializePasses.h"
440b57cec5SDimitry Andric #include "llvm/MC/LaneBitmask.h"
450b57cec5SDimitry Andric #include "llvm/MC/MCInstrDesc.h"
460b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
470b57cec5SDimitry Andric #include "llvm/Pass.h"
480b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
490b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
500b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
510b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
520b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
530b57cec5SDimitry Andric #include <algorithm>
540b57cec5SDimitry Andric #include <cassert>
550b57cec5SDimitry Andric #include <iterator>
560b57cec5SDimitry Andric #include <limits>
570b57cec5SDimitry Andric #include <tuple>
580b57cec5SDimitry Andric #include <utility>
590b57cec5SDimitry Andric #include <vector>
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric using namespace llvm;
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric #define DEBUG_TYPE "regalloc"
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric STATISTIC(numJoins    , "Number of interval joins performed");
660b57cec5SDimitry Andric STATISTIC(numCrossRCs , "Number of cross class joins performed");
670b57cec5SDimitry Andric STATISTIC(numCommutes , "Number of instruction commuting performed");
680b57cec5SDimitry Andric STATISTIC(numExtends  , "Number of copies extended");
690b57cec5SDimitry Andric STATISTIC(NumReMats   , "Number of instructions re-materialized");
700b57cec5SDimitry Andric STATISTIC(NumInflated , "Number of register classes inflated");
710b57cec5SDimitry Andric STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
720b57cec5SDimitry Andric STATISTIC(NumLaneResolves,  "Number of dead lane conflicts resolved");
730b57cec5SDimitry Andric STATISTIC(NumShrinkToUses,  "Number of shrinkToUses called");
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric static cl::opt<bool> EnableJoining("join-liveintervals",
760b57cec5SDimitry Andric                                    cl::desc("Coalesce copies (default=true)"),
770b57cec5SDimitry Andric                                    cl::init(true), cl::Hidden);
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric static cl::opt<bool> UseTerminalRule("terminal-rule",
800b57cec5SDimitry Andric                                      cl::desc("Apply the terminal rule"),
810b57cec5SDimitry Andric                                      cl::init(false), cl::Hidden);
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric /// Temporary flag to test critical edge unsplitting.
840b57cec5SDimitry Andric static cl::opt<bool>
850b57cec5SDimitry Andric EnableJoinSplits("join-splitedges",
860b57cec5SDimitry Andric   cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric /// Temporary flag to test global copy optimization.
890b57cec5SDimitry Andric static cl::opt<cl::boolOrDefault>
900b57cec5SDimitry Andric EnableGlobalCopies("join-globalcopies",
910b57cec5SDimitry Andric   cl::desc("Coalesce copies that span blocks (default=subtarget)"),
920b57cec5SDimitry Andric   cl::init(cl::BOU_UNSET), cl::Hidden);
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric static cl::opt<bool>
950b57cec5SDimitry Andric VerifyCoalescing("verify-coalescing",
960b57cec5SDimitry Andric          cl::desc("Verify machine instrs before and after register coalescing"),
970b57cec5SDimitry Andric          cl::Hidden);
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric static cl::opt<unsigned> LateRematUpdateThreshold(
1000b57cec5SDimitry Andric     "late-remat-update-threshold", cl::Hidden,
1010b57cec5SDimitry Andric     cl::desc("During rematerialization for a copy, if the def instruction has "
1020b57cec5SDimitry Andric              "many other copy uses to be rematerialized, delay the multiple "
1030b57cec5SDimitry Andric              "separate live interval update work and do them all at once after "
1040b57cec5SDimitry Andric              "all those rematerialization are done. It will save a lot of "
1050b57cec5SDimitry Andric              "repeated work. "),
1060b57cec5SDimitry Andric     cl::init(100));
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric static cl::opt<unsigned> LargeIntervalSizeThreshold(
1090b57cec5SDimitry Andric     "large-interval-size-threshold", cl::Hidden,
1100b57cec5SDimitry Andric     cl::desc("If the valnos size of an interval is larger than the threshold, "
1110b57cec5SDimitry Andric              "it is regarded as a large interval. "),
1120b57cec5SDimitry Andric     cl::init(100));
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric static cl::opt<unsigned> LargeIntervalFreqThreshold(
1150b57cec5SDimitry Andric     "large-interval-freq-threshold", cl::Hidden,
1160b57cec5SDimitry Andric     cl::desc("For a large interval, if it is coalesed with other live "
1170b57cec5SDimitry Andric              "intervals many times more than the threshold, stop its "
1180b57cec5SDimitry Andric              "coalescing to control the compile time. "),
11906c3fb27SDimitry Andric     cl::init(256));
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric namespace {
1220b57cec5SDimitry Andric 
123480093f4SDimitry Andric   class JoinVals;
124480093f4SDimitry Andric 
1250b57cec5SDimitry Andric   class RegisterCoalescer : public MachineFunctionPass,
1260b57cec5SDimitry Andric                             private LiveRangeEdit::Delegate {
127480093f4SDimitry Andric     MachineFunction* MF = nullptr;
128480093f4SDimitry Andric     MachineRegisterInfo* MRI = nullptr;
129480093f4SDimitry Andric     const TargetRegisterInfo* TRI = nullptr;
130480093f4SDimitry Andric     const TargetInstrInfo* TII = nullptr;
131480093f4SDimitry Andric     LiveIntervals *LIS = nullptr;
132480093f4SDimitry Andric     const MachineLoopInfo* Loops = nullptr;
133480093f4SDimitry Andric     AliasAnalysis *AA = nullptr;
1340b57cec5SDimitry Andric     RegisterClassInfo RegClassInfo;
1350b57cec5SDimitry Andric 
136fe6060f1SDimitry Andric     /// Position and VReg of a PHI instruction during coalescing.
137fe6060f1SDimitry Andric     struct PHIValPos {
138fe6060f1SDimitry Andric       SlotIndex SI;    ///< Slot where this PHI occurs.
139fe6060f1SDimitry Andric       Register Reg;    ///< VReg the PHI occurs in.
140fe6060f1SDimitry Andric       unsigned SubReg; ///< Qualifying subregister for Reg.
141fe6060f1SDimitry Andric     };
142fe6060f1SDimitry Andric 
143fe6060f1SDimitry Andric     /// Map from debug instruction number to PHI position during coalescing.
144fe6060f1SDimitry Andric     DenseMap<unsigned, PHIValPos> PHIValToPos;
145fe6060f1SDimitry Andric     /// Index of, for each VReg, which debug instruction numbers and
146fe6060f1SDimitry Andric     /// corresponding PHIs are sensitive to coalescing. Each VReg may have
147fe6060f1SDimitry Andric     /// multiple PHI defs, at different positions.
148fe6060f1SDimitry Andric     DenseMap<Register, SmallVector<unsigned, 2>> RegToPHIIdx;
149fe6060f1SDimitry Andric 
150480093f4SDimitry Andric     /// Debug variable location tracking -- for each VReg, maintain an
151480093f4SDimitry Andric     /// ordered-by-slot-index set of DBG_VALUEs, to help quick
152480093f4SDimitry Andric     /// identification of whether coalescing may change location validity.
153480093f4SDimitry Andric     using DbgValueLoc = std::pair<SlotIndex, MachineInstr*>;
154e8d8bef9SDimitry Andric     DenseMap<Register, std::vector<DbgValueLoc>> DbgVRegToValues;
155480093f4SDimitry Andric 
1560b57cec5SDimitry Andric     /// A LaneMask to remember on which subregister live ranges we need to call
1570b57cec5SDimitry Andric     /// shrinkToUses() later.
1580b57cec5SDimitry Andric     LaneBitmask ShrinkMask;
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric     /// True if the main range of the currently coalesced intervals should be
1610b57cec5SDimitry Andric     /// checked for smaller live intervals.
162480093f4SDimitry Andric     bool ShrinkMainRange = false;
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric     /// True if the coalescer should aggressively coalesce global copies
1650b57cec5SDimitry Andric     /// in favor of keeping local copies.
166480093f4SDimitry Andric     bool JoinGlobalCopies = false;
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric     /// True if the coalescer should aggressively coalesce fall-thru
1690b57cec5SDimitry Andric     /// blocks exclusively containing copies.
170480093f4SDimitry Andric     bool JoinSplitEdges = false;
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric     /// Copy instructions yet to be coalesced.
1730b57cec5SDimitry Andric     SmallVector<MachineInstr*, 8> WorkList;
1740b57cec5SDimitry Andric     SmallVector<MachineInstr*, 8> LocalWorkList;
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric     /// Set of instruction pointers that have been erased, and
1770b57cec5SDimitry Andric     /// that may be present in WorkList.
1780b57cec5SDimitry Andric     SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric     /// Dead instructions that are about to be deleted.
1810b57cec5SDimitry Andric     SmallVector<MachineInstr*, 8> DeadDefs;
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric     /// Virtual registers to be considered for register class inflation.
184e8d8bef9SDimitry Andric     SmallVector<Register, 8> InflateRegs;
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric     /// The collection of live intervals which should have been updated
1870b57cec5SDimitry Andric     /// immediately after rematerialiation but delayed until
1880b57cec5SDimitry Andric     /// lateLiveIntervalUpdate is called.
189e8d8bef9SDimitry Andric     DenseSet<Register> ToBeUpdated;
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric     /// Record how many times the large live interval with many valnos
1920b57cec5SDimitry Andric     /// has been tried to join with other live interval.
193e8d8bef9SDimitry Andric     DenseMap<Register, unsigned long> LargeLIVisitCounter;
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric     /// Recursively eliminate dead defs in DeadDefs.
196bdd1243dSDimitry Andric     void eliminateDeadDefs(LiveRangeEdit *Edit = nullptr);
197fe6060f1SDimitry Andric 
1980b57cec5SDimitry Andric     /// LiveRangeEdit callback for eliminateDeadDefs().
1990b57cec5SDimitry Andric     void LRE_WillEraseInstruction(MachineInstr *MI) override;
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric     /// Coalesce the LocalWorkList.
2020b57cec5SDimitry Andric     void coalesceLocals();
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric     /// Join compatible live intervals
2050b57cec5SDimitry Andric     void joinAllIntervals();
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric     /// Coalesce copies in the specified MBB, putting
2080b57cec5SDimitry Andric     /// copies that cannot yet be coalesced into WorkList.
2090b57cec5SDimitry Andric     void copyCoalesceInMBB(MachineBasicBlock *MBB);
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric     /// Tries to coalesce all copies in CurrList. Returns true if any progress
2120b57cec5SDimitry Andric     /// was made.
2130b57cec5SDimitry Andric     bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric     /// If one def has many copy like uses, and those copy uses are all
2160b57cec5SDimitry Andric     /// rematerialized, the live interval update needed for those
2170b57cec5SDimitry Andric     /// rematerializations will be delayed and done all at once instead
2180b57cec5SDimitry Andric     /// of being done multiple times. This is to save compile cost because
2190b57cec5SDimitry Andric     /// live interval update is costly.
2200b57cec5SDimitry Andric     void lateLiveIntervalUpdate();
2210b57cec5SDimitry Andric 
222e8d8bef9SDimitry Andric     /// Check if the incoming value defined by a COPY at \p SLRQ in the subrange
223e8d8bef9SDimitry Andric     /// has no value defined in the predecessors. If the incoming value is the
224e8d8bef9SDimitry Andric     /// same as defined by the copy itself, the value is considered undefined.
225e8d8bef9SDimitry Andric     bool copyValueUndefInPredecessors(LiveRange &S,
226e8d8bef9SDimitry Andric                                       const MachineBasicBlock *MBB,
227e8d8bef9SDimitry Andric                                       LiveQueryResult SLRQ);
228e8d8bef9SDimitry Andric 
229e8d8bef9SDimitry Andric     /// Set necessary undef flags on subregister uses after pruning out undef
230e8d8bef9SDimitry Andric     /// lane segments from the subrange.
231e8d8bef9SDimitry Andric     void setUndefOnPrunedSubRegUses(LiveInterval &LI, Register Reg,
232e8d8bef9SDimitry Andric                                     LaneBitmask PrunedLanes);
233e8d8bef9SDimitry Andric 
2340b57cec5SDimitry Andric     /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
2350b57cec5SDimitry Andric     /// src/dst of the copy instruction CopyMI.  This returns true if the copy
2360b57cec5SDimitry Andric     /// was successfully coalesced away. If it is not currently possible to
2370b57cec5SDimitry Andric     /// coalesce this interval, but it may be possible if other things get
2380b57cec5SDimitry Andric     /// coalesced, then it returns true by reference in 'Again'.
23974626c16SDimitry Andric     bool joinCopy(MachineInstr *CopyMI, bool &Again,
24074626c16SDimitry Andric                   SmallPtrSetImpl<MachineInstr *> &CurrentErasedInstrs);
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric     /// Attempt to join these two intervals.  On failure, this
2430b57cec5SDimitry Andric     /// returns false.  The output "SrcInt" will not have been modified, so we
2440b57cec5SDimitry Andric     /// can use this information below to update aliases.
2450b57cec5SDimitry Andric     bool joinIntervals(CoalescerPair &CP);
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric     /// Attempt joining two virtual registers. Return true on success.
2480b57cec5SDimitry Andric     bool joinVirtRegs(CoalescerPair &CP);
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric     /// If a live interval has many valnos and is coalesced with other
2510b57cec5SDimitry Andric     /// live intervals many times, we regard such live interval as having
2520b57cec5SDimitry Andric     /// high compile time cost.
2530b57cec5SDimitry Andric     bool isHighCostLiveInterval(LiveInterval &LI);
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric     /// Attempt joining with a reserved physreg.
2560b57cec5SDimitry Andric     bool joinReservedPhysReg(CoalescerPair &CP);
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric     /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
2590b57cec5SDimitry Andric     /// Subranges in @p LI which only partially interfere with the desired
2600b57cec5SDimitry Andric     /// LaneMask are split as necessary. @p LaneMask are the lanes that
2610b57cec5SDimitry Andric     /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
2620b57cec5SDimitry Andric     /// lanemasks already adjusted to the coalesced register.
2630b57cec5SDimitry Andric     void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
264480093f4SDimitry Andric                            LaneBitmask LaneMask, CoalescerPair &CP,
265480093f4SDimitry Andric                            unsigned DstIdx);
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric     /// Join the liveranges of two subregisters. Joins @p RRange into
2680b57cec5SDimitry Andric     /// @p LRange, @p RRange may be invalid afterwards.
2690b57cec5SDimitry Andric     void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
2700b57cec5SDimitry Andric                           LaneBitmask LaneMask, const CoalescerPair &CP);
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric     /// We found a non-trivially-coalescable copy. If the source value number is
2730b57cec5SDimitry Andric     /// defined by a copy from the destination reg see if we can merge these two
2740b57cec5SDimitry Andric     /// destination reg valno# into a single value number, eliminating a copy.
2750b57cec5SDimitry Andric     /// This returns true if an interval was modified.
2760b57cec5SDimitry Andric     bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric     /// Return true if there are definitions of IntB
2790b57cec5SDimitry Andric     /// other than BValNo val# that can reach uses of AValno val# of IntA.
2800b57cec5SDimitry Andric     bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
2810b57cec5SDimitry Andric                               VNInfo *AValNo, VNInfo *BValNo);
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric     /// We found a non-trivially-coalescable copy.
2840b57cec5SDimitry Andric     /// If the source value number is defined by a commutable instruction and
2850b57cec5SDimitry Andric     /// its other operand is coalesced to the copy dest register, see if we
2860b57cec5SDimitry Andric     /// can transform the copy into a noop by commuting the definition.
2870b57cec5SDimitry Andric     /// This returns a pair of two flags:
2880b57cec5SDimitry Andric     /// - the first element is true if an interval was modified,
2890b57cec5SDimitry Andric     /// - the second element is true if the destination interval needs
2900b57cec5SDimitry Andric     ///   to be shrunk after deleting the copy.
2910b57cec5SDimitry Andric     std::pair<bool,bool> removeCopyByCommutingDef(const CoalescerPair &CP,
2920b57cec5SDimitry Andric                                                   MachineInstr *CopyMI);
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric     /// We found a copy which can be moved to its less frequent predecessor.
2950b57cec5SDimitry Andric     bool removePartialRedundancy(const CoalescerPair &CP, MachineInstr &CopyMI);
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric     /// If the source of a copy is defined by a
2980b57cec5SDimitry Andric     /// trivial computation, replace the copy by rematerialize the definition.
2990b57cec5SDimitry Andric     bool reMaterializeTrivialDef(const CoalescerPair &CP, MachineInstr *CopyMI,
3000b57cec5SDimitry Andric                                  bool &IsDefCopy);
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric     /// Return true if a copy involving a physreg should be joined.
3030b57cec5SDimitry Andric     bool canJoinPhys(const CoalescerPair &CP);
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric     /// Replace all defs and uses of SrcReg to DstReg and update the subregister
3060b57cec5SDimitry Andric     /// number if it is not zero. If DstReg is a physical register and the
3070b57cec5SDimitry Andric     /// existing subregister number of the def / use being updated is not zero,
3080b57cec5SDimitry Andric     /// make sure to set it to the correct physical subregister.
309edc2dc17SDimitry Andric     void updateRegDefsUses(Register SrcReg, Register DstReg, unsigned SubIdx);
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric     /// If the given machine operand reads only undefined lanes add an undef
3120b57cec5SDimitry Andric     /// flag.
3130b57cec5SDimitry Andric     /// This can happen when undef uses were previously concealed by a copy
3140b57cec5SDimitry Andric     /// which we coalesced. Example:
3150b57cec5SDimitry Andric     ///    %0:sub0<def,read-undef> = ...
3160b57cec5SDimitry Andric     ///    %1 = COPY %0           <-- Coalescing COPY reveals undef
3170b57cec5SDimitry Andric     ///       = use %1:sub1       <-- hidden undef use
3180b57cec5SDimitry Andric     void addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
3190b57cec5SDimitry Andric                       MachineOperand &MO, unsigned SubRegIdx);
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric     /// Handle copies of undef values. If the undef value is an incoming
3220b57cec5SDimitry Andric     /// PHI value, it will convert @p CopyMI to an IMPLICIT_DEF.
3230b57cec5SDimitry Andric     /// Returns nullptr if @p CopyMI was not in any way eliminable. Otherwise,
3240b57cec5SDimitry Andric     /// it returns @p CopyMI (which could be an IMPLICIT_DEF at this point).
3250b57cec5SDimitry Andric     MachineInstr *eliminateUndefCopy(MachineInstr *CopyMI);
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric     /// Check whether or not we should apply the terminal rule on the
3280b57cec5SDimitry Andric     /// destination (Dst) of \p Copy.
3290b57cec5SDimitry Andric     /// When the terminal rule applies, Copy is not profitable to
3300b57cec5SDimitry Andric     /// coalesce.
3310b57cec5SDimitry Andric     /// Dst is terminal if it has exactly one affinity (Dst, Src) and
3320b57cec5SDimitry Andric     /// at least one interference (Dst, Dst2). If Dst is terminal, the
3330b57cec5SDimitry Andric     /// terminal rule consists in checking that at least one of
3340b57cec5SDimitry Andric     /// interfering node, say Dst2, has an affinity of equal or greater
3350b57cec5SDimitry Andric     /// weight with Src.
3360b57cec5SDimitry Andric     /// In that case, Dst2 and Dst will not be able to be both coalesced
3370b57cec5SDimitry Andric     /// with Src. Since Dst2 exposes more coalescing opportunities than
3380b57cec5SDimitry Andric     /// Dst, we can drop \p Copy.
3390b57cec5SDimitry Andric     bool applyTerminalRule(const MachineInstr &Copy) const;
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric     /// Wrapper method for \see LiveIntervals::shrinkToUses.
3420b57cec5SDimitry Andric     /// This method does the proper fixing of the live-ranges when the afore
3430b57cec5SDimitry Andric     /// mentioned method returns true.
3440b57cec5SDimitry Andric     void shrinkToUses(LiveInterval *LI,
3450b57cec5SDimitry Andric                       SmallVectorImpl<MachineInstr * > *Dead = nullptr) {
3460b57cec5SDimitry Andric       NumShrinkToUses++;
3470b57cec5SDimitry Andric       if (LIS->shrinkToUses(LI, Dead)) {
3480b57cec5SDimitry Andric         /// Check whether or not \p LI is composed by multiple connected
3490b57cec5SDimitry Andric         /// components and if that is the case, fix that.
3500b57cec5SDimitry Andric         SmallVector<LiveInterval*, 8> SplitLIs;
3510b57cec5SDimitry Andric         LIS->splitSeparateComponents(*LI, SplitLIs);
3520b57cec5SDimitry Andric       }
3530b57cec5SDimitry Andric     }
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric     /// Wrapper Method to do all the necessary work when an Instruction is
3560b57cec5SDimitry Andric     /// deleted.
3570b57cec5SDimitry Andric     /// Optimizations should use this to make sure that deleted instructions
3580b57cec5SDimitry Andric     /// are always accounted for.
3590b57cec5SDimitry Andric     void deleteInstr(MachineInstr* MI) {
3600b57cec5SDimitry Andric       ErasedInstrs.insert(MI);
3610b57cec5SDimitry Andric       LIS->RemoveMachineInstrFromMaps(*MI);
3620b57cec5SDimitry Andric       MI->eraseFromParent();
3630b57cec5SDimitry Andric     }
3640b57cec5SDimitry Andric 
365480093f4SDimitry Andric     /// Walk over function and initialize the DbgVRegToValues map.
366480093f4SDimitry Andric     void buildVRegToDbgValueMap(MachineFunction &MF);
367480093f4SDimitry Andric 
368480093f4SDimitry Andric     /// Test whether, after merging, any DBG_VALUEs would refer to a
369480093f4SDimitry Andric     /// different value number than before merging, and whether this can
370480093f4SDimitry Andric     /// be resolved. If not, mark the DBG_VALUE as being undef.
371480093f4SDimitry Andric     void checkMergingChangesDbgValues(CoalescerPair &CP, LiveRange &LHS,
372480093f4SDimitry Andric                                       JoinVals &LHSVals, LiveRange &RHS,
373480093f4SDimitry Andric                                       JoinVals &RHSVals);
374480093f4SDimitry Andric 
375e8d8bef9SDimitry Andric     void checkMergingChangesDbgValuesImpl(Register Reg, LiveRange &OtherRange,
376480093f4SDimitry Andric                                           LiveRange &RegRange, JoinVals &Vals2);
377480093f4SDimitry Andric 
3780b57cec5SDimitry Andric   public:
3790b57cec5SDimitry Andric     static char ID; ///< Class identification, replacement for typeinfo
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric     RegisterCoalescer() : MachineFunctionPass(ID) {
3820b57cec5SDimitry Andric       initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
3830b57cec5SDimitry Andric     }
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override;
3860b57cec5SDimitry Andric 
3875f757f3fSDimitry Andric     MachineFunctionProperties getClearedProperties() const override {
3885f757f3fSDimitry Andric       return MachineFunctionProperties().set(
3895f757f3fSDimitry Andric           MachineFunctionProperties::Property::IsSSA);
3905f757f3fSDimitry Andric     }
3915f757f3fSDimitry Andric 
3920b57cec5SDimitry Andric     void releaseMemory() override;
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric     /// This is the pass entry point.
3950b57cec5SDimitry Andric     bool runOnMachineFunction(MachineFunction&) override;
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric     /// Implement the dump method.
3980b57cec5SDimitry Andric     void print(raw_ostream &O, const Module* = nullptr) const override;
3990b57cec5SDimitry Andric   };
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric } // end anonymous namespace
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric char RegisterCoalescer::ID = 0;
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
4060b57cec5SDimitry Andric 
40706c3fb27SDimitry Andric INITIALIZE_PASS_BEGIN(RegisterCoalescer, "register-coalescer",
40806c3fb27SDimitry Andric                       "Register Coalescer", false, false)
4090fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
4100fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(SlotIndexesWrapperPass)
4110fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
4120b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
41306c3fb27SDimitry Andric INITIALIZE_PASS_END(RegisterCoalescer, "register-coalescer",
41406c3fb27SDimitry Andric                     "Register Coalescer", false, false)
4150b57cec5SDimitry Andric 
416bdd1243dSDimitry Andric [[nodiscard]] static bool isMoveInstr(const TargetRegisterInfo &tri,
417e8d8bef9SDimitry Andric                                       const MachineInstr *MI, Register &Src,
418e8d8bef9SDimitry Andric                                       Register &Dst, unsigned &SrcSub,
4190b57cec5SDimitry Andric                                       unsigned &DstSub) {
4200b57cec5SDimitry Andric     if (MI->isCopy()) {
4210b57cec5SDimitry Andric       Dst = MI->getOperand(0).getReg();
4220b57cec5SDimitry Andric       DstSub = MI->getOperand(0).getSubReg();
4230b57cec5SDimitry Andric       Src = MI->getOperand(1).getReg();
4240b57cec5SDimitry Andric       SrcSub = MI->getOperand(1).getSubReg();
4250b57cec5SDimitry Andric     } else if (MI->isSubregToReg()) {
4260b57cec5SDimitry Andric       Dst = MI->getOperand(0).getReg();
4270b57cec5SDimitry Andric       DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
4280b57cec5SDimitry Andric                                         MI->getOperand(3).getImm());
4290b57cec5SDimitry Andric       Src = MI->getOperand(2).getReg();
4300b57cec5SDimitry Andric       SrcSub = MI->getOperand(2).getSubReg();
4310b57cec5SDimitry Andric     } else
4320b57cec5SDimitry Andric       return false;
4330b57cec5SDimitry Andric     return true;
4340b57cec5SDimitry Andric }
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric /// Return true if this block should be vacated by the coalescer to eliminate
4370b57cec5SDimitry Andric /// branches. The important cases to handle in the coalescer are critical edges
4380b57cec5SDimitry Andric /// split during phi elimination which contain only copies. Simple blocks that
4390b57cec5SDimitry Andric /// contain non-branches should also be vacated, but this can be handled by an
4400b57cec5SDimitry Andric /// earlier pass similar to early if-conversion.
4410b57cec5SDimitry Andric static bool isSplitEdge(const MachineBasicBlock *MBB) {
4420b57cec5SDimitry Andric   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
4430b57cec5SDimitry Andric     return false;
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric   for (const auto &MI : *MBB) {
4460b57cec5SDimitry Andric     if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
4470b57cec5SDimitry Andric       return false;
4480b57cec5SDimitry Andric   }
4490b57cec5SDimitry Andric   return true;
4500b57cec5SDimitry Andric }
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric bool CoalescerPair::setRegisters(const MachineInstr *MI) {
453e8d8bef9SDimitry Andric   SrcReg = DstReg = Register();
4540b57cec5SDimitry Andric   SrcIdx = DstIdx = 0;
4550b57cec5SDimitry Andric   NewRC = nullptr;
4560b57cec5SDimitry Andric   Flipped = CrossClass = false;
4570b57cec5SDimitry Andric 
458e8d8bef9SDimitry Andric   Register Src, Dst;
459e8d8bef9SDimitry Andric   unsigned SrcSub = 0, DstSub = 0;
4600b57cec5SDimitry Andric   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
4610b57cec5SDimitry Andric     return false;
4620b57cec5SDimitry Andric   Partial = SrcSub || DstSub;
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   // If one register is a physreg, it must be Dst.
465bdd1243dSDimitry Andric   if (Src.isPhysical()) {
466bdd1243dSDimitry Andric     if (Dst.isPhysical())
4670b57cec5SDimitry Andric       return false;
4680b57cec5SDimitry Andric     std::swap(Src, Dst);
4690b57cec5SDimitry Andric     std::swap(SrcSub, DstSub);
4700b57cec5SDimitry Andric     Flipped = true;
4710b57cec5SDimitry Andric   }
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   const MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
4740b57cec5SDimitry Andric 
475bdd1243dSDimitry Andric   if (Dst.isPhysical()) {
4760b57cec5SDimitry Andric     // Eliminate DstSub on a physreg.
4770b57cec5SDimitry Andric     if (DstSub) {
4780b57cec5SDimitry Andric       Dst = TRI.getSubReg(Dst, DstSub);
4790b57cec5SDimitry Andric       if (!Dst) return false;
4800b57cec5SDimitry Andric       DstSub = 0;
4810b57cec5SDimitry Andric     }
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric     // Eliminate SrcSub by picking a corresponding Dst superregister.
4840b57cec5SDimitry Andric     if (SrcSub) {
4850b57cec5SDimitry Andric       Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
4860b57cec5SDimitry Andric       if (!Dst) return false;
4870b57cec5SDimitry Andric     } else if (!MRI.getRegClass(Src)->contains(Dst)) {
4880b57cec5SDimitry Andric       return false;
4890b57cec5SDimitry Andric     }
4900b57cec5SDimitry Andric   } else {
4910b57cec5SDimitry Andric     // Both registers are virtual.
4920b57cec5SDimitry Andric     const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
4930b57cec5SDimitry Andric     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric     // Both registers have subreg indices.
4960b57cec5SDimitry Andric     if (SrcSub && DstSub) {
4970b57cec5SDimitry Andric       // Copies between different sub-registers are never coalescable.
4980b57cec5SDimitry Andric       if (Src == Dst && SrcSub != DstSub)
4990b57cec5SDimitry Andric         return false;
5000b57cec5SDimitry Andric 
5010b57cec5SDimitry Andric       NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
5020b57cec5SDimitry Andric                                          SrcIdx, DstIdx);
5030b57cec5SDimitry Andric       if (!NewRC)
5040b57cec5SDimitry Andric         return false;
5050b57cec5SDimitry Andric     } else if (DstSub) {
5060b57cec5SDimitry Andric       // SrcReg will be merged with a sub-register of DstReg.
5070b57cec5SDimitry Andric       SrcIdx = DstSub;
5080b57cec5SDimitry Andric       NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
5090b57cec5SDimitry Andric     } else if (SrcSub) {
5100b57cec5SDimitry Andric       // DstReg will be merged with a sub-register of SrcReg.
5110b57cec5SDimitry Andric       DstIdx = SrcSub;
5120b57cec5SDimitry Andric       NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
5130b57cec5SDimitry Andric     } else {
5140b57cec5SDimitry Andric       // This is a straight copy without sub-registers.
5150b57cec5SDimitry Andric       NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
5160b57cec5SDimitry Andric     }
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric     // The combined constraint may be impossible to satisfy.
5190b57cec5SDimitry Andric     if (!NewRC)
5200b57cec5SDimitry Andric       return false;
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric     // Prefer SrcReg to be a sub-register of DstReg.
5230b57cec5SDimitry Andric     // FIXME: Coalescer should support subregs symmetrically.
5240b57cec5SDimitry Andric     if (DstIdx && !SrcIdx) {
5250b57cec5SDimitry Andric       std::swap(Src, Dst);
5260b57cec5SDimitry Andric       std::swap(SrcIdx, DstIdx);
5270b57cec5SDimitry Andric       Flipped = !Flipped;
5280b57cec5SDimitry Andric     }
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric     CrossClass = NewRC != DstRC || NewRC != SrcRC;
5310b57cec5SDimitry Andric   }
5320b57cec5SDimitry Andric   // Check our invariants
533bdd1243dSDimitry Andric   assert(Src.isVirtual() && "Src must be virtual");
534bdd1243dSDimitry Andric   assert(!(Dst.isPhysical() && DstSub) && "Cannot have a physical SubIdx");
5350b57cec5SDimitry Andric   SrcReg = Src;
5360b57cec5SDimitry Andric   DstReg = Dst;
5370b57cec5SDimitry Andric   return true;
5380b57cec5SDimitry Andric }
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric bool CoalescerPair::flip() {
541bdd1243dSDimitry Andric   if (DstReg.isPhysical())
5420b57cec5SDimitry Andric     return false;
5430b57cec5SDimitry Andric   std::swap(SrcReg, DstReg);
5440b57cec5SDimitry Andric   std::swap(SrcIdx, DstIdx);
5450b57cec5SDimitry Andric   Flipped = !Flipped;
5460b57cec5SDimitry Andric   return true;
5470b57cec5SDimitry Andric }
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
5500b57cec5SDimitry Andric   if (!MI)
5510b57cec5SDimitry Andric     return false;
552e8d8bef9SDimitry Andric   Register Src, Dst;
553e8d8bef9SDimitry Andric   unsigned SrcSub = 0, DstSub = 0;
5540b57cec5SDimitry Andric   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
5550b57cec5SDimitry Andric     return false;
5560b57cec5SDimitry Andric 
5570b57cec5SDimitry Andric   // Find the virtual register that is SrcReg.
5580b57cec5SDimitry Andric   if (Dst == SrcReg) {
5590b57cec5SDimitry Andric     std::swap(Src, Dst);
5600b57cec5SDimitry Andric     std::swap(SrcSub, DstSub);
5610b57cec5SDimitry Andric   } else if (Src != SrcReg) {
5620b57cec5SDimitry Andric     return false;
5630b57cec5SDimitry Andric   }
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric   // Now check that Dst matches DstReg.
566e8d8bef9SDimitry Andric   if (DstReg.isPhysical()) {
567e8d8bef9SDimitry Andric     if (!Dst.isPhysical())
5680b57cec5SDimitry Andric       return false;
5690b57cec5SDimitry Andric     assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
5700b57cec5SDimitry Andric     // DstSub could be set for a physreg from INSERT_SUBREG.
5710b57cec5SDimitry Andric     if (DstSub)
5720b57cec5SDimitry Andric       Dst = TRI.getSubReg(Dst, DstSub);
5730b57cec5SDimitry Andric     // Full copy of Src.
5740b57cec5SDimitry Andric     if (!SrcSub)
5750b57cec5SDimitry Andric       return DstReg == Dst;
5760b57cec5SDimitry Andric     // This is a partial register copy. Check that the parts match.
577e8d8bef9SDimitry Andric     return Register(TRI.getSubReg(DstReg, SrcSub)) == Dst;
5780b57cec5SDimitry Andric   } else {
5790b57cec5SDimitry Andric     // DstReg is virtual.
5800b57cec5SDimitry Andric     if (DstReg != Dst)
5810b57cec5SDimitry Andric       return false;
5820b57cec5SDimitry Andric     // Registers match, do the subregisters line up?
5830b57cec5SDimitry Andric     return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
5840b57cec5SDimitry Andric            TRI.composeSubRegIndices(DstIdx, DstSub);
5850b57cec5SDimitry Andric   }
5860b57cec5SDimitry Andric }
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
5890b57cec5SDimitry Andric   AU.setPreservesCFG();
5900b57cec5SDimitry Andric   AU.addRequired<AAResultsWrapperPass>();
5910fca6ea1SDimitry Andric   AU.addRequired<LiveIntervalsWrapperPass>();
5920fca6ea1SDimitry Andric   AU.addPreserved<LiveIntervalsWrapperPass>();
5930fca6ea1SDimitry Andric   AU.addPreserved<SlotIndexesWrapperPass>();
5940fca6ea1SDimitry Andric   AU.addRequired<MachineLoopInfoWrapperPass>();
5950fca6ea1SDimitry Andric   AU.addPreserved<MachineLoopInfoWrapperPass>();
5960b57cec5SDimitry Andric   AU.addPreservedID(MachineDominatorsID);
5970b57cec5SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
5980b57cec5SDimitry Andric }
5990b57cec5SDimitry Andric 
600bdd1243dSDimitry Andric void RegisterCoalescer::eliminateDeadDefs(LiveRangeEdit *Edit) {
601bdd1243dSDimitry Andric   if (Edit) {
602bdd1243dSDimitry Andric     Edit->eliminateDeadDefs(DeadDefs);
603bdd1243dSDimitry Andric     return;
604bdd1243dSDimitry Andric   }
6055ffd83dbSDimitry Andric   SmallVector<Register, 8> NewRegs;
6060b57cec5SDimitry Andric   LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
6070b57cec5SDimitry Andric                 nullptr, this).eliminateDeadDefs(DeadDefs);
6080b57cec5SDimitry Andric }
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
6110b57cec5SDimitry Andric   // MI may be in WorkList. Make sure we don't visit it.
6120b57cec5SDimitry Andric   ErasedInstrs.insert(MI);
6130b57cec5SDimitry Andric }
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
6160b57cec5SDimitry Andric                                              MachineInstr *CopyMI) {
6170b57cec5SDimitry Andric   assert(!CP.isPartial() && "This doesn't work for partial copies.");
6180b57cec5SDimitry Andric   assert(!CP.isPhys() && "This doesn't work for physreg copies.");
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric   LiveInterval &IntA =
6210b57cec5SDimitry Andric     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
6220b57cec5SDimitry Andric   LiveInterval &IntB =
6230b57cec5SDimitry Andric     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
6240b57cec5SDimitry Andric   SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric   // We have a non-trivially-coalescable copy with IntA being the source and
6270b57cec5SDimitry Andric   // IntB being the dest, thus this defines a value number in IntB.  If the
6280b57cec5SDimitry Andric   // source value number (in IntA) is defined by a copy from B, see if we can
6290b57cec5SDimitry Andric   // merge these two pieces of B into a single value number, eliminating a copy.
6300b57cec5SDimitry Andric   // For example:
6310b57cec5SDimitry Andric   //
6320b57cec5SDimitry Andric   //  A3 = B0
6330b57cec5SDimitry Andric   //    ...
6340b57cec5SDimitry Andric   //  B1 = A3      <- this copy
6350b57cec5SDimitry Andric   //
6360b57cec5SDimitry Andric   // In this case, B0 can be extended to where the B1 copy lives, allowing the
6370b57cec5SDimitry Andric   // B1 value number to be replaced with B0 (which simplifies the B
6380b57cec5SDimitry Andric   // liveinterval).
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   // BValNo is a value number in B that is defined by a copy from A.  'B1' in
6410b57cec5SDimitry Andric   // the example above.
6420b57cec5SDimitry Andric   LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
6430b57cec5SDimitry Andric   if (BS == IntB.end()) return false;
6440b57cec5SDimitry Andric   VNInfo *BValNo = BS->valno;
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric   // Get the location that B is defined at.  Two options: either this value has
6470b57cec5SDimitry Andric   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
6480b57cec5SDimitry Andric   // can't process it.
6490b57cec5SDimitry Andric   if (BValNo->def != CopyIdx) return false;
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric   // AValNo is the value number in A that defines the copy, A3 in the example.
6520b57cec5SDimitry Andric   SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
6530b57cec5SDimitry Andric   LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
6540b57cec5SDimitry Andric   // The live segment might not exist after fun with physreg coalescing.
6550b57cec5SDimitry Andric   if (AS == IntA.end()) return false;
6560b57cec5SDimitry Andric   VNInfo *AValNo = AS->valno;
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric   // If AValNo is defined as a copy from IntB, we can potentially process this.
6590b57cec5SDimitry Andric   // Get the instruction that defines this value number.
6600b57cec5SDimitry Andric   MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
6610b57cec5SDimitry Andric   // Don't allow any partial copies, even if isCoalescable() allows them.
6620b57cec5SDimitry Andric   if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
6630b57cec5SDimitry Andric     return false;
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   // Get the Segment in IntB that this value number starts with.
6660b57cec5SDimitry Andric   LiveInterval::iterator ValS =
6670b57cec5SDimitry Andric     IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
6680b57cec5SDimitry Andric   if (ValS == IntB.end())
6690b57cec5SDimitry Andric     return false;
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric   // Make sure that the end of the live segment is inside the same block as
6720b57cec5SDimitry Andric   // CopyMI.
6730b57cec5SDimitry Andric   MachineInstr *ValSEndInst =
6740b57cec5SDimitry Andric     LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
6750b57cec5SDimitry Andric   if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
6760b57cec5SDimitry Andric     return false;
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric   // Okay, we now know that ValS ends in the same block that the CopyMI
6790b57cec5SDimitry Andric   // live-range starts.  If there are no intervening live segments between them
6800b57cec5SDimitry Andric   // in IntB, we can merge them.
6810b57cec5SDimitry Andric   if (ValS+1 != BS) return false;
6820b57cec5SDimitry Andric 
683e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Extending: " << printReg(IntB.reg(), TRI));
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric   SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
6860b57cec5SDimitry Andric   // We are about to delete CopyMI, so need to remove it as the 'instruction
6870b57cec5SDimitry Andric   // that defines this value #'. Update the valnum with the new defining
6880b57cec5SDimitry Andric   // instruction #.
6890b57cec5SDimitry Andric   BValNo->def = FillerStart;
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric   // Okay, we can merge them.  We need to insert a new liverange:
6920b57cec5SDimitry Andric   // [ValS.end, BS.begin) of either value number, then we merge the
6930b57cec5SDimitry Andric   // two value numbers.
6940b57cec5SDimitry Andric   IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric   // Okay, merge "B1" into the same value number as "B0".
6970b57cec5SDimitry Andric   if (BValNo != ValS->valno)
6980b57cec5SDimitry Andric     IntB.MergeValueNumberInto(BValNo, ValS->valno);
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric   // Do the same for the subregister segments.
7010b57cec5SDimitry Andric   for (LiveInterval::SubRange &S : IntB.subranges()) {
7020b57cec5SDimitry Andric     // Check for SubRange Segments of the form [1234r,1234d:0) which can be
7030b57cec5SDimitry Andric     // removed to prevent creating bogus SubRange Segments.
7040b57cec5SDimitry Andric     LiveInterval::iterator SS = S.FindSegmentContaining(CopyIdx);
7050b57cec5SDimitry Andric     if (SS != S.end() && SlotIndex::isSameInstr(SS->start, SS->end)) {
7060b57cec5SDimitry Andric       S.removeSegment(*SS, true);
7070b57cec5SDimitry Andric       continue;
7080b57cec5SDimitry Andric     }
7095ffd83dbSDimitry Andric     // The subrange may have ended before FillerStart. If so, extend it.
7105ffd83dbSDimitry Andric     if (!S.getVNInfoAt(FillerStart)) {
7115ffd83dbSDimitry Andric       SlotIndex BBStart =
7125ffd83dbSDimitry Andric           LIS->getMBBStartIdx(LIS->getMBBFromIndex(FillerStart));
7135ffd83dbSDimitry Andric       S.extendInBlock(BBStart, FillerStart);
7145ffd83dbSDimitry Andric     }
7150b57cec5SDimitry Andric     VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
7160b57cec5SDimitry Andric     S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
7170b57cec5SDimitry Andric     VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
7180b57cec5SDimitry Andric     if (SubBValNo != SubValSNo)
7190b57cec5SDimitry Andric       S.MergeValueNumberInto(SubBValNo, SubValSNo);
7200b57cec5SDimitry Andric   }
7210b57cec5SDimitry Andric 
7220b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "   result = " << IntB << '\n');
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric   // If the source instruction was killing the source register before the
7250b57cec5SDimitry Andric   // merge, unset the isKill marker given the live range has been extended.
7260fca6ea1SDimitry Andric   int UIdx =
7270fca6ea1SDimitry Andric       ValSEndInst->findRegisterUseOperandIdx(IntB.reg(), /*TRI=*/nullptr, true);
7280b57cec5SDimitry Andric   if (UIdx != -1) {
7290b57cec5SDimitry Andric     ValSEndInst->getOperand(UIdx).setIsKill(false);
7300b57cec5SDimitry Andric   }
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric   // Rewrite the copy.
733e8d8bef9SDimitry Andric   CopyMI->substituteRegister(IntA.reg(), IntB.reg(), 0, *TRI);
7340b57cec5SDimitry Andric   // If the copy instruction was killing the destination register or any
7350b57cec5SDimitry Andric   // subrange before the merge trim the live range.
7360b57cec5SDimitry Andric   bool RecomputeLiveRange = AS->end == CopyIdx;
7370b57cec5SDimitry Andric   if (!RecomputeLiveRange) {
7380b57cec5SDimitry Andric     for (LiveInterval::SubRange &S : IntA.subranges()) {
7390b57cec5SDimitry Andric       LiveInterval::iterator SS = S.FindSegmentContaining(CopyUseIdx);
7400b57cec5SDimitry Andric       if (SS != S.end() && SS->end == CopyIdx) {
7410b57cec5SDimitry Andric         RecomputeLiveRange = true;
7420b57cec5SDimitry Andric         break;
7430b57cec5SDimitry Andric       }
7440b57cec5SDimitry Andric     }
7450b57cec5SDimitry Andric   }
7460b57cec5SDimitry Andric   if (RecomputeLiveRange)
7470b57cec5SDimitry Andric     shrinkToUses(&IntA);
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric   ++numExtends;
7500b57cec5SDimitry Andric   return true;
7510b57cec5SDimitry Andric }
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
7540b57cec5SDimitry Andric                                              LiveInterval &IntB,
7550b57cec5SDimitry Andric                                              VNInfo *AValNo,
7560b57cec5SDimitry Andric                                              VNInfo *BValNo) {
7570b57cec5SDimitry Andric   // If AValNo has PHI kills, conservatively assume that IntB defs can reach
7580b57cec5SDimitry Andric   // the PHI values.
7590b57cec5SDimitry Andric   if (LIS->hasPHIKill(IntA, AValNo))
7600b57cec5SDimitry Andric     return true;
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric   for (LiveRange::Segment &ASeg : IntA.segments) {
7630b57cec5SDimitry Andric     if (ASeg.valno != AValNo) continue;
7640b57cec5SDimitry Andric     LiveInterval::iterator BI = llvm::upper_bound(IntB, ASeg.start);
7650b57cec5SDimitry Andric     if (BI != IntB.begin())
7660b57cec5SDimitry Andric       --BI;
7670b57cec5SDimitry Andric     for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
7680b57cec5SDimitry Andric       if (BI->valno == BValNo)
7690b57cec5SDimitry Andric         continue;
7700b57cec5SDimitry Andric       if (BI->start <= ASeg.start && BI->end > ASeg.start)
7710b57cec5SDimitry Andric         return true;
7720b57cec5SDimitry Andric       if (BI->start > ASeg.start && BI->start < ASeg.end)
7730b57cec5SDimitry Andric         return true;
7740b57cec5SDimitry Andric     }
7750b57cec5SDimitry Andric   }
7760b57cec5SDimitry Andric   return false;
7770b57cec5SDimitry Andric }
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric /// Copy segments with value number @p SrcValNo from liverange @p Src to live
7800b57cec5SDimitry Andric /// range @Dst and use value number @p DstValNo there.
7810b57cec5SDimitry Andric static std::pair<bool,bool>
7820b57cec5SDimitry Andric addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo, const LiveRange &Src,
7830b57cec5SDimitry Andric                      const VNInfo *SrcValNo) {
7840b57cec5SDimitry Andric   bool Changed = false;
7850b57cec5SDimitry Andric   bool MergedWithDead = false;
7860b57cec5SDimitry Andric   for (const LiveRange::Segment &S : Src.segments) {
7870b57cec5SDimitry Andric     if (S.valno != SrcValNo)
7880b57cec5SDimitry Andric       continue;
7890b57cec5SDimitry Andric     // This is adding a segment from Src that ends in a copy that is about
7900b57cec5SDimitry Andric     // to be removed. This segment is going to be merged with a pre-existing
7910b57cec5SDimitry Andric     // segment in Dst. This works, except in cases when the corresponding
7920b57cec5SDimitry Andric     // segment in Dst is dead. For example: adding [192r,208r:1) from Src
7930b57cec5SDimitry Andric     // to [208r,208d:1) in Dst would create [192r,208d:1) in Dst.
7940b57cec5SDimitry Andric     // Recognized such cases, so that the segments can be shrunk.
7950b57cec5SDimitry Andric     LiveRange::Segment Added = LiveRange::Segment(S.start, S.end, DstValNo);
7960b57cec5SDimitry Andric     LiveRange::Segment &Merged = *Dst.addSegment(Added);
7970b57cec5SDimitry Andric     if (Merged.end.isDead())
7980b57cec5SDimitry Andric       MergedWithDead = true;
7990b57cec5SDimitry Andric     Changed = true;
8000b57cec5SDimitry Andric   }
8010b57cec5SDimitry Andric   return std::make_pair(Changed, MergedWithDead);
8020b57cec5SDimitry Andric }
8030b57cec5SDimitry Andric 
8040b57cec5SDimitry Andric std::pair<bool,bool>
8050b57cec5SDimitry Andric RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
8060b57cec5SDimitry Andric                                             MachineInstr *CopyMI) {
8070b57cec5SDimitry Andric   assert(!CP.isPhys());
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric   LiveInterval &IntA =
8100b57cec5SDimitry Andric       LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
8110b57cec5SDimitry Andric   LiveInterval &IntB =
8120b57cec5SDimitry Andric       LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric   // We found a non-trivially-coalescable copy with IntA being the source and
8150b57cec5SDimitry Andric   // IntB being the dest, thus this defines a value number in IntB.  If the
8160b57cec5SDimitry Andric   // source value number (in IntA) is defined by a commutable instruction and
8170b57cec5SDimitry Andric   // its other operand is coalesced to the copy dest register, see if we can
8180b57cec5SDimitry Andric   // transform the copy into a noop by commuting the definition. For example,
8190b57cec5SDimitry Andric   //
8200b57cec5SDimitry Andric   //  A3 = op A2 killed B0
8210b57cec5SDimitry Andric   //    ...
8220b57cec5SDimitry Andric   //  B1 = A3      <- this copy
8230b57cec5SDimitry Andric   //    ...
8240b57cec5SDimitry Andric   //     = op A3   <- more uses
8250b57cec5SDimitry Andric   //
8260b57cec5SDimitry Andric   // ==>
8270b57cec5SDimitry Andric   //
8280b57cec5SDimitry Andric   //  B2 = op B0 killed A2
8290b57cec5SDimitry Andric   //    ...
8300b57cec5SDimitry Andric   //  B1 = B2      <- now an identity copy
8310b57cec5SDimitry Andric   //    ...
8320b57cec5SDimitry Andric   //     = op B2   <- more uses
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric   // BValNo is a value number in B that is defined by a copy from A. 'B1' in
8350b57cec5SDimitry Andric   // the example above.
8360b57cec5SDimitry Andric   SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
8370b57cec5SDimitry Andric   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
8380b57cec5SDimitry Andric   assert(BValNo != nullptr && BValNo->def == CopyIdx);
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric   // AValNo is the value number in A that defines the copy, A3 in the example.
8410b57cec5SDimitry Andric   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
8420b57cec5SDimitry Andric   assert(AValNo && !AValNo->isUnused() && "COPY source not live");
8430b57cec5SDimitry Andric   if (AValNo->isPHIDef())
8440b57cec5SDimitry Andric     return { false, false };
8450b57cec5SDimitry Andric   MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
8460b57cec5SDimitry Andric   if (!DefMI)
8470b57cec5SDimitry Andric     return { false, false };
8480b57cec5SDimitry Andric   if (!DefMI->isCommutable())
8490b57cec5SDimitry Andric     return { false, false };
8500b57cec5SDimitry Andric   // If DefMI is a two-address instruction then commuting it will change the
8510b57cec5SDimitry Andric   // destination register.
8520fca6ea1SDimitry Andric   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg(), /*TRI=*/nullptr);
8530b57cec5SDimitry Andric   assert(DefIdx != -1);
8540b57cec5SDimitry Andric   unsigned UseOpIdx;
8550b57cec5SDimitry Andric   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
8560b57cec5SDimitry Andric     return { false, false };
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric   // FIXME: The code below tries to commute 'UseOpIdx' operand with some other
8590b57cec5SDimitry Andric   // commutable operand which is expressed by 'CommuteAnyOperandIndex'value
8600b57cec5SDimitry Andric   // passed to the method. That _other_ operand is chosen by
8610b57cec5SDimitry Andric   // the findCommutedOpIndices() method.
8620b57cec5SDimitry Andric   //
8630b57cec5SDimitry Andric   // That is obviously an area for improvement in case of instructions having
8640b57cec5SDimitry Andric   // more than 2 operands. For example, if some instruction has 3 commutable
8650b57cec5SDimitry Andric   // operands then all possible variants (i.e. op#1<->op#2, op#1<->op#3,
8660b57cec5SDimitry Andric   // op#2<->op#3) of commute transformation should be considered/tried here.
8670b57cec5SDimitry Andric   unsigned NewDstIdx = TargetInstrInfo::CommuteAnyOperandIndex;
8680b57cec5SDimitry Andric   if (!TII->findCommutedOpIndices(*DefMI, UseOpIdx, NewDstIdx))
8690b57cec5SDimitry Andric     return { false, false };
8700b57cec5SDimitry Andric 
8710b57cec5SDimitry Andric   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
8728bcb0991SDimitry Andric   Register NewReg = NewDstMO.getReg();
873e8d8bef9SDimitry Andric   if (NewReg != IntB.reg() || !IntB.Query(AValNo->def).isKill())
8740b57cec5SDimitry Andric     return { false, false };
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric   // Make sure there are no other definitions of IntB that would reach the
8770b57cec5SDimitry Andric   // uses which the new definition can reach.
8780b57cec5SDimitry Andric   if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
8790b57cec5SDimitry Andric     return { false, false };
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric   // If some of the uses of IntA.reg is already coalesced away, return false.
8820b57cec5SDimitry Andric   // It's not possible to determine whether it's safe to perform the coalescing.
883e8d8bef9SDimitry Andric   for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg())) {
8840b57cec5SDimitry Andric     MachineInstr *UseMI = MO.getParent();
8850b57cec5SDimitry Andric     unsigned OpNo = &MO - &UseMI->getOperand(0);
8860b57cec5SDimitry Andric     SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI);
8870b57cec5SDimitry Andric     LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
8880b57cec5SDimitry Andric     if (US == IntA.end() || US->valno != AValNo)
8890b57cec5SDimitry Andric       continue;
8900b57cec5SDimitry Andric     // If this use is tied to a def, we can't rewrite the register.
8910b57cec5SDimitry Andric     if (UseMI->isRegTiedToDefOperand(OpNo))
8920b57cec5SDimitry Andric       return { false, false };
8930b57cec5SDimitry Andric   }
8940b57cec5SDimitry Andric 
8950b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
8960b57cec5SDimitry Andric                     << *DefMI);
8970b57cec5SDimitry Andric 
8980b57cec5SDimitry Andric   // At this point we have decided that it is legal to do this
8990b57cec5SDimitry Andric   // transformation.  Start by commuting the instruction.
9000b57cec5SDimitry Andric   MachineBasicBlock *MBB = DefMI->getParent();
9010b57cec5SDimitry Andric   MachineInstr *NewMI =
9020b57cec5SDimitry Andric       TII->commuteInstruction(*DefMI, false, UseOpIdx, NewDstIdx);
9030b57cec5SDimitry Andric   if (!NewMI)
9040b57cec5SDimitry Andric     return { false, false };
905bdd1243dSDimitry Andric   if (IntA.reg().isVirtual() && IntB.reg().isVirtual() &&
906e8d8bef9SDimitry Andric       !MRI->constrainRegClass(IntB.reg(), MRI->getRegClass(IntA.reg())))
9070b57cec5SDimitry Andric     return { false, false };
9080b57cec5SDimitry Andric   if (NewMI != DefMI) {
9090b57cec5SDimitry Andric     LIS->ReplaceMachineInstrInMaps(*DefMI, *NewMI);
9100b57cec5SDimitry Andric     MachineBasicBlock::iterator Pos = DefMI;
9110b57cec5SDimitry Andric     MBB->insert(Pos, NewMI);
9120b57cec5SDimitry Andric     MBB->erase(DefMI);
9130b57cec5SDimitry Andric   }
9140b57cec5SDimitry Andric 
9150b57cec5SDimitry Andric   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
9160b57cec5SDimitry Andric   // A = or A, B
9170b57cec5SDimitry Andric   // ...
9180b57cec5SDimitry Andric   // B = A
9190b57cec5SDimitry Andric   // ...
9200b57cec5SDimitry Andric   // C = killed A
9210b57cec5SDimitry Andric   // ...
9220b57cec5SDimitry Andric   //   = B
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric   // Update uses of IntA of the specific Val# with IntB.
925349cc55cSDimitry Andric   for (MachineOperand &UseMO :
926349cc55cSDimitry Andric        llvm::make_early_inc_range(MRI->use_operands(IntA.reg()))) {
9270b57cec5SDimitry Andric     if (UseMO.isUndef())
9280b57cec5SDimitry Andric       continue;
9290b57cec5SDimitry Andric     MachineInstr *UseMI = UseMO.getParent();
930fe6060f1SDimitry Andric     if (UseMI->isDebugInstr()) {
9310b57cec5SDimitry Andric       // FIXME These don't have an instruction index.  Not clear we have enough
9320b57cec5SDimitry Andric       // info to decide whether to do this replacement or not.  For now do it.
9330b57cec5SDimitry Andric       UseMO.setReg(NewReg);
9340b57cec5SDimitry Andric       continue;
9350b57cec5SDimitry Andric     }
9360b57cec5SDimitry Andric     SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI).getRegSlot(true);
9370b57cec5SDimitry Andric     LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
9380b57cec5SDimitry Andric     assert(US != IntA.end() && "Use must be live");
9390b57cec5SDimitry Andric     if (US->valno != AValNo)
9400b57cec5SDimitry Andric       continue;
9410b57cec5SDimitry Andric     // Kill flags are no longer accurate. They are recomputed after RA.
9420b57cec5SDimitry Andric     UseMO.setIsKill(false);
943bdd1243dSDimitry Andric     if (NewReg.isPhysical())
9440b57cec5SDimitry Andric       UseMO.substPhysReg(NewReg, *TRI);
9450b57cec5SDimitry Andric     else
9460b57cec5SDimitry Andric       UseMO.setReg(NewReg);
9470b57cec5SDimitry Andric     if (UseMI == CopyMI)
9480b57cec5SDimitry Andric       continue;
9490b57cec5SDimitry Andric     if (!UseMI->isCopy())
9500b57cec5SDimitry Andric       continue;
951e8d8bef9SDimitry Andric     if (UseMI->getOperand(0).getReg() != IntB.reg() ||
9520b57cec5SDimitry Andric         UseMI->getOperand(0).getSubReg())
9530b57cec5SDimitry Andric       continue;
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric     // This copy will become a noop. If it's defining a new val#, merge it into
9560b57cec5SDimitry Andric     // BValNo.
9570b57cec5SDimitry Andric     SlotIndex DefIdx = UseIdx.getRegSlot();
9580b57cec5SDimitry Andric     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
9590b57cec5SDimitry Andric     if (!DVNI)
9600b57cec5SDimitry Andric       continue;
9610b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
9620b57cec5SDimitry Andric     assert(DVNI->def == DefIdx);
9630b57cec5SDimitry Andric     BValNo = IntB.MergeValueNumberInto(DVNI, BValNo);
9640b57cec5SDimitry Andric     for (LiveInterval::SubRange &S : IntB.subranges()) {
9650b57cec5SDimitry Andric       VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
9660b57cec5SDimitry Andric       if (!SubDVNI)
9670b57cec5SDimitry Andric         continue;
9680b57cec5SDimitry Andric       VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
9690b57cec5SDimitry Andric       assert(SubBValNo->def == CopyIdx);
9700b57cec5SDimitry Andric       S.MergeValueNumberInto(SubDVNI, SubBValNo);
9710b57cec5SDimitry Andric     }
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric     deleteInstr(UseMI);
9740b57cec5SDimitry Andric   }
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric   // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
9770b57cec5SDimitry Andric   // is updated.
9780b57cec5SDimitry Andric   bool ShrinkB = false;
9790b57cec5SDimitry Andric   BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
9800b57cec5SDimitry Andric   if (IntA.hasSubRanges() || IntB.hasSubRanges()) {
9810b57cec5SDimitry Andric     if (!IntA.hasSubRanges()) {
982e8d8bef9SDimitry Andric       LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntA.reg());
9830b57cec5SDimitry Andric       IntA.createSubRangeFrom(Allocator, Mask, IntA);
9840b57cec5SDimitry Andric     } else if (!IntB.hasSubRanges()) {
985e8d8bef9SDimitry Andric       LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntB.reg());
9860b57cec5SDimitry Andric       IntB.createSubRangeFrom(Allocator, Mask, IntB);
9870b57cec5SDimitry Andric     }
9880b57cec5SDimitry Andric     SlotIndex AIdx = CopyIdx.getRegSlot(true);
9890b57cec5SDimitry Andric     LaneBitmask MaskA;
9900b57cec5SDimitry Andric     const SlotIndexes &Indexes = *LIS->getSlotIndexes();
9910b57cec5SDimitry Andric     for (LiveInterval::SubRange &SA : IntA.subranges()) {
9920b57cec5SDimitry Andric       VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
9930b57cec5SDimitry Andric       // Even if we are dealing with a full copy, some lanes can
9940b57cec5SDimitry Andric       // still be undefined.
9950b57cec5SDimitry Andric       // E.g.,
9960b57cec5SDimitry Andric       // undef A.subLow = ...
9970b57cec5SDimitry Andric       // B = COPY A <== A.subHigh is undefined here and does
9980b57cec5SDimitry Andric       //                not have a value number.
9990b57cec5SDimitry Andric       if (!ASubValNo)
10000b57cec5SDimitry Andric         continue;
10010b57cec5SDimitry Andric       MaskA |= SA.LaneMask;
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric       IntB.refineSubRanges(
10040b57cec5SDimitry Andric           Allocator, SA.LaneMask,
10050b57cec5SDimitry Andric           [&Allocator, &SA, CopyIdx, ASubValNo,
10060b57cec5SDimitry Andric            &ShrinkB](LiveInterval::SubRange &SR) {
10070b57cec5SDimitry Andric             VNInfo *BSubValNo = SR.empty() ? SR.getNextValue(CopyIdx, Allocator)
10080b57cec5SDimitry Andric                                            : SR.getVNInfoAt(CopyIdx);
10090b57cec5SDimitry Andric             assert(BSubValNo != nullptr);
10100b57cec5SDimitry Andric             auto P = addSegmentsWithValNo(SR, BSubValNo, SA, ASubValNo);
10110b57cec5SDimitry Andric             ShrinkB |= P.second;
10120b57cec5SDimitry Andric             if (P.first)
10130b57cec5SDimitry Andric               BSubValNo->def = ASubValNo->def;
10140b57cec5SDimitry Andric           },
10150b57cec5SDimitry Andric           Indexes, *TRI);
10160b57cec5SDimitry Andric     }
10170b57cec5SDimitry Andric     // Go over all subranges of IntB that have not been covered by IntA,
10180b57cec5SDimitry Andric     // and delete the segments starting at CopyIdx. This can happen if
10190b57cec5SDimitry Andric     // IntA has undef lanes that are defined in IntB.
10200b57cec5SDimitry Andric     for (LiveInterval::SubRange &SB : IntB.subranges()) {
10210b57cec5SDimitry Andric       if ((SB.LaneMask & MaskA).any())
10220b57cec5SDimitry Andric         continue;
10230b57cec5SDimitry Andric       if (LiveRange::Segment *S = SB.getSegmentContaining(CopyIdx))
10240b57cec5SDimitry Andric         if (S->start.getBaseIndex() == CopyIdx.getBaseIndex())
10250b57cec5SDimitry Andric           SB.removeSegment(*S, true);
10260b57cec5SDimitry Andric     }
10270b57cec5SDimitry Andric   }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   BValNo->def = AValNo->def;
10300b57cec5SDimitry Andric   auto P = addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
10310b57cec5SDimitry Andric   ShrinkB |= P.second;
10320b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
10330b57cec5SDimitry Andric 
10340b57cec5SDimitry Andric   LIS->removeVRegDefAt(IntA, AValNo->def);
10350b57cec5SDimitry Andric 
10360b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
10370b57cec5SDimitry Andric   ++numCommutes;
10380b57cec5SDimitry Andric   return { true, ShrinkB };
10390b57cec5SDimitry Andric }
10400b57cec5SDimitry Andric 
10410b57cec5SDimitry Andric /// For copy B = A in BB2, if A is defined by A = B in BB0 which is a
10420b57cec5SDimitry Andric /// predecessor of BB2, and if B is not redefined on the way from A = B
10430b57cec5SDimitry Andric /// in BB0 to B = A in BB2, B = A in BB2 is partially redundant if the
10440b57cec5SDimitry Andric /// execution goes through the path from BB0 to BB2. We may move B = A
10450b57cec5SDimitry Andric /// to the predecessor without such reversed copy.
10460b57cec5SDimitry Andric /// So we will transform the program from:
10470b57cec5SDimitry Andric ///   BB0:
10480b57cec5SDimitry Andric ///      A = B;    BB1:
10490b57cec5SDimitry Andric ///       ...         ...
10500b57cec5SDimitry Andric ///     /     \      /
10510b57cec5SDimitry Andric ///             BB2:
10520b57cec5SDimitry Andric ///               ...
10530b57cec5SDimitry Andric ///               B = A;
10540b57cec5SDimitry Andric ///
10550b57cec5SDimitry Andric /// to:
10560b57cec5SDimitry Andric ///
10570b57cec5SDimitry Andric ///   BB0:         BB1:
10580b57cec5SDimitry Andric ///      A = B;        ...
10590b57cec5SDimitry Andric ///       ...          B = A;
10600b57cec5SDimitry Andric ///     /     \       /
10610b57cec5SDimitry Andric ///             BB2:
10620b57cec5SDimitry Andric ///               ...
10630b57cec5SDimitry Andric ///
10640b57cec5SDimitry Andric /// A special case is when BB0 and BB2 are the same BB which is the only
10650b57cec5SDimitry Andric /// BB in a loop:
10660b57cec5SDimitry Andric ///   BB1:
10670b57cec5SDimitry Andric ///        ...
10680b57cec5SDimitry Andric ///   BB0/BB2:  ----
10690b57cec5SDimitry Andric ///        B = A;   |
10700b57cec5SDimitry Andric ///        ...      |
10710b57cec5SDimitry Andric ///        A = B;   |
10720b57cec5SDimitry Andric ///          |-------
10730b57cec5SDimitry Andric ///          |
10740b57cec5SDimitry Andric /// We may hoist B = A from BB0/BB2 to BB1.
10750b57cec5SDimitry Andric ///
10760b57cec5SDimitry Andric /// The major preconditions for correctness to remove such partial
10770b57cec5SDimitry Andric /// redundancy include:
10780b57cec5SDimitry Andric /// 1. A in B = A in BB2 is defined by a PHI in BB2, and one operand of
10790b57cec5SDimitry Andric ///    the PHI is defined by the reversed copy A = B in BB0.
10800b57cec5SDimitry Andric /// 2. No B is referenced from the start of BB2 to B = A.
10810b57cec5SDimitry Andric /// 3. No B is defined from A = B to the end of BB0.
10820b57cec5SDimitry Andric /// 4. BB1 has only one successor.
10830b57cec5SDimitry Andric ///
10840b57cec5SDimitry Andric /// 2 and 4 implicitly ensure B is not live at the end of BB1.
10850b57cec5SDimitry Andric /// 4 guarantees BB2 is hotter than BB1, so we can only move a copy to a
10860b57cec5SDimitry Andric /// colder place, which not only prevent endless loop, but also make sure
10870b57cec5SDimitry Andric /// the movement of copy is beneficial.
10880b57cec5SDimitry Andric bool RegisterCoalescer::removePartialRedundancy(const CoalescerPair &CP,
10890b57cec5SDimitry Andric                                                 MachineInstr &CopyMI) {
10900b57cec5SDimitry Andric   assert(!CP.isPhys());
10910b57cec5SDimitry Andric   if (!CopyMI.isFullCopy())
10920b57cec5SDimitry Andric     return false;
10930b57cec5SDimitry Andric 
10940b57cec5SDimitry Andric   MachineBasicBlock &MBB = *CopyMI.getParent();
10955ffd83dbSDimitry Andric   // If this block is the target of an invoke/inlineasm_br, moving the copy into
10965ffd83dbSDimitry Andric   // the predecessor is tricker, and we don't handle it.
10975ffd83dbSDimitry Andric   if (MBB.isEHPad() || MBB.isInlineAsmBrIndirectTarget())
10980b57cec5SDimitry Andric     return false;
10990b57cec5SDimitry Andric 
11000b57cec5SDimitry Andric   if (MBB.pred_size() != 2)
11010b57cec5SDimitry Andric     return false;
11020b57cec5SDimitry Andric 
11030b57cec5SDimitry Andric   LiveInterval &IntA =
11040b57cec5SDimitry Andric       LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
11050b57cec5SDimitry Andric   LiveInterval &IntB =
11060b57cec5SDimitry Andric       LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
11070b57cec5SDimitry Andric 
11080b57cec5SDimitry Andric   // A is defined by PHI at the entry of MBB.
11090b57cec5SDimitry Andric   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
11100b57cec5SDimitry Andric   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx);
11110b57cec5SDimitry Andric   assert(AValNo && !AValNo->isUnused() && "COPY source not live");
11120b57cec5SDimitry Andric   if (!AValNo->isPHIDef())
11130b57cec5SDimitry Andric     return false;
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric   // No B is referenced before CopyMI in MBB.
11160b57cec5SDimitry Andric   if (IntB.overlaps(LIS->getMBBStartIdx(&MBB), CopyIdx))
11170b57cec5SDimitry Andric     return false;
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric   // MBB has two predecessors: one contains A = B so no copy will be inserted
11200b57cec5SDimitry Andric   // for it. The other one will have a copy moved from MBB.
11210b57cec5SDimitry Andric   bool FoundReverseCopy = false;
11220b57cec5SDimitry Andric   MachineBasicBlock *CopyLeftBB = nullptr;
11230b57cec5SDimitry Andric   for (MachineBasicBlock *Pred : MBB.predecessors()) {
11240b57cec5SDimitry Andric     VNInfo *PVal = IntA.getVNInfoBefore(LIS->getMBBEndIdx(Pred));
11250b57cec5SDimitry Andric     MachineInstr *DefMI = LIS->getInstructionFromIndex(PVal->def);
11260b57cec5SDimitry Andric     if (!DefMI || !DefMI->isFullCopy()) {
11270b57cec5SDimitry Andric       CopyLeftBB = Pred;
11280b57cec5SDimitry Andric       continue;
11290b57cec5SDimitry Andric     }
11300b57cec5SDimitry Andric     // Check DefMI is a reverse copy and it is in BB Pred.
1131e8d8bef9SDimitry Andric     if (DefMI->getOperand(0).getReg() != IntA.reg() ||
1132e8d8bef9SDimitry Andric         DefMI->getOperand(1).getReg() != IntB.reg() ||
11330b57cec5SDimitry Andric         DefMI->getParent() != Pred) {
11340b57cec5SDimitry Andric       CopyLeftBB = Pred;
11350b57cec5SDimitry Andric       continue;
11360b57cec5SDimitry Andric     }
11370b57cec5SDimitry Andric     // If there is any other def of B after DefMI and before the end of Pred,
11380b57cec5SDimitry Andric     // we need to keep the copy of B = A at the end of Pred if we remove
11390b57cec5SDimitry Andric     // B = A from MBB.
11400b57cec5SDimitry Andric     bool ValB_Changed = false;
1141fcaf7f86SDimitry Andric     for (auto *VNI : IntB.valnos) {
11420b57cec5SDimitry Andric       if (VNI->isUnused())
11430b57cec5SDimitry Andric         continue;
11440b57cec5SDimitry Andric       if (PVal->def < VNI->def && VNI->def < LIS->getMBBEndIdx(Pred)) {
11450b57cec5SDimitry Andric         ValB_Changed = true;
11460b57cec5SDimitry Andric         break;
11470b57cec5SDimitry Andric       }
11480b57cec5SDimitry Andric     }
11490b57cec5SDimitry Andric     if (ValB_Changed) {
11500b57cec5SDimitry Andric       CopyLeftBB = Pred;
11510b57cec5SDimitry Andric       continue;
11520b57cec5SDimitry Andric     }
11530b57cec5SDimitry Andric     FoundReverseCopy = true;
11540b57cec5SDimitry Andric   }
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric   // If no reverse copy is found in predecessors, nothing to do.
11570b57cec5SDimitry Andric   if (!FoundReverseCopy)
11580b57cec5SDimitry Andric     return false;
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric   // If CopyLeftBB is nullptr, it means every predecessor of MBB contains
11610b57cec5SDimitry Andric   // reverse copy, CopyMI can be removed trivially if only IntA/IntB is updated.
11620b57cec5SDimitry Andric   // If CopyLeftBB is not nullptr, move CopyMI from MBB to CopyLeftBB and
11630b57cec5SDimitry Andric   // update IntA/IntB.
11640b57cec5SDimitry Andric   //
11650b57cec5SDimitry Andric   // If CopyLeftBB is not nullptr, ensure CopyLeftBB has a single succ so
11660b57cec5SDimitry Andric   // MBB is hotter than CopyLeftBB.
11670b57cec5SDimitry Andric   if (CopyLeftBB && CopyLeftBB->succ_size() > 1)
11680b57cec5SDimitry Andric     return false;
11690b57cec5SDimitry Andric 
11700b57cec5SDimitry Andric   // Now (almost sure it's) ok to move copy.
11710b57cec5SDimitry Andric   if (CopyLeftBB) {
11720b57cec5SDimitry Andric     // Position in CopyLeftBB where we should insert new copy.
11730b57cec5SDimitry Andric     auto InsPos = CopyLeftBB->getFirstTerminator();
11740b57cec5SDimitry Andric 
11750b57cec5SDimitry Andric     // Make sure that B isn't referenced in the terminators (if any) at the end
11760b57cec5SDimitry Andric     // of the predecessor since we're about to insert a new definition of B
11770b57cec5SDimitry Andric     // before them.
11780b57cec5SDimitry Andric     if (InsPos != CopyLeftBB->end()) {
11790b57cec5SDimitry Andric       SlotIndex InsPosIdx = LIS->getInstructionIndex(*InsPos).getRegSlot(true);
11800b57cec5SDimitry Andric       if (IntB.overlaps(InsPosIdx, LIS->getMBBEndIdx(CopyLeftBB)))
11810b57cec5SDimitry Andric         return false;
11820b57cec5SDimitry Andric     }
11830b57cec5SDimitry Andric 
11840b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Move the copy to "
11850b57cec5SDimitry Andric                       << printMBBReference(*CopyLeftBB) << '\t' << CopyMI);
11860b57cec5SDimitry Andric 
11870b57cec5SDimitry Andric     // Insert new copy to CopyLeftBB.
11880b57cec5SDimitry Andric     MachineInstr *NewCopyMI = BuildMI(*CopyLeftBB, InsPos, CopyMI.getDebugLoc(),
1189e8d8bef9SDimitry Andric                                       TII->get(TargetOpcode::COPY), IntB.reg())
1190e8d8bef9SDimitry Andric                                   .addReg(IntA.reg());
11910b57cec5SDimitry Andric     SlotIndex NewCopyIdx =
11920b57cec5SDimitry Andric         LIS->InsertMachineInstrInMaps(*NewCopyMI).getRegSlot();
11930b57cec5SDimitry Andric     IntB.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
11940b57cec5SDimitry Andric     for (LiveInterval::SubRange &SR : IntB.subranges())
11950b57cec5SDimitry Andric       SR.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric     // If the newly created Instruction has an address of an instruction that was
11980b57cec5SDimitry Andric     // deleted before (object recycled by the allocator) it needs to be removed from
11990b57cec5SDimitry Andric     // the deleted list.
12000b57cec5SDimitry Andric     ErasedInstrs.erase(NewCopyMI);
12010b57cec5SDimitry Andric   } else {
12020b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Remove the copy from "
12030b57cec5SDimitry Andric                       << printMBBReference(MBB) << '\t' << CopyMI);
12040b57cec5SDimitry Andric   }
12050b57cec5SDimitry Andric 
12065f757f3fSDimitry Andric   const bool IsUndefCopy = CopyMI.getOperand(1).isUndef();
12075f757f3fSDimitry Andric 
12080b57cec5SDimitry Andric   // Remove CopyMI.
12090b57cec5SDimitry Andric   // Note: This is fine to remove the copy before updating the live-ranges.
12100b57cec5SDimitry Andric   // While updating the live-ranges, we only look at slot indices and
12110b57cec5SDimitry Andric   // never go back to the instruction.
12120b57cec5SDimitry Andric   // Mark instructions as deleted.
12130b57cec5SDimitry Andric   deleteInstr(&CopyMI);
12140b57cec5SDimitry Andric 
12150b57cec5SDimitry Andric   // Update the liveness.
12160b57cec5SDimitry Andric   SmallVector<SlotIndex, 8> EndPoints;
12170b57cec5SDimitry Andric   VNInfo *BValNo = IntB.Query(CopyIdx).valueOutOrDead();
12180b57cec5SDimitry Andric   LIS->pruneValue(*static_cast<LiveRange *>(&IntB), CopyIdx.getRegSlot(),
12190b57cec5SDimitry Andric                   &EndPoints);
12200b57cec5SDimitry Andric   BValNo->markUnused();
12215f757f3fSDimitry Andric 
12225f757f3fSDimitry Andric   if (IsUndefCopy) {
12235f757f3fSDimitry Andric     // We're introducing an undef phi def, and need to set undef on any users of
12245f757f3fSDimitry Andric     // the previously local def to avoid artifically extending the lifetime
12255f757f3fSDimitry Andric     // through the block.
12265f757f3fSDimitry Andric     for (MachineOperand &MO : MRI->use_nodbg_operands(IntB.reg())) {
12275f757f3fSDimitry Andric       const MachineInstr &MI = *MO.getParent();
12285f757f3fSDimitry Andric       SlotIndex UseIdx = LIS->getInstructionIndex(MI);
12295f757f3fSDimitry Andric       if (!IntB.liveAt(UseIdx))
12305f757f3fSDimitry Andric         MO.setIsUndef(true);
12315f757f3fSDimitry Andric     }
12325f757f3fSDimitry Andric   }
12335f757f3fSDimitry Andric 
12340b57cec5SDimitry Andric   // Extend IntB to the EndPoints of its original live interval.
12350b57cec5SDimitry Andric   LIS->extendToIndices(IntB, EndPoints);
12360b57cec5SDimitry Andric 
12370b57cec5SDimitry Andric   // Now, do the same for its subranges.
12380b57cec5SDimitry Andric   for (LiveInterval::SubRange &SR : IntB.subranges()) {
12390b57cec5SDimitry Andric     EndPoints.clear();
12400b57cec5SDimitry Andric     VNInfo *BValNo = SR.Query(CopyIdx).valueOutOrDead();
12410b57cec5SDimitry Andric     assert(BValNo && "All sublanes should be live");
12420b57cec5SDimitry Andric     LIS->pruneValue(SR, CopyIdx.getRegSlot(), &EndPoints);
12430b57cec5SDimitry Andric     BValNo->markUnused();
12440b57cec5SDimitry Andric     // We can have a situation where the result of the original copy is live,
12450b57cec5SDimitry Andric     // but is immediately dead in this subrange, e.g. [336r,336d:0). That makes
12460b57cec5SDimitry Andric     // the copy appear as an endpoint from pruneValue(), but we don't want it
12470b57cec5SDimitry Andric     // to because the copy has been removed.  We can go ahead and remove that
12480b57cec5SDimitry Andric     // endpoint; there is no other situation here that there could be a use at
12490b57cec5SDimitry Andric     // the same place as we know that the copy is a full copy.
12500b57cec5SDimitry Andric     for (unsigned I = 0; I != EndPoints.size(); ) {
12510b57cec5SDimitry Andric       if (SlotIndex::isSameInstr(EndPoints[I], CopyIdx)) {
12520b57cec5SDimitry Andric         EndPoints[I] = EndPoints.back();
12530b57cec5SDimitry Andric         EndPoints.pop_back();
12540b57cec5SDimitry Andric         continue;
12550b57cec5SDimitry Andric       }
12560b57cec5SDimitry Andric       ++I;
12570b57cec5SDimitry Andric     }
1258e8d8bef9SDimitry Andric     SmallVector<SlotIndex, 8> Undefs;
1259e8d8bef9SDimitry Andric     IntB.computeSubRangeUndefs(Undefs, SR.LaneMask, *MRI,
1260e8d8bef9SDimitry Andric                                *LIS->getSlotIndexes());
1261e8d8bef9SDimitry Andric     LIS->extendToIndices(SR, EndPoints, Undefs);
12620b57cec5SDimitry Andric   }
12630b57cec5SDimitry Andric   // If any dead defs were extended, truncate them.
12640b57cec5SDimitry Andric   shrinkToUses(&IntB);
12650b57cec5SDimitry Andric 
12660b57cec5SDimitry Andric   // Finally, update the live-range of IntA.
12670b57cec5SDimitry Andric   shrinkToUses(&IntA);
12680b57cec5SDimitry Andric   return true;
12690b57cec5SDimitry Andric }
12700b57cec5SDimitry Andric 
12710b57cec5SDimitry Andric /// Returns true if @p MI defines the full vreg @p Reg, as opposed to just
12720b57cec5SDimitry Andric /// defining a subregister.
1273e8d8bef9SDimitry Andric static bool definesFullReg(const MachineInstr &MI, Register Reg) {
1274e8d8bef9SDimitry Andric   assert(!Reg.isPhysical() && "This code cannot handle physreg aliasing");
1275e8d8bef9SDimitry Andric 
127606c3fb27SDimitry Andric   for (const MachineOperand &Op : MI.all_defs()) {
127706c3fb27SDimitry Andric     if (Op.getReg() != Reg)
12780b57cec5SDimitry Andric       continue;
12790b57cec5SDimitry Andric     // Return true if we define the full register or don't care about the value
12800b57cec5SDimitry Andric     // inside other subregisters.
12810b57cec5SDimitry Andric     if (Op.getSubReg() == 0 || Op.isUndef())
12820b57cec5SDimitry Andric       return true;
12830b57cec5SDimitry Andric   }
12840b57cec5SDimitry Andric   return false;
12850b57cec5SDimitry Andric }
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric bool RegisterCoalescer::reMaterializeTrivialDef(const CoalescerPair &CP,
12880b57cec5SDimitry Andric                                                 MachineInstr *CopyMI,
12890b57cec5SDimitry Andric                                                 bool &IsDefCopy) {
12900b57cec5SDimitry Andric   IsDefCopy = false;
1291e8d8bef9SDimitry Andric   Register SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
12920b57cec5SDimitry Andric   unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
1293e8d8bef9SDimitry Andric   Register DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
12940b57cec5SDimitry Andric   unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
1295bdd1243dSDimitry Andric   if (SrcReg.isPhysical())
12960b57cec5SDimitry Andric     return false;
12970b57cec5SDimitry Andric 
12980b57cec5SDimitry Andric   LiveInterval &SrcInt = LIS->getInterval(SrcReg);
12990b57cec5SDimitry Andric   SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
13000b57cec5SDimitry Andric   VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
13010b57cec5SDimitry Andric   if (!ValNo)
13020b57cec5SDimitry Andric     return false;
13030b57cec5SDimitry Andric   if (ValNo->isPHIDef() || ValNo->isUnused())
13040b57cec5SDimitry Andric     return false;
13050b57cec5SDimitry Andric   MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
13060b57cec5SDimitry Andric   if (!DefMI)
13070b57cec5SDimitry Andric     return false;
13080b57cec5SDimitry Andric   if (DefMI->isCopyLike()) {
13090b57cec5SDimitry Andric     IsDefCopy = true;
13100b57cec5SDimitry Andric     return false;
13110b57cec5SDimitry Andric   }
13120b57cec5SDimitry Andric   if (!TII->isAsCheapAsAMove(*DefMI))
13130b57cec5SDimitry Andric     return false;
1314bdd1243dSDimitry Andric 
1315bdd1243dSDimitry Andric   SmallVector<Register, 8> NewRegs;
1316bdd1243dSDimitry Andric   LiveRangeEdit Edit(&SrcInt, NewRegs, *MF, *LIS, nullptr, this);
1317bdd1243dSDimitry Andric   if (!Edit.checkRematerializable(ValNo, DefMI))
13180b57cec5SDimitry Andric     return false;
1319bdd1243dSDimitry Andric 
13200b57cec5SDimitry Andric   if (!definesFullReg(*DefMI, SrcReg))
13210b57cec5SDimitry Andric     return false;
13220b57cec5SDimitry Andric   bool SawStore = false;
13230b57cec5SDimitry Andric   if (!DefMI->isSafeToMove(AA, SawStore))
13240b57cec5SDimitry Andric     return false;
13250b57cec5SDimitry Andric   const MCInstrDesc &MCID = DefMI->getDesc();
13260b57cec5SDimitry Andric   if (MCID.getNumDefs() != 1)
13270b57cec5SDimitry Andric     return false;
13280b57cec5SDimitry Andric   // Only support subregister destinations when the def is read-undef.
13290b57cec5SDimitry Andric   MachineOperand &DstOperand = CopyMI->getOperand(0);
13308bcb0991SDimitry Andric   Register CopyDstReg = DstOperand.getReg();
13310b57cec5SDimitry Andric   if (DstOperand.getSubReg() && !DstOperand.isUndef())
13320b57cec5SDimitry Andric     return false;
13330b57cec5SDimitry Andric 
13340b57cec5SDimitry Andric   // If both SrcIdx and DstIdx are set, correct rematerialization would widen
13350b57cec5SDimitry Andric   // the register substantially (beyond both source and dest size). This is bad
13360b57cec5SDimitry Andric   // for performance since it can cascade through a function, introducing many
13370b57cec5SDimitry Andric   // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
13380b57cec5SDimitry Andric   // around after a few subreg copies).
13390b57cec5SDimitry Andric   if (SrcIdx && DstIdx)
13400b57cec5SDimitry Andric     return false;
13410b57cec5SDimitry Andric 
13420fca6ea1SDimitry Andric   const unsigned DefSubIdx = DefMI->getOperand(0).getSubReg();
13430b57cec5SDimitry Andric   const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
13440b57cec5SDimitry Andric   if (!DefMI->isImplicitDef()) {
1345e8d8bef9SDimitry Andric     if (DstReg.isPhysical()) {
1346e8d8bef9SDimitry Andric       Register NewDstReg = DstReg;
13470b57cec5SDimitry Andric 
13480fca6ea1SDimitry Andric       unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(), DefSubIdx);
13490b57cec5SDimitry Andric       if (NewDstIdx)
13500b57cec5SDimitry Andric         NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric       // Finally, make sure that the physical subregister that will be
13530b57cec5SDimitry Andric       // constructed later is permitted for the instruction.
13540b57cec5SDimitry Andric       if (!DefRC->contains(NewDstReg))
13550b57cec5SDimitry Andric         return false;
13560b57cec5SDimitry Andric     } else {
13570b57cec5SDimitry Andric       // Theoretically, some stack frame reference could exist. Just make sure
13580b57cec5SDimitry Andric       // it hasn't actually happened.
1359bdd1243dSDimitry Andric       assert(DstReg.isVirtual() &&
13600b57cec5SDimitry Andric              "Only expect to deal with virtual or physical registers");
13610b57cec5SDimitry Andric     }
13620b57cec5SDimitry Andric   }
13630b57cec5SDimitry Andric 
1364bdd1243dSDimitry Andric   LiveRangeEdit::Remat RM(ValNo);
1365bdd1243dSDimitry Andric   RM.OrigMI = DefMI;
1366bdd1243dSDimitry Andric   if (!Edit.canRematerializeAt(RM, ValNo, CopyIdx, true))
1367fe6060f1SDimitry Andric     return false;
1368fe6060f1SDimitry Andric 
13690b57cec5SDimitry Andric   DebugLoc DL = CopyMI->getDebugLoc();
13700b57cec5SDimitry Andric   MachineBasicBlock *MBB = CopyMI->getParent();
13710b57cec5SDimitry Andric   MachineBasicBlock::iterator MII =
13720b57cec5SDimitry Andric     std::next(MachineBasicBlock::iterator(CopyMI));
1373bdd1243dSDimitry Andric   Edit.rematerializeAt(*MBB, MII, DstReg, RM, *TRI, false, SrcIdx, CopyMI);
13740b57cec5SDimitry Andric   MachineInstr &NewMI = *std::prev(MII);
13750b57cec5SDimitry Andric   NewMI.setDebugLoc(DL);
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric   // In a situation like the following:
13780b57cec5SDimitry Andric   //     %0:subreg = instr              ; DefMI, subreg = DstIdx
13790b57cec5SDimitry Andric   //     %1        = copy %0:subreg ; CopyMI, SrcIdx = 0
13800b57cec5SDimitry Andric   // instead of widening %1 to the register class of %0 simply do:
13810b57cec5SDimitry Andric   //     %1 = instr
13820b57cec5SDimitry Andric   const TargetRegisterClass *NewRC = CP.getNewRC();
13830b57cec5SDimitry Andric   if (DstIdx != 0) {
13840b57cec5SDimitry Andric     MachineOperand &DefMO = NewMI.getOperand(0);
13850b57cec5SDimitry Andric     if (DefMO.getSubReg() == DstIdx) {
13860b57cec5SDimitry Andric       assert(SrcIdx == 0 && CP.isFlipped()
13870b57cec5SDimitry Andric              && "Shouldn't have SrcIdx+DstIdx at this point");
13880b57cec5SDimitry Andric       const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
13890b57cec5SDimitry Andric       const TargetRegisterClass *CommonRC =
13900b57cec5SDimitry Andric         TRI->getCommonSubClass(DefRC, DstRC);
13910b57cec5SDimitry Andric       if (CommonRC != nullptr) {
13920b57cec5SDimitry Andric         NewRC = CommonRC;
1393bdd1243dSDimitry Andric 
1394bdd1243dSDimitry Andric         // Instruction might contain "undef %0:subreg" as use operand:
1395bdd1243dSDimitry Andric         //   %0:subreg = instr op_1, ..., op_N, undef %0:subreg, op_N+2, ...
1396bdd1243dSDimitry Andric         //
1397bdd1243dSDimitry Andric         // Need to check all operands.
1398bdd1243dSDimitry Andric         for (MachineOperand &MO : NewMI.operands()) {
1399bdd1243dSDimitry Andric           if (MO.isReg() && MO.getReg() == DstReg && MO.getSubReg() == DstIdx) {
1400bdd1243dSDimitry Andric             MO.setSubReg(0);
1401bdd1243dSDimitry Andric           }
1402bdd1243dSDimitry Andric         }
1403bdd1243dSDimitry Andric 
14040b57cec5SDimitry Andric         DstIdx = 0;
14050b57cec5SDimitry Andric         DefMO.setIsUndef(false); // Only subregs can have def+undef.
14060b57cec5SDimitry Andric       }
14070b57cec5SDimitry Andric     }
14080b57cec5SDimitry Andric   }
14090b57cec5SDimitry Andric 
14100b57cec5SDimitry Andric   // CopyMI may have implicit operands, save them so that we can transfer them
14110b57cec5SDimitry Andric   // over to the newly materialized instruction after CopyMI is removed.
14120b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> ImplicitOps;
14130b57cec5SDimitry Andric   ImplicitOps.reserve(CopyMI->getNumOperands() -
14140b57cec5SDimitry Andric                       CopyMI->getDesc().getNumOperands());
14150b57cec5SDimitry Andric   for (unsigned I = CopyMI->getDesc().getNumOperands(),
14160b57cec5SDimitry Andric                 E = CopyMI->getNumOperands();
14170b57cec5SDimitry Andric        I != E; ++I) {
14180b57cec5SDimitry Andric     MachineOperand &MO = CopyMI->getOperand(I);
14190b57cec5SDimitry Andric     if (MO.isReg()) {
14200b57cec5SDimitry Andric       assert(MO.isImplicit() && "No explicit operands after implicit operands.");
14215f757f3fSDimitry Andric       assert((MO.getReg().isPhysical() ||
14225f757f3fSDimitry Andric               (MO.getSubReg() == 0 && MO.getReg() == DstOperand.getReg())) &&
14235f757f3fSDimitry Andric              "unexpected implicit virtual register def");
14240b57cec5SDimitry Andric       ImplicitOps.push_back(MO);
14250b57cec5SDimitry Andric     }
14260b57cec5SDimitry Andric   }
14270b57cec5SDimitry Andric 
14280b57cec5SDimitry Andric   CopyMI->eraseFromParent();
14290b57cec5SDimitry Andric   ErasedInstrs.insert(CopyMI);
14300b57cec5SDimitry Andric 
14310b57cec5SDimitry Andric   // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
14320b57cec5SDimitry Andric   // We need to remember these so we can add intervals once we insert
14330b57cec5SDimitry Andric   // NewMI into SlotIndexes.
14345f757f3fSDimitry Andric   //
14355f757f3fSDimitry Andric   // We also expect to have tied implicit-defs of super registers originating
14365f757f3fSDimitry Andric   // from SUBREG_TO_REG, such as:
14375f757f3fSDimitry Andric   // $edi = MOV32r0 implicit-def dead $eflags, implicit-def $rdi
14385f757f3fSDimitry Andric   // undef %0.sub_32bit = MOV32r0 implicit-def dead $eflags, implicit-def %0
14395f757f3fSDimitry Andric   //
14405f757f3fSDimitry Andric   // The implicit-def of the super register may have been reduced to
14415f757f3fSDimitry Andric   // subregisters depending on the uses.
14425f757f3fSDimitry Andric 
14435f757f3fSDimitry Andric   bool NewMIDefinesFullReg = false;
14445f757f3fSDimitry Andric 
1445e8d8bef9SDimitry Andric   SmallVector<MCRegister, 4> NewMIImplDefs;
14460b57cec5SDimitry Andric   for (unsigned i = NewMI.getDesc().getNumOperands(),
14470b57cec5SDimitry Andric                 e = NewMI.getNumOperands();
14480b57cec5SDimitry Andric        i != e; ++i) {
14490b57cec5SDimitry Andric     MachineOperand &MO = NewMI.getOperand(i);
14500b57cec5SDimitry Andric     if (MO.isReg() && MO.isDef()) {
14515f757f3fSDimitry Andric       assert(MO.isImplicit());
14525f757f3fSDimitry Andric       if (MO.getReg().isPhysical()) {
14535f757f3fSDimitry Andric         if (MO.getReg() == DstReg)
14545f757f3fSDimitry Andric           NewMIDefinesFullReg = true;
14555f757f3fSDimitry Andric 
14565f757f3fSDimitry Andric         assert(MO.isImplicit() && MO.getReg().isPhysical() &&
14575f757f3fSDimitry Andric                (MO.isDead() ||
14585f757f3fSDimitry Andric                 (DefSubIdx &&
14595f757f3fSDimitry Andric                  ((TRI->getSubReg(MO.getReg(), DefSubIdx) ==
14605f757f3fSDimitry Andric                    MCRegister((unsigned)NewMI.getOperand(0).getReg())) ||
14615f757f3fSDimitry Andric                   TRI->isSubRegisterEq(NewMI.getOperand(0).getReg(),
14625f757f3fSDimitry Andric                                        MO.getReg())))));
1463e8d8bef9SDimitry Andric         NewMIImplDefs.push_back(MO.getReg().asMCReg());
14645f757f3fSDimitry Andric       } else {
14655f757f3fSDimitry Andric         assert(MO.getReg() == NewMI.getOperand(0).getReg());
14665f757f3fSDimitry Andric 
14675f757f3fSDimitry Andric         // We're only expecting another def of the main output, so the range
14685f757f3fSDimitry Andric         // should get updated with the regular output range.
14695f757f3fSDimitry Andric         //
14705f757f3fSDimitry Andric         // FIXME: The range updating below probably needs updating to look at
14715f757f3fSDimitry Andric         // the super register if subranges are tracked.
14725f757f3fSDimitry Andric         assert(!MRI->shouldTrackSubRegLiveness(DstReg) &&
14735f757f3fSDimitry Andric                "subrange update for implicit-def of super register may not be "
14745f757f3fSDimitry Andric                "properly handled");
14755f757f3fSDimitry Andric       }
14760b57cec5SDimitry Andric     }
14770b57cec5SDimitry Andric   }
14780b57cec5SDimitry Andric 
1479e8d8bef9SDimitry Andric   if (DstReg.isVirtual()) {
14800b57cec5SDimitry Andric     unsigned NewIdx = NewMI.getOperand(0).getSubReg();
14810b57cec5SDimitry Andric 
14820b57cec5SDimitry Andric     if (DefRC != nullptr) {
14830b57cec5SDimitry Andric       if (NewIdx)
14840b57cec5SDimitry Andric         NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
14850b57cec5SDimitry Andric       else
14860b57cec5SDimitry Andric         NewRC = TRI->getCommonSubClass(NewRC, DefRC);
14870b57cec5SDimitry Andric       assert(NewRC && "subreg chosen for remat incompatible with instruction");
14880b57cec5SDimitry Andric     }
14890b57cec5SDimitry Andric     // Remap subranges to new lanemask and change register class.
14900b57cec5SDimitry Andric     LiveInterval &DstInt = LIS->getInterval(DstReg);
14910b57cec5SDimitry Andric     for (LiveInterval::SubRange &SR : DstInt.subranges()) {
14920b57cec5SDimitry Andric       SR.LaneMask = TRI->composeSubRegIndexLaneMask(DstIdx, SR.LaneMask);
14930b57cec5SDimitry Andric     }
14940b57cec5SDimitry Andric     MRI->setRegClass(DstReg, NewRC);
14950b57cec5SDimitry Andric 
14960b57cec5SDimitry Andric     // Update machine operands and add flags.
1497edc2dc17SDimitry Andric     updateRegDefsUses(DstReg, DstReg, DstIdx);
14980b57cec5SDimitry Andric     NewMI.getOperand(0).setSubReg(NewIdx);
14990b57cec5SDimitry Andric     // updateRegDefUses can add an "undef" flag to the definition, since
15000b57cec5SDimitry Andric     // it will replace DstReg with DstReg.DstIdx. If NewIdx is 0, make
15010b57cec5SDimitry Andric     // sure that "undef" is not set.
15020b57cec5SDimitry Andric     if (NewIdx == 0)
15030b57cec5SDimitry Andric       NewMI.getOperand(0).setIsUndef(false);
15040b57cec5SDimitry Andric     // Add dead subregister definitions if we are defining the whole register
15050b57cec5SDimitry Andric     // but only part of it is live.
15060b57cec5SDimitry Andric     // This could happen if the rematerialization instruction is rematerializing
15070b57cec5SDimitry Andric     // more than actually is used in the register.
15080b57cec5SDimitry Andric     // An example would be:
15090b57cec5SDimitry Andric     // %1 = LOAD CONSTANTS 5, 8 ; Loading both 5 and 8 in different subregs
15100b57cec5SDimitry Andric     // ; Copying only part of the register here, but the rest is undef.
15110b57cec5SDimitry Andric     // %2:sub_16bit<def, read-undef> = COPY %1:sub_16bit
15120b57cec5SDimitry Andric     // ==>
15130b57cec5SDimitry Andric     // ; Materialize all the constants but only using one
15140b57cec5SDimitry Andric     // %2 = LOAD_CONSTANTS 5, 8
15150b57cec5SDimitry Andric     //
15160b57cec5SDimitry Andric     // at this point for the part that wasn't defined before we could have
15170b57cec5SDimitry Andric     // subranges missing the definition.
15180b57cec5SDimitry Andric     if (NewIdx == 0 && DstInt.hasSubRanges()) {
15190b57cec5SDimitry Andric       SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
15200b57cec5SDimitry Andric       SlotIndex DefIndex =
15210b57cec5SDimitry Andric           CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
15220b57cec5SDimitry Andric       LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(DstReg);
15230b57cec5SDimitry Andric       VNInfo::Allocator& Alloc = LIS->getVNInfoAllocator();
15240b57cec5SDimitry Andric       for (LiveInterval::SubRange &SR : DstInt.subranges()) {
15250b57cec5SDimitry Andric         if (!SR.liveAt(DefIndex))
15260b57cec5SDimitry Andric           SR.createDeadDef(DefIndex, Alloc);
15270b57cec5SDimitry Andric         MaxMask &= ~SR.LaneMask;
15280b57cec5SDimitry Andric       }
15290b57cec5SDimitry Andric       if (MaxMask.any()) {
15300b57cec5SDimitry Andric         LiveInterval::SubRange *SR = DstInt.createSubRange(Alloc, MaxMask);
15310b57cec5SDimitry Andric         SR->createDeadDef(DefIndex, Alloc);
15320b57cec5SDimitry Andric       }
15330b57cec5SDimitry Andric     }
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric     // Make sure that the subrange for resultant undef is removed
15360b57cec5SDimitry Andric     // For example:
15370b57cec5SDimitry Andric     //   %1:sub1<def,read-undef> = LOAD CONSTANT 1
15380b57cec5SDimitry Andric     //   %2 = COPY %1
15390b57cec5SDimitry Andric     // ==>
15400b57cec5SDimitry Andric     //   %2:sub1<def, read-undef> = LOAD CONSTANT 1
15410b57cec5SDimitry Andric     //     ; Correct but need to remove the subrange for %2:sub0
15420b57cec5SDimitry Andric     //     ; as it is now undef
15430b57cec5SDimitry Andric     if (NewIdx != 0 && DstInt.hasSubRanges()) {
15440b57cec5SDimitry Andric       // The affected subregister segments can be removed.
15450b57cec5SDimitry Andric       SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
15460b57cec5SDimitry Andric       LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(NewIdx);
15470b57cec5SDimitry Andric       bool UpdatedSubRanges = false;
15485ffd83dbSDimitry Andric       SlotIndex DefIndex =
15495ffd83dbSDimitry Andric           CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
15505ffd83dbSDimitry Andric       VNInfo::Allocator &Alloc = LIS->getVNInfoAllocator();
15510b57cec5SDimitry Andric       for (LiveInterval::SubRange &SR : DstInt.subranges()) {
15520b57cec5SDimitry Andric         if ((SR.LaneMask & DstMask).none()) {
15530b57cec5SDimitry Andric           LLVM_DEBUG(dbgs()
15540b57cec5SDimitry Andric                      << "Removing undefined SubRange "
15550b57cec5SDimitry Andric                      << PrintLaneMask(SR.LaneMask) << " : " << SR << "\n");
155606c3fb27SDimitry Andric 
15570b57cec5SDimitry Andric           if (VNInfo *RmValNo = SR.getVNInfoAt(CurrIdx.getRegSlot())) {
155806c3fb27SDimitry Andric             // VNI is in ValNo - remove any segments in this SubRange that have
155906c3fb27SDimitry Andric             // this ValNo
15600b57cec5SDimitry Andric             SR.removeValNo(RmValNo);
15610b57cec5SDimitry Andric           }
156206c3fb27SDimitry Andric 
156306c3fb27SDimitry Andric           // We may not have a defined value at this point, but still need to
156406c3fb27SDimitry Andric           // clear out any empty subranges tentatively created by
156506c3fb27SDimitry Andric           // updateRegDefUses. The original subrange def may have only undefed
156606c3fb27SDimitry Andric           // some lanes.
156706c3fb27SDimitry Andric           UpdatedSubRanges = true;
15685ffd83dbSDimitry Andric         } else {
15695ffd83dbSDimitry Andric           // We know that this lane is defined by this instruction,
15705ffd83dbSDimitry Andric           // but at this point it may be empty because it is not used by
15715ffd83dbSDimitry Andric           // anything. This happens when updateRegDefUses adds the missing
15725ffd83dbSDimitry Andric           // lanes. Assign that lane a dead def so that the interferences
15735ffd83dbSDimitry Andric           // are properly modeled.
15745ffd83dbSDimitry Andric           if (SR.empty())
15755ffd83dbSDimitry Andric             SR.createDeadDef(DefIndex, Alloc);
15760b57cec5SDimitry Andric         }
15770b57cec5SDimitry Andric       }
15780b57cec5SDimitry Andric       if (UpdatedSubRanges)
15790b57cec5SDimitry Andric         DstInt.removeEmptySubRanges();
15800b57cec5SDimitry Andric     }
15810b57cec5SDimitry Andric   } else if (NewMI.getOperand(0).getReg() != CopyDstReg) {
15820b57cec5SDimitry Andric     // The New instruction may be defining a sub-register of what's actually
15830b57cec5SDimitry Andric     // been asked for. If so it must implicitly define the whole thing.
1584bdd1243dSDimitry Andric     assert(DstReg.isPhysical() &&
15850b57cec5SDimitry Andric            "Only expect virtual or physical registers in remat");
15860b57cec5SDimitry Andric     NewMI.getOperand(0).setIsDead(true);
15875f757f3fSDimitry Andric 
15885f757f3fSDimitry Andric     if (!NewMIDefinesFullReg) {
15890b57cec5SDimitry Andric       NewMI.addOperand(MachineOperand::CreateReg(
15900b57cec5SDimitry Andric           CopyDstReg, true /*IsDef*/, true /*IsImp*/, false /*IsKill*/));
15915f757f3fSDimitry Andric     }
15925f757f3fSDimitry Andric 
15930b57cec5SDimitry Andric     // Record small dead def live-ranges for all the subregisters
15940b57cec5SDimitry Andric     // of the destination register.
15950b57cec5SDimitry Andric     // Otherwise, variables that live through may miss some
15960b57cec5SDimitry Andric     // interferences, thus creating invalid allocation.
15970b57cec5SDimitry Andric     // E.g., i386 code:
15980b57cec5SDimitry Andric     // %1 = somedef ; %1 GR8
15990b57cec5SDimitry Andric     // %2 = remat ; %2 GR32
16000b57cec5SDimitry Andric     // CL = COPY %2.sub_8bit
16010b57cec5SDimitry Andric     // = somedef %1 ; %1 GR8
16020b57cec5SDimitry Andric     // =>
16030b57cec5SDimitry Andric     // %1 = somedef ; %1 GR8
16040b57cec5SDimitry Andric     // dead ECX = remat ; implicit-def CL
16050b57cec5SDimitry Andric     // = somedef %1 ; %1 GR8
16060b57cec5SDimitry Andric     // %1 will see the interferences with CL but not with CH since
16070b57cec5SDimitry Andric     // no live-ranges would have been created for ECX.
16080b57cec5SDimitry Andric     // Fix that!
16090b57cec5SDimitry Andric     SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
161006c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(NewMI.getOperand(0).getReg()))
161106c3fb27SDimitry Andric       if (LiveRange *LR = LIS->getCachedRegUnit(Unit))
16120b57cec5SDimitry Andric         LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
16130b57cec5SDimitry Andric   }
16140b57cec5SDimitry Andric 
16155f757f3fSDimitry Andric   NewMI.setRegisterDefReadUndef(NewMI.getOperand(0).getReg());
16160b57cec5SDimitry Andric 
16170b57cec5SDimitry Andric   // Transfer over implicit operands to the rematerialized instruction.
16180b57cec5SDimitry Andric   for (MachineOperand &MO : ImplicitOps)
16190b57cec5SDimitry Andric     NewMI.addOperand(MO);
16200b57cec5SDimitry Andric 
16210b57cec5SDimitry Andric   SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1622cb14a3feSDimitry Andric   for (MCRegister Reg : NewMIImplDefs) {
162306c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(Reg))
162406c3fb27SDimitry Andric       if (LiveRange *LR = LIS->getCachedRegUnit(Unit))
16250b57cec5SDimitry Andric         LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
16260b57cec5SDimitry Andric   }
16270b57cec5SDimitry Andric 
16280b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Remat: " << NewMI);
16290b57cec5SDimitry Andric   ++NumReMats;
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric   // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
16320b57cec5SDimitry Andric   // to describe DstReg instead.
16330b57cec5SDimitry Andric   if (MRI->use_nodbg_empty(SrcReg)) {
1634349cc55cSDimitry Andric     for (MachineOperand &UseMO :
1635349cc55cSDimitry Andric          llvm::make_early_inc_range(MRI->use_operands(SrcReg))) {
16360b57cec5SDimitry Andric       MachineInstr *UseMI = UseMO.getParent();
1637fe6060f1SDimitry Andric       if (UseMI->isDebugInstr()) {
1638bdd1243dSDimitry Andric         if (DstReg.isPhysical())
16390b57cec5SDimitry Andric           UseMO.substPhysReg(DstReg, *TRI);
16400b57cec5SDimitry Andric         else
16410b57cec5SDimitry Andric           UseMO.setReg(DstReg);
16420b57cec5SDimitry Andric         // Move the debug value directly after the def of the rematerialized
16430b57cec5SDimitry Andric         // value in DstReg.
16440b57cec5SDimitry Andric         MBB->splice(std::next(NewMI.getIterator()), UseMI->getParent(), UseMI);
16450b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
16460b57cec5SDimitry Andric       }
16470b57cec5SDimitry Andric     }
16480b57cec5SDimitry Andric   }
16490b57cec5SDimitry Andric 
16500b57cec5SDimitry Andric   if (ToBeUpdated.count(SrcReg))
16510b57cec5SDimitry Andric     return true;
16520b57cec5SDimitry Andric 
16530b57cec5SDimitry Andric   unsigned NumCopyUses = 0;
16540b57cec5SDimitry Andric   for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
16550b57cec5SDimitry Andric     if (UseMO.getParent()->isCopyLike())
16560b57cec5SDimitry Andric       NumCopyUses++;
16570b57cec5SDimitry Andric   }
16580b57cec5SDimitry Andric   if (NumCopyUses < LateRematUpdateThreshold) {
16590b57cec5SDimitry Andric     // The source interval can become smaller because we removed a use.
16600b57cec5SDimitry Andric     shrinkToUses(&SrcInt, &DeadDefs);
16610b57cec5SDimitry Andric     if (!DeadDefs.empty())
1662bdd1243dSDimitry Andric       eliminateDeadDefs(&Edit);
16630b57cec5SDimitry Andric   } else {
16640b57cec5SDimitry Andric     ToBeUpdated.insert(SrcReg);
16650b57cec5SDimitry Andric   }
16660b57cec5SDimitry Andric   return true;
16670b57cec5SDimitry Andric }
16680b57cec5SDimitry Andric 
16690b57cec5SDimitry Andric MachineInstr *RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
16700b57cec5SDimitry Andric   // ProcessImplicitDefs may leave some copies of <undef> values, it only
16710b57cec5SDimitry Andric   // removes local variables. When we have a copy like:
16720b57cec5SDimitry Andric   //
16730b57cec5SDimitry Andric   //   %1 = COPY undef %2
16740b57cec5SDimitry Andric   //
16750b57cec5SDimitry Andric   // We delete the copy and remove the corresponding value number from %1.
16760b57cec5SDimitry Andric   // Any uses of that value number are marked as <undef>.
16770b57cec5SDimitry Andric 
16780b57cec5SDimitry Andric   // Note that we do not query CoalescerPair here but redo isMoveInstr as the
16790b57cec5SDimitry Andric   // CoalescerPair may have a new register class with adjusted subreg indices
16800b57cec5SDimitry Andric   // at this point.
1681e8d8bef9SDimitry Andric   Register SrcReg, DstReg;
1682e8d8bef9SDimitry Andric   unsigned SrcSubIdx = 0, DstSubIdx = 0;
16830b57cec5SDimitry Andric   if(!isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
16840b57cec5SDimitry Andric     return nullptr;
16850b57cec5SDimitry Andric 
16860b57cec5SDimitry Andric   SlotIndex Idx = LIS->getInstructionIndex(*CopyMI);
16870b57cec5SDimitry Andric   const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
16880b57cec5SDimitry Andric   // CopyMI is undef iff SrcReg is not live before the instruction.
16890b57cec5SDimitry Andric   if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
16900b57cec5SDimitry Andric     LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
16910b57cec5SDimitry Andric     for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
16920b57cec5SDimitry Andric       if ((SR.LaneMask & SrcMask).none())
16930b57cec5SDimitry Andric         continue;
16940b57cec5SDimitry Andric       if (SR.liveAt(Idx))
16950b57cec5SDimitry Andric         return nullptr;
16960b57cec5SDimitry Andric     }
16970b57cec5SDimitry Andric   } else if (SrcLI.liveAt(Idx))
16980b57cec5SDimitry Andric     return nullptr;
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric   // If the undef copy defines a live-out value (i.e. an input to a PHI def),
17010b57cec5SDimitry Andric   // then replace it with an IMPLICIT_DEF.
17020b57cec5SDimitry Andric   LiveInterval &DstLI = LIS->getInterval(DstReg);
17030b57cec5SDimitry Andric   SlotIndex RegIndex = Idx.getRegSlot();
17040b57cec5SDimitry Andric   LiveRange::Segment *Seg = DstLI.getSegmentContaining(RegIndex);
17050b57cec5SDimitry Andric   assert(Seg != nullptr && "No segment for defining instruction");
1706bdd1243dSDimitry Andric   VNInfo *V = DstLI.getVNInfoAt(Seg->end);
1707bdd1243dSDimitry Andric 
1708bdd1243dSDimitry Andric   // The source interval may also have been on an undef use, in which case the
1709bdd1243dSDimitry Andric   // copy introduced a live value.
1710bdd1243dSDimitry Andric   if (((V && V->isPHIDef()) || (!V && !DstLI.liveAt(Idx)))) {
17110b57cec5SDimitry Andric     for (unsigned i = CopyMI->getNumOperands(); i != 0; --i) {
17120b57cec5SDimitry Andric       MachineOperand &MO = CopyMI->getOperand(i-1);
17135f757f3fSDimitry Andric       if (MO.isReg()) {
17145f757f3fSDimitry Andric         if (MO.isUse())
17155f757f3fSDimitry Andric           CopyMI->removeOperand(i - 1);
17165f757f3fSDimitry Andric       } else {
17175f757f3fSDimitry Andric         assert(MO.isImm() &&
17185f757f3fSDimitry Andric                CopyMI->getOpcode() == TargetOpcode::SUBREG_TO_REG);
171981ad6265SDimitry Andric         CopyMI->removeOperand(i-1);
17200b57cec5SDimitry Andric       }
17215f757f3fSDimitry Andric     }
17225f757f3fSDimitry Andric 
17235f757f3fSDimitry Andric     CopyMI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
17240b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tReplaced copy of <undef> value with an "
17250b57cec5SDimitry Andric                "implicit def\n");
17260b57cec5SDimitry Andric     return CopyMI;
17270b57cec5SDimitry Andric   }
17280b57cec5SDimitry Andric 
17290b57cec5SDimitry Andric   // Remove any DstReg segments starting at the instruction.
17300b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric   // Remove value or merge with previous one in case of a subregister def.
17330b57cec5SDimitry Andric   if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
17340b57cec5SDimitry Andric     VNInfo *VNI = DstLI.getVNInfoAt(RegIndex);
17350b57cec5SDimitry Andric     DstLI.MergeValueNumberInto(VNI, PrevVNI);
17360b57cec5SDimitry Andric 
17370b57cec5SDimitry Andric     // The affected subregister segments can be removed.
17380b57cec5SDimitry Andric     LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
17390b57cec5SDimitry Andric     for (LiveInterval::SubRange &SR : DstLI.subranges()) {
17400b57cec5SDimitry Andric       if ((SR.LaneMask & DstMask).none())
17410b57cec5SDimitry Andric         continue;
17420b57cec5SDimitry Andric 
17430b57cec5SDimitry Andric       VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
17440b57cec5SDimitry Andric       assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex));
17450b57cec5SDimitry Andric       SR.removeValNo(SVNI);
17460b57cec5SDimitry Andric     }
17470b57cec5SDimitry Andric     DstLI.removeEmptySubRanges();
17480b57cec5SDimitry Andric   } else
17490b57cec5SDimitry Andric     LIS->removeVRegDefAt(DstLI, RegIndex);
17500b57cec5SDimitry Andric 
17510b57cec5SDimitry Andric   // Mark uses as undef.
17520b57cec5SDimitry Andric   for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
17530b57cec5SDimitry Andric     if (MO.isDef() /*|| MO.isUndef()*/)
17540b57cec5SDimitry Andric       continue;
17550b57cec5SDimitry Andric     const MachineInstr &MI = *MO.getParent();
17560b57cec5SDimitry Andric     SlotIndex UseIdx = LIS->getInstructionIndex(MI);
17570b57cec5SDimitry Andric     LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
17580b57cec5SDimitry Andric     bool isLive;
17590b57cec5SDimitry Andric     if (!UseMask.all() && DstLI.hasSubRanges()) {
17600b57cec5SDimitry Andric       isLive = false;
17610b57cec5SDimitry Andric       for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
17620b57cec5SDimitry Andric         if ((SR.LaneMask & UseMask).none())
17630b57cec5SDimitry Andric           continue;
17640b57cec5SDimitry Andric         if (SR.liveAt(UseIdx)) {
17650b57cec5SDimitry Andric           isLive = true;
17660b57cec5SDimitry Andric           break;
17670b57cec5SDimitry Andric         }
17680b57cec5SDimitry Andric       }
17690b57cec5SDimitry Andric     } else
17700b57cec5SDimitry Andric       isLive = DstLI.liveAt(UseIdx);
17710b57cec5SDimitry Andric     if (isLive)
17720b57cec5SDimitry Andric       continue;
17730b57cec5SDimitry Andric     MO.setIsUndef(true);
17740b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
17750b57cec5SDimitry Andric   }
17760b57cec5SDimitry Andric 
17770b57cec5SDimitry Andric   // A def of a subregister may be a use of the other subregisters, so
17780b57cec5SDimitry Andric   // deleting a def of a subregister may also remove uses. Since CopyMI
17790b57cec5SDimitry Andric   // is still part of the function (but about to be erased), mark all
17800b57cec5SDimitry Andric   // defs of DstReg in it as <undef>, so that shrinkToUses would
17810b57cec5SDimitry Andric   // ignore them.
178206c3fb27SDimitry Andric   for (MachineOperand &MO : CopyMI->all_defs())
178306c3fb27SDimitry Andric     if (MO.getReg() == DstReg)
17840b57cec5SDimitry Andric       MO.setIsUndef(true);
17850b57cec5SDimitry Andric   LIS->shrinkToUses(&DstLI);
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric   return CopyMI;
17880b57cec5SDimitry Andric }
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric void RegisterCoalescer::addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
17910b57cec5SDimitry Andric                                      MachineOperand &MO, unsigned SubRegIdx) {
17920b57cec5SDimitry Andric   LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubRegIdx);
17930b57cec5SDimitry Andric   if (MO.isDef())
17940b57cec5SDimitry Andric     Mask = ~Mask;
17950b57cec5SDimitry Andric   bool IsUndef = true;
17960b57cec5SDimitry Andric   for (const LiveInterval::SubRange &S : Int.subranges()) {
17970b57cec5SDimitry Andric     if ((S.LaneMask & Mask).none())
17980b57cec5SDimitry Andric       continue;
17990b57cec5SDimitry Andric     if (S.liveAt(UseIdx)) {
18000b57cec5SDimitry Andric       IsUndef = false;
18010b57cec5SDimitry Andric       break;
18020b57cec5SDimitry Andric     }
18030b57cec5SDimitry Andric   }
18040b57cec5SDimitry Andric   if (IsUndef) {
18050b57cec5SDimitry Andric     MO.setIsUndef(true);
18060b57cec5SDimitry Andric     // We found out some subregister use is actually reading an undefined
18070b57cec5SDimitry Andric     // value. In some cases the whole vreg has become undefined at this
18080b57cec5SDimitry Andric     // point so we have to potentially shrink the main range if the
18090b57cec5SDimitry Andric     // use was ending a live segment there.
18100b57cec5SDimitry Andric     LiveQueryResult Q = Int.Query(UseIdx);
18110b57cec5SDimitry Andric     if (Q.valueOut() == nullptr)
18120b57cec5SDimitry Andric       ShrinkMainRange = true;
18130b57cec5SDimitry Andric   }
18140b57cec5SDimitry Andric }
18150b57cec5SDimitry Andric 
1816e8d8bef9SDimitry Andric void RegisterCoalescer::updateRegDefsUses(Register SrcReg, Register DstReg,
1817edc2dc17SDimitry Andric                                           unsigned SubIdx) {
1818bdd1243dSDimitry Andric   bool DstIsPhys = DstReg.isPhysical();
18190b57cec5SDimitry Andric   LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
18200b57cec5SDimitry Andric 
18210b57cec5SDimitry Andric   if (DstInt && DstInt->hasSubRanges() && DstReg != SrcReg) {
18220b57cec5SDimitry Andric     for (MachineOperand &MO : MRI->reg_operands(DstReg)) {
18230b57cec5SDimitry Andric       unsigned SubReg = MO.getSubReg();
18240b57cec5SDimitry Andric       if (SubReg == 0 || MO.isUndef())
18250b57cec5SDimitry Andric         continue;
18260b57cec5SDimitry Andric       MachineInstr &MI = *MO.getParent();
1827fe6060f1SDimitry Andric       if (MI.isDebugInstr())
18280b57cec5SDimitry Andric         continue;
18290b57cec5SDimitry Andric       SlotIndex UseIdx = LIS->getInstructionIndex(MI).getRegSlot(true);
18300b57cec5SDimitry Andric       addUndefFlag(*DstInt, UseIdx, MO, SubReg);
18310b57cec5SDimitry Andric     }
18320b57cec5SDimitry Andric   }
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric   SmallPtrSet<MachineInstr*, 8> Visited;
18350b57cec5SDimitry Andric   for (MachineRegisterInfo::reg_instr_iterator
18360b57cec5SDimitry Andric        I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
18370b57cec5SDimitry Andric        I != E; ) {
18380b57cec5SDimitry Andric     MachineInstr *UseMI = &*(I++);
18390b57cec5SDimitry Andric 
18400b57cec5SDimitry Andric     // Each instruction can only be rewritten once because sub-register
18410b57cec5SDimitry Andric     // composition is not always idempotent. When SrcReg != DstReg, rewriting
18420b57cec5SDimitry Andric     // the UseMI operands removes them from the SrcReg use-def chain, but when
18430b57cec5SDimitry Andric     // SrcReg is DstReg we could encounter UseMI twice if it has multiple
18440b57cec5SDimitry Andric     // operands mentioning the virtual register.
18450b57cec5SDimitry Andric     if (SrcReg == DstReg && !Visited.insert(UseMI).second)
18460b57cec5SDimitry Andric       continue;
18470b57cec5SDimitry Andric 
18480b57cec5SDimitry Andric     SmallVector<unsigned,8> Ops;
18490b57cec5SDimitry Andric     bool Reads, Writes;
18500b57cec5SDimitry Andric     std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
18510b57cec5SDimitry Andric 
18520b57cec5SDimitry Andric     // If SrcReg wasn't read, it may still be the case that DstReg is live-in
18530b57cec5SDimitry Andric     // because SrcReg is a sub-register.
1854fe6060f1SDimitry Andric     if (DstInt && !Reads && SubIdx && !UseMI->isDebugInstr())
18550b57cec5SDimitry Andric       Reads = DstInt->liveAt(LIS->getInstructionIndex(*UseMI));
18560b57cec5SDimitry Andric 
18570b57cec5SDimitry Andric     // Replace SrcReg with DstReg in all UseMI operands.
18580fca6ea1SDimitry Andric     for (unsigned Op : Ops) {
18590fca6ea1SDimitry Andric       MachineOperand &MO = UseMI->getOperand(Op);
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric       // Adjust <undef> flags in case of sub-register joins. We don't want to
18620b57cec5SDimitry Andric       // turn a full def into a read-modify-write sub-register def and vice
18630b57cec5SDimitry Andric       // versa.
1864edc2dc17SDimitry Andric       if (SubIdx && MO.isDef())
18650b57cec5SDimitry Andric         MO.setIsUndef(!Reads);
18660b57cec5SDimitry Andric 
18670b57cec5SDimitry Andric       // A subreg use of a partially undef (super) register may be a complete
18680b57cec5SDimitry Andric       // undef use now and then has to be marked that way.
1869fe6060f1SDimitry Andric       if (MO.isUse() && !DstIsPhys) {
1870fe6060f1SDimitry Andric         unsigned SubUseIdx = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
1871fe6060f1SDimitry Andric         if (SubUseIdx != 0 && MRI->shouldTrackSubRegLiveness(DstReg)) {
18720b57cec5SDimitry Andric           if (!DstInt->hasSubRanges()) {
18730b57cec5SDimitry Andric             BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
1874e8d8bef9SDimitry Andric             LaneBitmask FullMask = MRI->getMaxLaneMaskForVReg(DstInt->reg());
1875480093f4SDimitry Andric             LaneBitmask UsedLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1876480093f4SDimitry Andric             LaneBitmask UnusedLanes = FullMask & ~UsedLanes;
1877480093f4SDimitry Andric             DstInt->createSubRangeFrom(Allocator, UsedLanes, *DstInt);
1878480093f4SDimitry Andric             // The unused lanes are just empty live-ranges at this point.
1879480093f4SDimitry Andric             // It is the caller responsibility to set the proper
1880480093f4SDimitry Andric             // dead segments if there is an actual dead def of the
1881480093f4SDimitry Andric             // unused lanes. This may happen with rematerialization.
1882480093f4SDimitry Andric             DstInt->createSubRange(Allocator, UnusedLanes);
18830b57cec5SDimitry Andric           }
1884fe6060f1SDimitry Andric           SlotIndex MIIdx = UseMI->isDebugInstr()
18850b57cec5SDimitry Andric             ? LIS->getSlotIndexes()->getIndexBefore(*UseMI)
18860b57cec5SDimitry Andric             : LIS->getInstructionIndex(*UseMI);
18870b57cec5SDimitry Andric           SlotIndex UseIdx = MIIdx.getRegSlot(true);
1888fe6060f1SDimitry Andric           addUndefFlag(*DstInt, UseIdx, MO, SubUseIdx);
1889fe6060f1SDimitry Andric         }
18900b57cec5SDimitry Andric       }
18910b57cec5SDimitry Andric 
18920b57cec5SDimitry Andric       if (DstIsPhys)
18930b57cec5SDimitry Andric         MO.substPhysReg(DstReg, *TRI);
18940b57cec5SDimitry Andric       else
18950b57cec5SDimitry Andric         MO.substVirtReg(DstReg, SubIdx, *TRI);
18960b57cec5SDimitry Andric     }
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric     LLVM_DEBUG({
18990b57cec5SDimitry Andric       dbgs() << "\t\tupdated: ";
1900fe6060f1SDimitry Andric       if (!UseMI->isDebugInstr())
19010b57cec5SDimitry Andric         dbgs() << LIS->getInstructionIndex(*UseMI) << "\t";
19020b57cec5SDimitry Andric       dbgs() << *UseMI;
19030b57cec5SDimitry Andric     });
19040b57cec5SDimitry Andric   }
19050b57cec5SDimitry Andric }
19060b57cec5SDimitry Andric 
19070b57cec5SDimitry Andric bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
19080b57cec5SDimitry Andric   // Always join simple intervals that are defined by a single copy from a
19090b57cec5SDimitry Andric   // reserved register. This doesn't increase register pressure, so it is
19100b57cec5SDimitry Andric   // always beneficial.
19110b57cec5SDimitry Andric   if (!MRI->isReserved(CP.getDstReg())) {
19120b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
19130b57cec5SDimitry Andric     return false;
19140b57cec5SDimitry Andric   }
19150b57cec5SDimitry Andric 
19160b57cec5SDimitry Andric   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
19170b57cec5SDimitry Andric   if (JoinVInt.containsOneValue())
19180b57cec5SDimitry Andric     return true;
19190b57cec5SDimitry Andric 
19200b57cec5SDimitry Andric   LLVM_DEBUG(
19210b57cec5SDimitry Andric       dbgs() << "\tCannot join complex intervals into reserved register.\n");
19220b57cec5SDimitry Andric   return false;
19230b57cec5SDimitry Andric }
19240b57cec5SDimitry Andric 
1925e8d8bef9SDimitry Andric bool RegisterCoalescer::copyValueUndefInPredecessors(
1926e8d8bef9SDimitry Andric     LiveRange &S, const MachineBasicBlock *MBB, LiveQueryResult SLRQ) {
1927e8d8bef9SDimitry Andric   for (const MachineBasicBlock *Pred : MBB->predecessors()) {
1928e8d8bef9SDimitry Andric     SlotIndex PredEnd = LIS->getMBBEndIdx(Pred);
1929e8d8bef9SDimitry Andric     if (VNInfo *V = S.getVNInfoAt(PredEnd.getPrevSlot())) {
1930e8d8bef9SDimitry Andric       // If this is a self loop, we may be reading the same value.
1931e8d8bef9SDimitry Andric       if (V->id != SLRQ.valueOutOrDead()->id)
1932e8d8bef9SDimitry Andric         return false;
1933e8d8bef9SDimitry Andric     }
1934e8d8bef9SDimitry Andric   }
1935e8d8bef9SDimitry Andric 
1936e8d8bef9SDimitry Andric   return true;
1937e8d8bef9SDimitry Andric }
1938e8d8bef9SDimitry Andric 
1939e8d8bef9SDimitry Andric void RegisterCoalescer::setUndefOnPrunedSubRegUses(LiveInterval &LI,
1940e8d8bef9SDimitry Andric                                                    Register Reg,
1941e8d8bef9SDimitry Andric                                                    LaneBitmask PrunedLanes) {
1942e8d8bef9SDimitry Andric   // If we had other instructions in the segment reading the undef sublane
1943e8d8bef9SDimitry Andric   // value, we need to mark them with undef.
1944e8d8bef9SDimitry Andric   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
1945e8d8bef9SDimitry Andric     unsigned SubRegIdx = MO.getSubReg();
1946e8d8bef9SDimitry Andric     if (SubRegIdx == 0 || MO.isUndef())
1947e8d8bef9SDimitry Andric       continue;
1948e8d8bef9SDimitry Andric 
1949e8d8bef9SDimitry Andric     LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
1950e8d8bef9SDimitry Andric     SlotIndex Pos = LIS->getInstructionIndex(*MO.getParent());
1951e8d8bef9SDimitry Andric     for (LiveInterval::SubRange &S : LI.subranges()) {
1952e8d8bef9SDimitry Andric       if (!S.liveAt(Pos) && (PrunedLanes & SubRegMask).any()) {
1953e8d8bef9SDimitry Andric         MO.setIsUndef();
1954e8d8bef9SDimitry Andric         break;
1955e8d8bef9SDimitry Andric       }
1956e8d8bef9SDimitry Andric     }
1957e8d8bef9SDimitry Andric   }
1958e8d8bef9SDimitry Andric 
1959e8d8bef9SDimitry Andric   LI.removeEmptySubRanges();
1960e8d8bef9SDimitry Andric 
1961e8d8bef9SDimitry Andric   // A def of a subregister may be a use of other register lanes. Replacing
1962e8d8bef9SDimitry Andric   // such a def with a def of a different register will eliminate the use,
1963e8d8bef9SDimitry Andric   // and may cause the recorded live range to be larger than the actual
1964e8d8bef9SDimitry Andric   // liveness in the program IR.
1965e8d8bef9SDimitry Andric   LIS->shrinkToUses(&LI);
1966e8d8bef9SDimitry Andric }
1967e8d8bef9SDimitry Andric 
196874626c16SDimitry Andric bool RegisterCoalescer::joinCopy(
196974626c16SDimitry Andric     MachineInstr *CopyMI, bool &Again,
197074626c16SDimitry Andric     SmallPtrSetImpl<MachineInstr *> &CurrentErasedInstrs) {
19710b57cec5SDimitry Andric   Again = false;
19720b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI);
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric   CoalescerPair CP(*TRI);
19750b57cec5SDimitry Andric   if (!CP.setRegisters(CopyMI)) {
19760b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tNot coalescable.\n");
19770b57cec5SDimitry Andric     return false;
19780b57cec5SDimitry Andric   }
19790b57cec5SDimitry Andric 
19800b57cec5SDimitry Andric   if (CP.getNewRC()) {
19810b57cec5SDimitry Andric     auto SrcRC = MRI->getRegClass(CP.getSrcReg());
19820b57cec5SDimitry Andric     auto DstRC = MRI->getRegClass(CP.getDstReg());
19830b57cec5SDimitry Andric     unsigned SrcIdx = CP.getSrcIdx();
19840b57cec5SDimitry Andric     unsigned DstIdx = CP.getDstIdx();
19850b57cec5SDimitry Andric     if (CP.isFlipped()) {
19860b57cec5SDimitry Andric       std::swap(SrcIdx, DstIdx);
19870b57cec5SDimitry Andric       std::swap(SrcRC, DstRC);
19880b57cec5SDimitry Andric     }
19890b57cec5SDimitry Andric     if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
19900b57cec5SDimitry Andric                              CP.getNewRC(), *LIS)) {
19910b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
19920b57cec5SDimitry Andric       return false;
19930b57cec5SDimitry Andric     }
19940b57cec5SDimitry Andric   }
19950b57cec5SDimitry Andric 
19960b57cec5SDimitry Andric   // Dead code elimination. This really should be handled by MachineDCE, but
19970b57cec5SDimitry Andric   // sometimes dead copies slip through, and we can't generate invalid live
19980b57cec5SDimitry Andric   // ranges.
19990b57cec5SDimitry Andric   if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
20000b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tCopy is dead.\n");
20010b57cec5SDimitry Andric     DeadDefs.push_back(CopyMI);
20020b57cec5SDimitry Andric     eliminateDeadDefs();
20030b57cec5SDimitry Andric     return true;
20040b57cec5SDimitry Andric   }
20050b57cec5SDimitry Andric 
20060b57cec5SDimitry Andric   // Eliminate undefs.
20070b57cec5SDimitry Andric   if (!CP.isPhys()) {
20080b57cec5SDimitry Andric     // If this is an IMPLICIT_DEF, leave it alone, but don't try to coalesce.
20090b57cec5SDimitry Andric     if (MachineInstr *UndefMI = eliminateUndefCopy(CopyMI)) {
20100b57cec5SDimitry Andric       if (UndefMI->isImplicitDef())
20110b57cec5SDimitry Andric         return false;
20120b57cec5SDimitry Andric       deleteInstr(CopyMI);
20130b57cec5SDimitry Andric       return false;  // Not coalescable.
20140b57cec5SDimitry Andric     }
20150b57cec5SDimitry Andric   }
20160b57cec5SDimitry Andric 
20170b57cec5SDimitry Andric   // Coalesced copies are normally removed immediately, but transformations
20180b57cec5SDimitry Andric   // like removeCopyByCommutingDef() can inadvertently create identity copies.
20190b57cec5SDimitry Andric   // When that happens, just join the values and remove the copy.
20200b57cec5SDimitry Andric   if (CP.getSrcReg() == CP.getDstReg()) {
20210b57cec5SDimitry Andric     LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
20220b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
20230b57cec5SDimitry Andric     const SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
20240b57cec5SDimitry Andric     LiveQueryResult LRQ = LI.Query(CopyIdx);
20250b57cec5SDimitry Andric     if (VNInfo *DefVNI = LRQ.valueDefined()) {
20260b57cec5SDimitry Andric       VNInfo *ReadVNI = LRQ.valueIn();
20270b57cec5SDimitry Andric       assert(ReadVNI && "No value before copy and no <undef> flag.");
20280b57cec5SDimitry Andric       assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
2029e8d8bef9SDimitry Andric 
2030e8d8bef9SDimitry Andric       // Track incoming undef lanes we need to eliminate from the subrange.
2031e8d8bef9SDimitry Andric       LaneBitmask PrunedLanes;
2032e8d8bef9SDimitry Andric       MachineBasicBlock *MBB = CopyMI->getParent();
20330b57cec5SDimitry Andric 
20340b57cec5SDimitry Andric       // Process subregister liveranges.
20350b57cec5SDimitry Andric       for (LiveInterval::SubRange &S : LI.subranges()) {
20360b57cec5SDimitry Andric         LiveQueryResult SLRQ = S.Query(CopyIdx);
20370b57cec5SDimitry Andric         if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
2038e8d8bef9SDimitry Andric           if (VNInfo *SReadVNI = SLRQ.valueIn())
2039e8d8bef9SDimitry Andric             SDefVNI = S.MergeValueNumberInto(SDefVNI, SReadVNI);
2040e8d8bef9SDimitry Andric 
2041e8d8bef9SDimitry Andric           // If this copy introduced an undef subrange from an incoming value,
2042e8d8bef9SDimitry Andric           // we need to eliminate the undef live in values from the subrange.
2043e8d8bef9SDimitry Andric           if (copyValueUndefInPredecessors(S, MBB, SLRQ)) {
2044e8d8bef9SDimitry Andric             LLVM_DEBUG(dbgs() << "Incoming sublane value is undef at copy\n");
2045e8d8bef9SDimitry Andric             PrunedLanes |= S.LaneMask;
2046e8d8bef9SDimitry Andric             S.removeValNo(SDefVNI);
20470b57cec5SDimitry Andric           }
20480b57cec5SDimitry Andric         }
2049e8d8bef9SDimitry Andric       }
2050e8d8bef9SDimitry Andric 
2051e8d8bef9SDimitry Andric       LI.MergeValueNumberInto(DefVNI, ReadVNI);
2052e8d8bef9SDimitry Andric       if (PrunedLanes.any()) {
2053e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "Pruning undef incoming lanes: "
2054e8d8bef9SDimitry Andric                           << PrunedLanes << '\n');
2055e8d8bef9SDimitry Andric         setUndefOnPrunedSubRegUses(LI, CP.getSrcReg(), PrunedLanes);
2056e8d8bef9SDimitry Andric       }
2057e8d8bef9SDimitry Andric 
20580b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\tMerged values:          " << LI << '\n');
20590b57cec5SDimitry Andric     }
20600b57cec5SDimitry Andric     deleteInstr(CopyMI);
20610b57cec5SDimitry Andric     return true;
20620b57cec5SDimitry Andric   }
20630b57cec5SDimitry Andric 
20640b57cec5SDimitry Andric   // Enforce policies.
20650b57cec5SDimitry Andric   if (CP.isPhys()) {
20660b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tConsidering merging "
20670b57cec5SDimitry Andric                       << printReg(CP.getSrcReg(), TRI) << " with "
20680b57cec5SDimitry Andric                       << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n');
20690b57cec5SDimitry Andric     if (!canJoinPhys(CP)) {
20700b57cec5SDimitry Andric       // Before giving up coalescing, if definition of source is defined by
20710b57cec5SDimitry Andric       // trivial computation, try rematerializing it.
2072e8d8bef9SDimitry Andric       bool IsDefCopy = false;
20730b57cec5SDimitry Andric       if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
20740b57cec5SDimitry Andric         return true;
20750b57cec5SDimitry Andric       if (IsDefCopy)
20760b57cec5SDimitry Andric         Again = true;  // May be possible to coalesce later.
20770b57cec5SDimitry Andric       return false;
20780b57cec5SDimitry Andric     }
20790b57cec5SDimitry Andric   } else {
20800b57cec5SDimitry Andric     // When possible, let DstReg be the larger interval.
20810b57cec5SDimitry Andric     if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
20820b57cec5SDimitry Andric                            LIS->getInterval(CP.getDstReg()).size())
20830b57cec5SDimitry Andric       CP.flip();
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric     LLVM_DEBUG({
20860b57cec5SDimitry Andric       dbgs() << "\tConsidering merging to "
20870b57cec5SDimitry Andric              << TRI->getRegClassName(CP.getNewRC()) << " with ";
20880b57cec5SDimitry Andric       if (CP.getDstIdx() && CP.getSrcIdx())
20890b57cec5SDimitry Andric         dbgs() << printReg(CP.getDstReg()) << " in "
20900b57cec5SDimitry Andric                << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
20910b57cec5SDimitry Andric                << printReg(CP.getSrcReg()) << " in "
20920b57cec5SDimitry Andric                << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
20930b57cec5SDimitry Andric       else
20940b57cec5SDimitry Andric         dbgs() << printReg(CP.getSrcReg(), TRI) << " in "
20950b57cec5SDimitry Andric                << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
20960b57cec5SDimitry Andric     });
20970b57cec5SDimitry Andric   }
20980b57cec5SDimitry Andric 
20990b57cec5SDimitry Andric   ShrinkMask = LaneBitmask::getNone();
21000b57cec5SDimitry Andric   ShrinkMainRange = false;
21010b57cec5SDimitry Andric 
21020b57cec5SDimitry Andric   // Okay, attempt to join these two intervals.  On failure, this returns false.
21030b57cec5SDimitry Andric   // Otherwise, if one of the intervals being joined is a physreg, this method
21040b57cec5SDimitry Andric   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
21050b57cec5SDimitry Andric   // been modified, so we can use this information below to update aliases.
21060b57cec5SDimitry Andric   if (!joinIntervals(CP)) {
21070b57cec5SDimitry Andric     // Coalescing failed.
21080b57cec5SDimitry Andric 
21090b57cec5SDimitry Andric     // If definition of source is defined by trivial computation, try
21100b57cec5SDimitry Andric     // rematerializing it.
2111e8d8bef9SDimitry Andric     bool IsDefCopy = false;
21120b57cec5SDimitry Andric     if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
21130b57cec5SDimitry Andric       return true;
21140b57cec5SDimitry Andric 
21150b57cec5SDimitry Andric     // If we can eliminate the copy without merging the live segments, do so
21160b57cec5SDimitry Andric     // now.
21170b57cec5SDimitry Andric     if (!CP.isPartial() && !CP.isPhys()) {
21180b57cec5SDimitry Andric       bool Changed = adjustCopiesBackFrom(CP, CopyMI);
21190b57cec5SDimitry Andric       bool Shrink = false;
21200b57cec5SDimitry Andric       if (!Changed)
21210b57cec5SDimitry Andric         std::tie(Changed, Shrink) = removeCopyByCommutingDef(CP, CopyMI);
21220b57cec5SDimitry Andric       if (Changed) {
21230b57cec5SDimitry Andric         deleteInstr(CopyMI);
21240b57cec5SDimitry Andric         if (Shrink) {
2125e8d8bef9SDimitry Andric           Register DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
21260b57cec5SDimitry Andric           LiveInterval &DstLI = LIS->getInterval(DstReg);
21270b57cec5SDimitry Andric           shrinkToUses(&DstLI);
21280b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << "\t\tshrunk:   " << DstLI << '\n');
21290b57cec5SDimitry Andric         }
21300b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "\tTrivial!\n");
21310b57cec5SDimitry Andric         return true;
21320b57cec5SDimitry Andric       }
21330b57cec5SDimitry Andric     }
21340b57cec5SDimitry Andric 
21350b57cec5SDimitry Andric     // Try and see if we can partially eliminate the copy by moving the copy to
21360b57cec5SDimitry Andric     // its predecessor.
21370b57cec5SDimitry Andric     if (!CP.isPartial() && !CP.isPhys())
21380b57cec5SDimitry Andric       if (removePartialRedundancy(CP, *CopyMI))
21390b57cec5SDimitry Andric         return true;
21400b57cec5SDimitry Andric 
21410b57cec5SDimitry Andric     // Otherwise, we are unable to join the intervals.
21420b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tInterference!\n");
21430b57cec5SDimitry Andric     Again = true;  // May be possible to coalesce later.
21440b57cec5SDimitry Andric     return false;
21450b57cec5SDimitry Andric   }
21460b57cec5SDimitry Andric 
21470b57cec5SDimitry Andric   // Coalescing to a virtual register that is of a sub-register class of the
21480b57cec5SDimitry Andric   // other. Make sure the resulting register is set to the right register class.
21490b57cec5SDimitry Andric   if (CP.isCrossClass()) {
21500b57cec5SDimitry Andric     ++numCrossRCs;
21510b57cec5SDimitry Andric     MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
21520b57cec5SDimitry Andric   }
21530b57cec5SDimitry Andric 
21540b57cec5SDimitry Andric   // Removing sub-register copies can ease the register class constraints.
21550b57cec5SDimitry Andric   // Make sure we attempt to inflate the register class of DstReg.
21560b57cec5SDimitry Andric   if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
21570b57cec5SDimitry Andric     InflateRegs.push_back(CP.getDstReg());
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric   // CopyMI has been erased by joinIntervals at this point. Remove it from
21600b57cec5SDimitry Andric   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
21610b57cec5SDimitry Andric   // to the work list. This keeps ErasedInstrs from growing needlessly.
216274626c16SDimitry Andric   if (ErasedInstrs.erase(CopyMI))
216374626c16SDimitry Andric     // But we may encounter the instruction again in this iteration.
216474626c16SDimitry Andric     CurrentErasedInstrs.insert(CopyMI);
21650b57cec5SDimitry Andric 
21660b57cec5SDimitry Andric   // Rewrite all SrcReg operands to DstReg.
21670b57cec5SDimitry Andric   // Also update DstReg operands to include DstIdx if it is set.
2168edc2dc17SDimitry Andric   if (CP.getDstIdx())
2169edc2dc17SDimitry Andric     updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
2170edc2dc17SDimitry Andric   updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
21710b57cec5SDimitry Andric 
21720b57cec5SDimitry Andric   // Shrink subregister ranges if necessary.
21730b57cec5SDimitry Andric   if (ShrinkMask.any()) {
21740b57cec5SDimitry Andric     LiveInterval &LI = LIS->getInterval(CP.getDstReg());
21750b57cec5SDimitry Andric     for (LiveInterval::SubRange &S : LI.subranges()) {
21760b57cec5SDimitry Andric       if ((S.LaneMask & ShrinkMask).none())
21770b57cec5SDimitry Andric         continue;
21780b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask)
21790b57cec5SDimitry Andric                         << ")\n");
2180e8d8bef9SDimitry Andric       LIS->shrinkToUses(S, LI.reg());
2181bdd1243dSDimitry Andric       ShrinkMainRange = true;
21820b57cec5SDimitry Andric     }
21830b57cec5SDimitry Andric     LI.removeEmptySubRanges();
21840b57cec5SDimitry Andric   }
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric   // CP.getSrcReg()'s live interval has been merged into CP.getDstReg's live
21870b57cec5SDimitry Andric   // interval. Since CP.getSrcReg() is in ToBeUpdated set and its live interval
21880b57cec5SDimitry Andric   // is not up-to-date, need to update the merged live interval here.
21890b57cec5SDimitry Andric   if (ToBeUpdated.count(CP.getSrcReg()))
21900b57cec5SDimitry Andric     ShrinkMainRange = true;
21910b57cec5SDimitry Andric 
21920b57cec5SDimitry Andric   if (ShrinkMainRange) {
21930b57cec5SDimitry Andric     LiveInterval &LI = LIS->getInterval(CP.getDstReg());
21940b57cec5SDimitry Andric     shrinkToUses(&LI);
21950b57cec5SDimitry Andric   }
21960b57cec5SDimitry Andric 
21970b57cec5SDimitry Andric   // SrcReg is guaranteed to be the register whose live interval that is
21980b57cec5SDimitry Andric   // being merged.
21990b57cec5SDimitry Andric   LIS->removeInterval(CP.getSrcReg());
22000b57cec5SDimitry Andric 
22010b57cec5SDimitry Andric   // Update regalloc hint.
22020b57cec5SDimitry Andric   TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
22030b57cec5SDimitry Andric 
22040b57cec5SDimitry Andric   LLVM_DEBUG({
22050b57cec5SDimitry Andric     dbgs() << "\tSuccess: " << printReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
22060b57cec5SDimitry Andric            << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
22070b57cec5SDimitry Andric     dbgs() << "\tResult = ";
22080b57cec5SDimitry Andric     if (CP.isPhys())
22090b57cec5SDimitry Andric       dbgs() << printReg(CP.getDstReg(), TRI);
22100b57cec5SDimitry Andric     else
22110b57cec5SDimitry Andric       dbgs() << LIS->getInterval(CP.getDstReg());
22120b57cec5SDimitry Andric     dbgs() << '\n';
22130b57cec5SDimitry Andric   });
22140b57cec5SDimitry Andric 
22150b57cec5SDimitry Andric   ++numJoins;
22160b57cec5SDimitry Andric   return true;
22170b57cec5SDimitry Andric }
22180b57cec5SDimitry Andric 
22190b57cec5SDimitry Andric bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
2220e8d8bef9SDimitry Andric   Register DstReg = CP.getDstReg();
2221e8d8bef9SDimitry Andric   Register SrcReg = CP.getSrcReg();
22220b57cec5SDimitry Andric   assert(CP.isPhys() && "Must be a physreg copy");
22230b57cec5SDimitry Andric   assert(MRI->isReserved(DstReg) && "Not a reserved register");
22240b57cec5SDimitry Andric   LiveInterval &RHS = LIS->getInterval(SrcReg);
22250b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
22260b57cec5SDimitry Andric 
22270b57cec5SDimitry Andric   assert(RHS.containsOneValue() && "Invalid join with reserved register");
22280b57cec5SDimitry Andric 
22290b57cec5SDimitry Andric   // Optimization for reserved registers like ESP. We can only merge with a
22300b57cec5SDimitry Andric   // reserved physreg if RHS has a single value that is a copy of DstReg.
22310b57cec5SDimitry Andric   // The live range of the reserved register will look like a set of dead defs
22320b57cec5SDimitry Andric   // - we don't properly track the live range of reserved registers.
22330b57cec5SDimitry Andric 
22340b57cec5SDimitry Andric   // Deny any overlapping intervals.  This depends on all the reserved
22350b57cec5SDimitry Andric   // register live ranges to look like dead defs.
22360b57cec5SDimitry Andric   if (!MRI->isConstantPhysReg(DstReg)) {
223706c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(DstReg)) {
22380b57cec5SDimitry Andric       // Abort if not all the regunits are reserved.
223906c3fb27SDimitry Andric       for (MCRegUnitRootIterator RI(Unit, TRI); RI.isValid(); ++RI) {
22400b57cec5SDimitry Andric         if (!MRI->isReserved(*RI))
22410b57cec5SDimitry Andric           return false;
22420b57cec5SDimitry Andric       }
224306c3fb27SDimitry Andric       if (RHS.overlaps(LIS->getRegUnit(Unit))) {
224406c3fb27SDimitry Andric         LLVM_DEBUG(dbgs() << "\t\tInterference: " << printRegUnit(Unit, TRI)
22450b57cec5SDimitry Andric                           << '\n');
22460b57cec5SDimitry Andric         return false;
22470b57cec5SDimitry Andric       }
22480b57cec5SDimitry Andric     }
22490b57cec5SDimitry Andric 
22500b57cec5SDimitry Andric     // We must also check for overlaps with regmask clobbers.
22510b57cec5SDimitry Andric     BitVector RegMaskUsable;
22520b57cec5SDimitry Andric     if (LIS->checkRegMaskInterference(RHS, RegMaskUsable) &&
22530b57cec5SDimitry Andric         !RegMaskUsable.test(DstReg)) {
22540b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\t\tRegMask interference\n");
22550b57cec5SDimitry Andric       return false;
22560b57cec5SDimitry Andric     }
22570b57cec5SDimitry Andric   }
22580b57cec5SDimitry Andric 
22590b57cec5SDimitry Andric   // Skip any value computations, we are not adding new values to the
22600b57cec5SDimitry Andric   // reserved register.  Also skip merging the live ranges, the reserved
22610b57cec5SDimitry Andric   // register live range doesn't need to be accurate as long as all the
22620b57cec5SDimitry Andric   // defs are there.
22630b57cec5SDimitry Andric 
22640b57cec5SDimitry Andric   // Delete the identity copy.
22650b57cec5SDimitry Andric   MachineInstr *CopyMI;
22660b57cec5SDimitry Andric   if (CP.isFlipped()) {
22670b57cec5SDimitry Andric     // Physreg is copied into vreg
22680b57cec5SDimitry Andric     //   %y = COPY %physreg_x
22690b57cec5SDimitry Andric     //   ...  //< no other def of %physreg_x here
22700b57cec5SDimitry Andric     //   use %y
22710b57cec5SDimitry Andric     // =>
22720b57cec5SDimitry Andric     //   ...
22730b57cec5SDimitry Andric     //   use %physreg_x
22740b57cec5SDimitry Andric     CopyMI = MRI->getVRegDef(SrcReg);
227506c3fb27SDimitry Andric     deleteInstr(CopyMI);
22760b57cec5SDimitry Andric   } else {
22770b57cec5SDimitry Andric     // VReg is copied into physreg:
22780b57cec5SDimitry Andric     //   %y = def
22790b57cec5SDimitry Andric     //   ... //< no other def or use of %physreg_x here
22800b57cec5SDimitry Andric     //   %physreg_x = COPY %y
22810b57cec5SDimitry Andric     // =>
22820b57cec5SDimitry Andric     //   %physreg_x = def
22830b57cec5SDimitry Andric     //   ...
22840b57cec5SDimitry Andric     if (!MRI->hasOneNonDBGUse(SrcReg)) {
22850b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\t\tMultiple vreg uses!\n");
22860b57cec5SDimitry Andric       return false;
22870b57cec5SDimitry Andric     }
22880b57cec5SDimitry Andric 
22890b57cec5SDimitry Andric     if (!LIS->intervalIsInOneMBB(RHS)) {
22900b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\t\tComplex control flow!\n");
22910b57cec5SDimitry Andric       return false;
22920b57cec5SDimitry Andric     }
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric     MachineInstr &DestMI = *MRI->getVRegDef(SrcReg);
22950b57cec5SDimitry Andric     CopyMI = &*MRI->use_instr_nodbg_begin(SrcReg);
22960b57cec5SDimitry Andric     SlotIndex CopyRegIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
22970b57cec5SDimitry Andric     SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot();
22980b57cec5SDimitry Andric 
22990b57cec5SDimitry Andric     if (!MRI->isConstantPhysReg(DstReg)) {
23000b57cec5SDimitry Andric       // We checked above that there are no interfering defs of the physical
23010b57cec5SDimitry Andric       // register. However, for this case, where we intend to move up the def of
23020b57cec5SDimitry Andric       // the physical register, we also need to check for interfering uses.
23030b57cec5SDimitry Andric       SlotIndexes *Indexes = LIS->getSlotIndexes();
23040b57cec5SDimitry Andric       for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx);
23050b57cec5SDimitry Andric            SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) {
23060b57cec5SDimitry Andric         MachineInstr *MI = LIS->getInstructionFromIndex(SI);
23070b57cec5SDimitry Andric         if (MI->readsRegister(DstReg, TRI)) {
23080b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << "\t\tInterference (read): " << *MI);
23090b57cec5SDimitry Andric           return false;
23100b57cec5SDimitry Andric         }
23110b57cec5SDimitry Andric       }
23120b57cec5SDimitry Andric     }
23130b57cec5SDimitry Andric 
23140b57cec5SDimitry Andric     // We're going to remove the copy which defines a physical reserved
23150b57cec5SDimitry Andric     // register, so remove its valno, etc.
23160b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\t\tRemoving phys reg def of "
23170b57cec5SDimitry Andric                       << printReg(DstReg, TRI) << " at " << CopyRegIdx << "\n");
23180b57cec5SDimitry Andric 
2319e8d8bef9SDimitry Andric     LIS->removePhysRegDefAt(DstReg.asMCReg(), CopyRegIdx);
232006c3fb27SDimitry Andric     deleteInstr(CopyMI);
232106c3fb27SDimitry Andric 
23220b57cec5SDimitry Andric     // Create a new dead def at the new def location.
232306c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(DstReg)) {
232406c3fb27SDimitry Andric       LiveRange &LR = LIS->getRegUnit(Unit);
23250b57cec5SDimitry Andric       LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
23260b57cec5SDimitry Andric     }
23270b57cec5SDimitry Andric   }
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric   // We don't track kills for reserved registers.
23300b57cec5SDimitry Andric   MRI->clearKillFlags(CP.getSrcReg());
23310b57cec5SDimitry Andric 
23320b57cec5SDimitry Andric   return true;
23330b57cec5SDimitry Andric }
23340b57cec5SDimitry Andric 
23350b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
23360b57cec5SDimitry Andric //                 Interference checking and interval joining
23370b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
23380b57cec5SDimitry Andric //
23390b57cec5SDimitry Andric // In the easiest case, the two live ranges being joined are disjoint, and
23400b57cec5SDimitry Andric // there is no interference to consider. It is quite common, though, to have
23410b57cec5SDimitry Andric // overlapping live ranges, and we need to check if the interference can be
23420b57cec5SDimitry Andric // resolved.
23430b57cec5SDimitry Andric //
23440b57cec5SDimitry Andric // The live range of a single SSA value forms a sub-tree of the dominator tree.
23450b57cec5SDimitry Andric // This means that two SSA values overlap if and only if the def of one value
23460b57cec5SDimitry Andric // is contained in the live range of the other value. As a special case, the
23470b57cec5SDimitry Andric // overlapping values can be defined at the same index.
23480b57cec5SDimitry Andric //
23490b57cec5SDimitry Andric // The interference from an overlapping def can be resolved in these cases:
23500b57cec5SDimitry Andric //
23510b57cec5SDimitry Andric // 1. Coalescable copies. The value is defined by a copy that would become an
23520b57cec5SDimitry Andric //    identity copy after joining SrcReg and DstReg. The copy instruction will
23530b57cec5SDimitry Andric //    be removed, and the value will be merged with the source value.
23540b57cec5SDimitry Andric //
23550b57cec5SDimitry Andric //    There can be several copies back and forth, causing many values to be
23560b57cec5SDimitry Andric //    merged into one. We compute a list of ultimate values in the joined live
23570b57cec5SDimitry Andric //    range as well as a mappings from the old value numbers.
23580b57cec5SDimitry Andric //
23590b57cec5SDimitry Andric // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
23600b57cec5SDimitry Andric //    predecessors have a live out value. It doesn't cause real interference,
23610b57cec5SDimitry Andric //    and can be merged into the value it overlaps. Like a coalescable copy, it
23620b57cec5SDimitry Andric //    can be erased after joining.
23630b57cec5SDimitry Andric //
23640b57cec5SDimitry Andric // 3. Copy of external value. The overlapping def may be a copy of a value that
23650b57cec5SDimitry Andric //    is already in the other register. This is like a coalescable copy, but
23660b57cec5SDimitry Andric //    the live range of the source register must be trimmed after erasing the
23670b57cec5SDimitry Andric //    copy instruction:
23680b57cec5SDimitry Andric //
23690b57cec5SDimitry Andric //      %src = COPY %ext
23700b57cec5SDimitry Andric //      %dst = COPY %ext  <-- Remove this COPY, trim the live range of %ext.
23710b57cec5SDimitry Andric //
23720b57cec5SDimitry Andric // 4. Clobbering undefined lanes. Vector registers are sometimes built by
23730b57cec5SDimitry Andric //    defining one lane at a time:
23740b57cec5SDimitry Andric //
23750b57cec5SDimitry Andric //      %dst:ssub0<def,read-undef> = FOO
23760b57cec5SDimitry Andric //      %src = BAR
23770b57cec5SDimitry Andric //      %dst:ssub1 = COPY %src
23780b57cec5SDimitry Andric //
23790b57cec5SDimitry Andric //    The live range of %src overlaps the %dst value defined by FOO, but
23800b57cec5SDimitry Andric //    merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
23810b57cec5SDimitry Andric //    which was undef anyway.
23820b57cec5SDimitry Andric //
23830b57cec5SDimitry Andric //    The value mapping is more complicated in this case. The final live range
23840b57cec5SDimitry Andric //    will have different value numbers for both FOO and BAR, but there is no
23850b57cec5SDimitry Andric //    simple mapping from old to new values. It may even be necessary to add
23860b57cec5SDimitry Andric //    new PHI values.
23870b57cec5SDimitry Andric //
23880b57cec5SDimitry Andric // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
23890b57cec5SDimitry Andric //    is live, but never read. This can happen because we don't compute
23900b57cec5SDimitry Andric //    individual live ranges per lane.
23910b57cec5SDimitry Andric //
23920b57cec5SDimitry Andric //      %dst = FOO
23930b57cec5SDimitry Andric //      %src = BAR
23940b57cec5SDimitry Andric //      %dst:ssub1 = COPY %src
23950b57cec5SDimitry Andric //
23960b57cec5SDimitry Andric //    This kind of interference is only resolved locally. If the clobbered
23970b57cec5SDimitry Andric //    lane value escapes the block, the join is aborted.
23980b57cec5SDimitry Andric 
23990b57cec5SDimitry Andric namespace {
24000b57cec5SDimitry Andric 
24010b57cec5SDimitry Andric /// Track information about values in a single virtual register about to be
24020b57cec5SDimitry Andric /// joined. Objects of this class are always created in pairs - one for each
24030b57cec5SDimitry Andric /// side of the CoalescerPair (or one for each lane of a side of the coalescer
24040b57cec5SDimitry Andric /// pair)
24050b57cec5SDimitry Andric class JoinVals {
24060b57cec5SDimitry Andric   /// Live range we work on.
24070b57cec5SDimitry Andric   LiveRange &LR;
24080b57cec5SDimitry Andric 
24090b57cec5SDimitry Andric   /// (Main) register we work on.
2410e8d8bef9SDimitry Andric   const Register Reg;
24110b57cec5SDimitry Andric 
24120b57cec5SDimitry Andric   /// Reg (and therefore the values in this liverange) will end up as
24130b57cec5SDimitry Andric   /// subregister SubIdx in the coalesced register. Either CP.DstIdx or
24140b57cec5SDimitry Andric   /// CP.SrcIdx.
24150b57cec5SDimitry Andric   const unsigned SubIdx;
24160b57cec5SDimitry Andric 
24170b57cec5SDimitry Andric   /// The LaneMask that this liverange will occupy the coalesced register. May
24180b57cec5SDimitry Andric   /// be smaller than the lanemask produced by SubIdx when merging subranges.
24190b57cec5SDimitry Andric   const LaneBitmask LaneMask;
24200b57cec5SDimitry Andric 
24210b57cec5SDimitry Andric   /// This is true when joining sub register ranges, false when joining main
24220b57cec5SDimitry Andric   /// ranges.
24230b57cec5SDimitry Andric   const bool SubRangeJoin;
24240b57cec5SDimitry Andric 
24250b57cec5SDimitry Andric   /// Whether the current LiveInterval tracks subregister liveness.
24260b57cec5SDimitry Andric   const bool TrackSubRegLiveness;
24270b57cec5SDimitry Andric 
24280b57cec5SDimitry Andric   /// Values that will be present in the final live range.
24290b57cec5SDimitry Andric   SmallVectorImpl<VNInfo*> &NewVNInfo;
24300b57cec5SDimitry Andric 
24310b57cec5SDimitry Andric   const CoalescerPair &CP;
24320b57cec5SDimitry Andric   LiveIntervals *LIS;
24330b57cec5SDimitry Andric   SlotIndexes *Indexes;
24340b57cec5SDimitry Andric   const TargetRegisterInfo *TRI;
24350b57cec5SDimitry Andric 
24360b57cec5SDimitry Andric   /// Value number assignments. Maps value numbers in LI to entries in
24370b57cec5SDimitry Andric   /// NewVNInfo. This is suitable for passing to LiveInterval::join().
24380b57cec5SDimitry Andric   SmallVector<int, 8> Assignments;
24390b57cec5SDimitry Andric 
2440480093f4SDimitry Andric   public:
24410b57cec5SDimitry Andric   /// Conflict resolution for overlapping values.
24420b57cec5SDimitry Andric   enum ConflictResolution {
24430b57cec5SDimitry Andric     /// No overlap, simply keep this value.
24440b57cec5SDimitry Andric     CR_Keep,
24450b57cec5SDimitry Andric 
24460b57cec5SDimitry Andric     /// Merge this value into OtherVNI and erase the defining instruction.
24470b57cec5SDimitry Andric     /// Used for IMPLICIT_DEF, coalescable copies, and copies from external
24480b57cec5SDimitry Andric     /// values.
24490b57cec5SDimitry Andric     CR_Erase,
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric     /// Merge this value into OtherVNI but keep the defining instruction.
24520b57cec5SDimitry Andric     /// This is for the special case where OtherVNI is defined by the same
24530b57cec5SDimitry Andric     /// instruction.
24540b57cec5SDimitry Andric     CR_Merge,
24550b57cec5SDimitry Andric 
24560b57cec5SDimitry Andric     /// Keep this value, and have it replace OtherVNI where possible. This
24570b57cec5SDimitry Andric     /// complicates value mapping since OtherVNI maps to two different values
24580b57cec5SDimitry Andric     /// before and after this def.
24590b57cec5SDimitry Andric     /// Used when clobbering undefined or dead lanes.
24600b57cec5SDimitry Andric     CR_Replace,
24610b57cec5SDimitry Andric 
24620b57cec5SDimitry Andric     /// Unresolved conflict. Visit later when all values have been mapped.
24630b57cec5SDimitry Andric     CR_Unresolved,
24640b57cec5SDimitry Andric 
24650b57cec5SDimitry Andric     /// Unresolvable conflict. Abort the join.
24660b57cec5SDimitry Andric     CR_Impossible
24670b57cec5SDimitry Andric   };
24680b57cec5SDimitry Andric 
2469480093f4SDimitry Andric   private:
24700b57cec5SDimitry Andric   /// Per-value info for LI. The lane bit masks are all relative to the final
24710b57cec5SDimitry Andric   /// joined register, so they can be compared directly between SrcReg and
24720b57cec5SDimitry Andric   /// DstReg.
24730b57cec5SDimitry Andric   struct Val {
24740b57cec5SDimitry Andric     ConflictResolution Resolution = CR_Keep;
24750b57cec5SDimitry Andric 
24760b57cec5SDimitry Andric     /// Lanes written by this def, 0 for unanalyzed values.
24770b57cec5SDimitry Andric     LaneBitmask WriteLanes;
24780b57cec5SDimitry Andric 
24790b57cec5SDimitry Andric     /// Lanes with defined values in this register. Other lanes are undef and
24800b57cec5SDimitry Andric     /// safe to clobber.
24810b57cec5SDimitry Andric     LaneBitmask ValidLanes;
24820b57cec5SDimitry Andric 
24830b57cec5SDimitry Andric     /// Value in LI being redefined by this def.
24840b57cec5SDimitry Andric     VNInfo *RedefVNI = nullptr;
24850b57cec5SDimitry Andric 
24860b57cec5SDimitry Andric     /// Value in the other live range that overlaps this def, if any.
24870b57cec5SDimitry Andric     VNInfo *OtherVNI = nullptr;
24880b57cec5SDimitry Andric 
24890b57cec5SDimitry Andric     /// Is this value an IMPLICIT_DEF that can be erased?
24900b57cec5SDimitry Andric     ///
24910b57cec5SDimitry Andric     /// IMPLICIT_DEF values should only exist at the end of a basic block that
24920b57cec5SDimitry Andric     /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
24930b57cec5SDimitry Andric     /// safely erased if they are overlapping a live value in the other live
24940b57cec5SDimitry Andric     /// interval.
24950b57cec5SDimitry Andric     ///
24960b57cec5SDimitry Andric     /// Weird control flow graphs and incomplete PHI handling in
24970b57cec5SDimitry Andric     /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
24980b57cec5SDimitry Andric     /// longer live ranges. Such IMPLICIT_DEF values should be treated like
24990b57cec5SDimitry Andric     /// normal values.
25000b57cec5SDimitry Andric     bool ErasableImplicitDef = false;
25010b57cec5SDimitry Andric 
25020b57cec5SDimitry Andric     /// True when the live range of this value will be pruned because of an
25030b57cec5SDimitry Andric     /// overlapping CR_Replace value in the other live range.
25040b57cec5SDimitry Andric     bool Pruned = false;
25050b57cec5SDimitry Andric 
25060b57cec5SDimitry Andric     /// True once Pruned above has been computed.
25070b57cec5SDimitry Andric     bool PrunedComputed = false;
25080b57cec5SDimitry Andric 
25090b57cec5SDimitry Andric     /// True if this value is determined to be identical to OtherVNI
25100b57cec5SDimitry Andric     /// (in valuesIdentical). This is used with CR_Erase where the erased
25110b57cec5SDimitry Andric     /// copy is redundant, i.e. the source value is already the same as
25120b57cec5SDimitry Andric     /// the destination. In such cases the subranges need to be updated
25130b57cec5SDimitry Andric     /// properly. See comment at pruneSubRegValues for more info.
25140b57cec5SDimitry Andric     bool Identical = false;
25150b57cec5SDimitry Andric 
25160b57cec5SDimitry Andric     Val() = default;
25170b57cec5SDimitry Andric 
25180b57cec5SDimitry Andric     bool isAnalyzed() const { return WriteLanes.any(); }
25195f757f3fSDimitry Andric 
25205f757f3fSDimitry Andric     /// Mark this value as an IMPLICIT_DEF which must be kept as if it were an
25215f757f3fSDimitry Andric     /// ordinary value.
25225f757f3fSDimitry Andric     void mustKeepImplicitDef(const TargetRegisterInfo &TRI,
25235f757f3fSDimitry Andric                              const MachineInstr &ImpDef) {
25245f757f3fSDimitry Andric       assert(ImpDef.isImplicitDef());
25255f757f3fSDimitry Andric       ErasableImplicitDef = false;
25265f757f3fSDimitry Andric       ValidLanes = TRI.getSubRegIndexLaneMask(ImpDef.getOperand(0).getSubReg());
25275f757f3fSDimitry Andric     }
25280b57cec5SDimitry Andric   };
25290b57cec5SDimitry Andric 
25300b57cec5SDimitry Andric   /// One entry per value number in LI.
25310b57cec5SDimitry Andric   SmallVector<Val, 8> Vals;
25320b57cec5SDimitry Andric 
25330b57cec5SDimitry Andric   /// Compute the bitmask of lanes actually written by DefMI.
25340b57cec5SDimitry Andric   /// Set Redef if there are any partial register definitions that depend on the
25350b57cec5SDimitry Andric   /// previous value of the register.
25360b57cec5SDimitry Andric   LaneBitmask computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
25370b57cec5SDimitry Andric 
25380b57cec5SDimitry Andric   /// Find the ultimate value that VNI was copied from.
2539e8d8bef9SDimitry Andric   std::pair<const VNInfo *, Register> followCopyChain(const VNInfo *VNI) const;
25400b57cec5SDimitry Andric 
25410b57cec5SDimitry Andric   bool valuesIdentical(VNInfo *Value0, VNInfo *Value1, const JoinVals &Other) const;
25420b57cec5SDimitry Andric 
25430b57cec5SDimitry Andric   /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
25440b57cec5SDimitry Andric   /// Return a conflict resolution when possible, but leave the hard cases as
25450b57cec5SDimitry Andric   /// CR_Unresolved.
25460b57cec5SDimitry Andric   /// Recursively calls computeAssignment() on this and Other, guaranteeing that
25470b57cec5SDimitry Andric   /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
25480b57cec5SDimitry Andric   /// The recursion always goes upwards in the dominator tree, making loops
25490b57cec5SDimitry Andric   /// impossible.
25500b57cec5SDimitry Andric   ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
25510b57cec5SDimitry Andric 
25520b57cec5SDimitry Andric   /// Compute the value assignment for ValNo in RI.
25530b57cec5SDimitry Andric   /// This may be called recursively by analyzeValue(), but never for a ValNo on
25540b57cec5SDimitry Andric   /// the stack.
25550b57cec5SDimitry Andric   void computeAssignment(unsigned ValNo, JoinVals &Other);
25560b57cec5SDimitry Andric 
25570b57cec5SDimitry Andric   /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
25580b57cec5SDimitry Andric   /// the extent of the tainted lanes in the block.
25590b57cec5SDimitry Andric   ///
25600b57cec5SDimitry Andric   /// Multiple values in Other.LR can be affected since partial redefinitions
25610b57cec5SDimitry Andric   /// can preserve previously tainted lanes.
25620b57cec5SDimitry Andric   ///
25630b57cec5SDimitry Andric   ///   1 %dst = VLOAD           <-- Define all lanes in %dst
25640b57cec5SDimitry Andric   ///   2 %src = FOO             <-- ValNo to be joined with %dst:ssub0
25650b57cec5SDimitry Andric   ///   3 %dst:ssub1 = BAR       <-- Partial redef doesn't clear taint in ssub0
25660b57cec5SDimitry Andric   ///   4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
25670b57cec5SDimitry Andric   ///
25680b57cec5SDimitry Andric   /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
25690b57cec5SDimitry Andric   /// entry to TaintedVals.
25700b57cec5SDimitry Andric   ///
25710b57cec5SDimitry Andric   /// Returns false if the tainted lanes extend beyond the basic block.
25720b57cec5SDimitry Andric   bool
25730b57cec5SDimitry Andric   taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
25740b57cec5SDimitry Andric               SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent);
25750b57cec5SDimitry Andric 
25760b57cec5SDimitry Andric   /// Return true if MI uses any of the given Lanes from Reg.
25770b57cec5SDimitry Andric   /// This does not include partial redefinitions of Reg.
2578e8d8bef9SDimitry Andric   bool usesLanes(const MachineInstr &MI, Register, unsigned, LaneBitmask) const;
25790b57cec5SDimitry Andric 
25800b57cec5SDimitry Andric   /// Determine if ValNo is a copy of a value number in LR or Other.LR that will
25810b57cec5SDimitry Andric   /// be pruned:
25820b57cec5SDimitry Andric   ///
25830b57cec5SDimitry Andric   ///   %dst = COPY %src
25840b57cec5SDimitry Andric   ///   %src = COPY %dst  <-- This value to be pruned.
25850b57cec5SDimitry Andric   ///   %dst = COPY %src  <-- This value is a copy of a pruned value.
25860b57cec5SDimitry Andric   bool isPrunedValue(unsigned ValNo, JoinVals &Other);
25870b57cec5SDimitry Andric 
25880b57cec5SDimitry Andric public:
2589e8d8bef9SDimitry Andric   JoinVals(LiveRange &LR, Register Reg, unsigned SubIdx, LaneBitmask LaneMask,
25900b57cec5SDimitry Andric            SmallVectorImpl<VNInfo *> &newVNInfo, const CoalescerPair &cp,
25910b57cec5SDimitry Andric            LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
25920b57cec5SDimitry Andric            bool TrackSubRegLiveness)
25930b57cec5SDimitry Andric       : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
25940b57cec5SDimitry Andric         SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
25950b57cec5SDimitry Andric         NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
2596e8d8bef9SDimitry Andric         TRI(TRI), Assignments(LR.getNumValNums(), -1),
2597e8d8bef9SDimitry Andric         Vals(LR.getNumValNums()) {}
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric   /// Analyze defs in LR and compute a value mapping in NewVNInfo.
26000b57cec5SDimitry Andric   /// Returns false if any conflicts were impossible to resolve.
26010b57cec5SDimitry Andric   bool mapValues(JoinVals &Other);
26020b57cec5SDimitry Andric 
26030b57cec5SDimitry Andric   /// Try to resolve conflicts that require all values to be mapped.
26040b57cec5SDimitry Andric   /// Returns false if any conflicts were impossible to resolve.
26050b57cec5SDimitry Andric   bool resolveConflicts(JoinVals &Other);
26060b57cec5SDimitry Andric 
26070b57cec5SDimitry Andric   /// Prune the live range of values in Other.LR where they would conflict with
26080b57cec5SDimitry Andric   /// CR_Replace values in LR. Collect end points for restoring the live range
26090b57cec5SDimitry Andric   /// after joining.
26100b57cec5SDimitry Andric   void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
26110b57cec5SDimitry Andric                    bool changeInstrs);
26120b57cec5SDimitry Andric 
26130b57cec5SDimitry Andric   /// Removes subranges starting at copies that get removed. This sometimes
26140b57cec5SDimitry Andric   /// happens when undefined subranges are copied around. These ranges contain
26150b57cec5SDimitry Andric   /// no useful information and can be removed.
26160b57cec5SDimitry Andric   void pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask);
26170b57cec5SDimitry Andric 
26180b57cec5SDimitry Andric   /// Pruning values in subranges can lead to removing segments in these
26190b57cec5SDimitry Andric   /// subranges started by IMPLICIT_DEFs. The corresponding segments in
26200b57cec5SDimitry Andric   /// the main range also need to be removed. This function will mark
26210b57cec5SDimitry Andric   /// the corresponding values in the main range as pruned, so that
26220b57cec5SDimitry Andric   /// eraseInstrs can do the final cleanup.
26230b57cec5SDimitry Andric   /// The parameter @p LI must be the interval whose main range is the
26240b57cec5SDimitry Andric   /// live range LR.
26250b57cec5SDimitry Andric   void pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange);
26260b57cec5SDimitry Andric 
26270b57cec5SDimitry Andric   /// Erase any machine instructions that have been coalesced away.
26280b57cec5SDimitry Andric   /// Add erased instructions to ErasedInstrs.
26290b57cec5SDimitry Andric   /// Add foreign virtual registers to ShrinkRegs if their live range ended at
26300b57cec5SDimitry Andric   /// the erased instrs.
26310b57cec5SDimitry Andric   void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
26325ffd83dbSDimitry Andric                    SmallVectorImpl<Register> &ShrinkRegs,
26330b57cec5SDimitry Andric                    LiveInterval *LI = nullptr);
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric   /// Remove liverange defs at places where implicit defs will be removed.
26360b57cec5SDimitry Andric   void removeImplicitDefs();
26370b57cec5SDimitry Andric 
26380b57cec5SDimitry Andric   /// Get the value assignments suitable for passing to LiveInterval::join.
26390b57cec5SDimitry Andric   const int *getAssignments() const { return Assignments.data(); }
2640480093f4SDimitry Andric 
2641480093f4SDimitry Andric   /// Get the conflict resolution for a value number.
2642480093f4SDimitry Andric   ConflictResolution getResolution(unsigned Num) const {
2643480093f4SDimitry Andric     return Vals[Num].Resolution;
2644480093f4SDimitry Andric   }
26450b57cec5SDimitry Andric };
26460b57cec5SDimitry Andric 
26470b57cec5SDimitry Andric } // end anonymous namespace
26480b57cec5SDimitry Andric 
26490b57cec5SDimitry Andric LaneBitmask JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
26500b57cec5SDimitry Andric   const {
26510b57cec5SDimitry Andric   LaneBitmask L;
265206c3fb27SDimitry Andric   for (const MachineOperand &MO : DefMI->all_defs()) {
265306c3fb27SDimitry Andric     if (MO.getReg() != Reg)
26540b57cec5SDimitry Andric       continue;
26550b57cec5SDimitry Andric     L |= TRI->getSubRegIndexLaneMask(
26560b57cec5SDimitry Andric            TRI->composeSubRegIndices(SubIdx, MO.getSubReg()));
26570b57cec5SDimitry Andric     if (MO.readsReg())
26580b57cec5SDimitry Andric       Redef = true;
26590b57cec5SDimitry Andric   }
26600b57cec5SDimitry Andric   return L;
26610b57cec5SDimitry Andric }
26620b57cec5SDimitry Andric 
2663e8d8bef9SDimitry Andric std::pair<const VNInfo *, Register>
2664e8d8bef9SDimitry Andric JoinVals::followCopyChain(const VNInfo *VNI) const {
2665e8d8bef9SDimitry Andric   Register TrackReg = Reg;
26660b57cec5SDimitry Andric 
26670b57cec5SDimitry Andric   while (!VNI->isPHIDef()) {
26680b57cec5SDimitry Andric     SlotIndex Def = VNI->def;
26690b57cec5SDimitry Andric     MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
26700b57cec5SDimitry Andric     assert(MI && "No defining instruction");
26710b57cec5SDimitry Andric     if (!MI->isFullCopy())
26720b57cec5SDimitry Andric       return std::make_pair(VNI, TrackReg);
26738bcb0991SDimitry Andric     Register SrcReg = MI->getOperand(1).getReg();
2674e8d8bef9SDimitry Andric     if (!SrcReg.isVirtual())
26750b57cec5SDimitry Andric       return std::make_pair(VNI, TrackReg);
26760b57cec5SDimitry Andric 
26770b57cec5SDimitry Andric     const LiveInterval &LI = LIS->getInterval(SrcReg);
26780b57cec5SDimitry Andric     const VNInfo *ValueIn;
26790b57cec5SDimitry Andric     // No subrange involved.
26800b57cec5SDimitry Andric     if (!SubRangeJoin || !LI.hasSubRanges()) {
26810b57cec5SDimitry Andric       LiveQueryResult LRQ = LI.Query(Def);
26820b57cec5SDimitry Andric       ValueIn = LRQ.valueIn();
26830b57cec5SDimitry Andric     } else {
26840b57cec5SDimitry Andric       // Query subranges. Ensure that all matching ones take us to the same def
26850b57cec5SDimitry Andric       // (allowing some of them to be undef).
26860b57cec5SDimitry Andric       ValueIn = nullptr;
26870b57cec5SDimitry Andric       for (const LiveInterval::SubRange &S : LI.subranges()) {
26880b57cec5SDimitry Andric         // Transform lanemask to a mask in the joined live interval.
26890b57cec5SDimitry Andric         LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
26900b57cec5SDimitry Andric         if ((SMask & LaneMask).none())
26910b57cec5SDimitry Andric           continue;
26920b57cec5SDimitry Andric         LiveQueryResult LRQ = S.Query(Def);
26930b57cec5SDimitry Andric         if (!ValueIn) {
26940b57cec5SDimitry Andric           ValueIn = LRQ.valueIn();
26950b57cec5SDimitry Andric           continue;
26960b57cec5SDimitry Andric         }
26970b57cec5SDimitry Andric         if (LRQ.valueIn() && ValueIn != LRQ.valueIn())
26980b57cec5SDimitry Andric           return std::make_pair(VNI, TrackReg);
26990b57cec5SDimitry Andric       }
27000b57cec5SDimitry Andric     }
27010b57cec5SDimitry Andric     if (ValueIn == nullptr) {
27020b57cec5SDimitry Andric       // Reaching an undefined value is legitimate, for example:
27030b57cec5SDimitry Andric       //
27040b57cec5SDimitry Andric       // 1   undef %0.sub1 = ...  ;; %0.sub0 == undef
27050b57cec5SDimitry Andric       // 2   %1 = COPY %0         ;; %1 is defined here.
27060b57cec5SDimitry Andric       // 3   %0 = COPY %1         ;; Now %0.sub0 has a definition,
27070b57cec5SDimitry Andric       //                          ;; but it's equivalent to "undef".
27080b57cec5SDimitry Andric       return std::make_pair(nullptr, SrcReg);
27090b57cec5SDimitry Andric     }
27100b57cec5SDimitry Andric     VNI = ValueIn;
27110b57cec5SDimitry Andric     TrackReg = SrcReg;
27120b57cec5SDimitry Andric   }
27130b57cec5SDimitry Andric   return std::make_pair(VNI, TrackReg);
27140b57cec5SDimitry Andric }
27150b57cec5SDimitry Andric 
27160b57cec5SDimitry Andric bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
27170b57cec5SDimitry Andric                                const JoinVals &Other) const {
27180b57cec5SDimitry Andric   const VNInfo *Orig0;
2719e8d8bef9SDimitry Andric   Register Reg0;
27200b57cec5SDimitry Andric   std::tie(Orig0, Reg0) = followCopyChain(Value0);
27210b57cec5SDimitry Andric   if (Orig0 == Value1 && Reg0 == Other.Reg)
27220b57cec5SDimitry Andric     return true;
27230b57cec5SDimitry Andric 
27240b57cec5SDimitry Andric   const VNInfo *Orig1;
2725e8d8bef9SDimitry Andric   Register Reg1;
27260b57cec5SDimitry Andric   std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
27270b57cec5SDimitry Andric   // If both values are undefined, and the source registers are the same
27280b57cec5SDimitry Andric   // register, the values are identical. Filter out cases where only one
27290b57cec5SDimitry Andric   // value is defined.
27300b57cec5SDimitry Andric   if (Orig0 == nullptr || Orig1 == nullptr)
27310b57cec5SDimitry Andric     return Orig0 == Orig1 && Reg0 == Reg1;
27320b57cec5SDimitry Andric 
27330b57cec5SDimitry Andric   // The values are equal if they are defined at the same place and use the
27340b57cec5SDimitry Andric   // same register. Note that we cannot compare VNInfos directly as some of
27350b57cec5SDimitry Andric   // them might be from a copy created in mergeSubRangeInto()  while the other
27360b57cec5SDimitry Andric   // is from the original LiveInterval.
27370b57cec5SDimitry Andric   return Orig0->def == Orig1->def && Reg0 == Reg1;
27380b57cec5SDimitry Andric }
27390b57cec5SDimitry Andric 
27400b57cec5SDimitry Andric JoinVals::ConflictResolution
27410b57cec5SDimitry Andric JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
27420b57cec5SDimitry Andric   Val &V = Vals[ValNo];
27430b57cec5SDimitry Andric   assert(!V.isAnalyzed() && "Value has already been analyzed!");
27440b57cec5SDimitry Andric   VNInfo *VNI = LR.getValNumInfo(ValNo);
27450b57cec5SDimitry Andric   if (VNI->isUnused()) {
27460b57cec5SDimitry Andric     V.WriteLanes = LaneBitmask::getAll();
27470b57cec5SDimitry Andric     return CR_Keep;
27480b57cec5SDimitry Andric   }
27490b57cec5SDimitry Andric 
27500b57cec5SDimitry Andric   // Get the instruction defining this value, compute the lanes written.
27510b57cec5SDimitry Andric   const MachineInstr *DefMI = nullptr;
27520b57cec5SDimitry Andric   if (VNI->isPHIDef()) {
27530b57cec5SDimitry Andric     // Conservatively assume that all lanes in a PHI are valid.
27540b57cec5SDimitry Andric     LaneBitmask Lanes = SubRangeJoin ? LaneBitmask::getLane(0)
27550b57cec5SDimitry Andric                                      : TRI->getSubRegIndexLaneMask(SubIdx);
27560b57cec5SDimitry Andric     V.ValidLanes = V.WriteLanes = Lanes;
27570b57cec5SDimitry Andric   } else {
27580b57cec5SDimitry Andric     DefMI = Indexes->getInstructionFromIndex(VNI->def);
27590b57cec5SDimitry Andric     assert(DefMI != nullptr);
27600b57cec5SDimitry Andric     if (SubRangeJoin) {
27610b57cec5SDimitry Andric       // We don't care about the lanes when joining subregister ranges.
27620b57cec5SDimitry Andric       V.WriteLanes = V.ValidLanes = LaneBitmask::getLane(0);
27630b57cec5SDimitry Andric       if (DefMI->isImplicitDef()) {
27640b57cec5SDimitry Andric         V.ValidLanes = LaneBitmask::getNone();
27650b57cec5SDimitry Andric         V.ErasableImplicitDef = true;
27660b57cec5SDimitry Andric       }
27670b57cec5SDimitry Andric     } else {
27680b57cec5SDimitry Andric       bool Redef = false;
27690b57cec5SDimitry Andric       V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
27700b57cec5SDimitry Andric 
27710b57cec5SDimitry Andric       // If this is a read-modify-write instruction, there may be more valid
27720b57cec5SDimitry Andric       // lanes than the ones written by this instruction.
27730b57cec5SDimitry Andric       // This only covers partial redef operands. DefMI may have normal use
27740b57cec5SDimitry Andric       // operands reading the register. They don't contribute valid lanes.
27750b57cec5SDimitry Andric       //
27760b57cec5SDimitry Andric       // This adds ssub1 to the set of valid lanes in %src:
27770b57cec5SDimitry Andric       //
27780b57cec5SDimitry Andric       //   %src:ssub1 = FOO
27790b57cec5SDimitry Andric       //
27800b57cec5SDimitry Andric       // This leaves only ssub1 valid, making any other lanes undef:
27810b57cec5SDimitry Andric       //
27820b57cec5SDimitry Andric       //   %src:ssub1<def,read-undef> = FOO %src:ssub2
27830b57cec5SDimitry Andric       //
27840b57cec5SDimitry Andric       // The <read-undef> flag on the def operand means that old lane values are
27850b57cec5SDimitry Andric       // not important.
27860b57cec5SDimitry Andric       if (Redef) {
27870b57cec5SDimitry Andric         V.RedefVNI = LR.Query(VNI->def).valueIn();
27880b57cec5SDimitry Andric         assert((TrackSubRegLiveness || V.RedefVNI) &&
27890b57cec5SDimitry Andric                "Instruction is reading nonexistent value");
27900b57cec5SDimitry Andric         if (V.RedefVNI != nullptr) {
27910b57cec5SDimitry Andric           computeAssignment(V.RedefVNI->id, Other);
27920b57cec5SDimitry Andric           V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
27930b57cec5SDimitry Andric         }
27940b57cec5SDimitry Andric       }
27950b57cec5SDimitry Andric 
27960b57cec5SDimitry Andric       // An IMPLICIT_DEF writes undef values.
27970b57cec5SDimitry Andric       if (DefMI->isImplicitDef()) {
27980b57cec5SDimitry Andric         // We normally expect IMPLICIT_DEF values to be live only until the end
27990b57cec5SDimitry Andric         // of their block. If the value is really live longer and gets pruned in
28000b57cec5SDimitry Andric         // another block, this flag is cleared again.
28010b57cec5SDimitry Andric         //
28020b57cec5SDimitry Andric         // Clearing the valid lanes is deferred until it is sure this can be
28030b57cec5SDimitry Andric         // erased.
28040b57cec5SDimitry Andric         V.ErasableImplicitDef = true;
28050b57cec5SDimitry Andric       }
28060b57cec5SDimitry Andric     }
28070b57cec5SDimitry Andric   }
28080b57cec5SDimitry Andric 
28090b57cec5SDimitry Andric   // Find the value in Other that overlaps VNI->def, if any.
28100b57cec5SDimitry Andric   LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
28110b57cec5SDimitry Andric 
28120b57cec5SDimitry Andric   // It is possible that both values are defined by the same instruction, or
28130b57cec5SDimitry Andric   // the values are PHIs defined in the same block. When that happens, the two
28140b57cec5SDimitry Andric   // values should be merged into one, but not into any preceding value.
28150b57cec5SDimitry Andric   // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
28160b57cec5SDimitry Andric   if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
28170b57cec5SDimitry Andric     assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
28180b57cec5SDimitry Andric 
28190b57cec5SDimitry Andric     // One value stays, the other is merged. Keep the earlier one, or the first
28200b57cec5SDimitry Andric     // one we see.
28210b57cec5SDimitry Andric     if (OtherVNI->def < VNI->def)
28220b57cec5SDimitry Andric       Other.computeAssignment(OtherVNI->id, *this);
28230b57cec5SDimitry Andric     else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
28240b57cec5SDimitry Andric       // This is an early-clobber def overlapping a live-in value in the other
28250b57cec5SDimitry Andric       // register. Not mergeable.
28260b57cec5SDimitry Andric       V.OtherVNI = OtherLRQ.valueIn();
28270b57cec5SDimitry Andric       return CR_Impossible;
28280b57cec5SDimitry Andric     }
28290b57cec5SDimitry Andric     V.OtherVNI = OtherVNI;
28300b57cec5SDimitry Andric     Val &OtherV = Other.Vals[OtherVNI->id];
2831bdd1243dSDimitry Andric     // Keep this value, check for conflicts when analyzing OtherVNI. Avoid
2832bdd1243dSDimitry Andric     // revisiting OtherVNI->id in JoinVals::computeAssignment() below before it
2833bdd1243dSDimitry Andric     // is assigned.
2834bdd1243dSDimitry Andric     if (!OtherV.isAnalyzed() || Other.Assignments[OtherVNI->id] == -1)
28350b57cec5SDimitry Andric       return CR_Keep;
28360b57cec5SDimitry Andric     // Both sides have been analyzed now.
28370b57cec5SDimitry Andric     // Allow overlapping PHI values. Any real interference would show up in a
28380b57cec5SDimitry Andric     // predecessor, the PHI itself can't introduce any conflicts.
28390b57cec5SDimitry Andric     if (VNI->isPHIDef())
28400b57cec5SDimitry Andric       return CR_Merge;
28410b57cec5SDimitry Andric     if ((V.ValidLanes & OtherV.ValidLanes).any())
28420b57cec5SDimitry Andric       // Overlapping lanes can't be resolved.
28430b57cec5SDimitry Andric       return CR_Impossible;
28440b57cec5SDimitry Andric     else
28450b57cec5SDimitry Andric       return CR_Merge;
28460b57cec5SDimitry Andric   }
28470b57cec5SDimitry Andric 
28480b57cec5SDimitry Andric   // No simultaneous def. Is Other live at the def?
28490b57cec5SDimitry Andric   V.OtherVNI = OtherLRQ.valueIn();
28500b57cec5SDimitry Andric   if (!V.OtherVNI)
28510b57cec5SDimitry Andric     // No overlap, no conflict.
28520b57cec5SDimitry Andric     return CR_Keep;
28530b57cec5SDimitry Andric 
28540b57cec5SDimitry Andric   assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
28550b57cec5SDimitry Andric 
28560b57cec5SDimitry Andric   // We have overlapping values, or possibly a kill of Other.
28570b57cec5SDimitry Andric   // Recursively compute assignments up the dominator tree.
28580b57cec5SDimitry Andric   Other.computeAssignment(V.OtherVNI->id, *this);
28590b57cec5SDimitry Andric   Val &OtherV = Other.Vals[V.OtherVNI->id];
28600b57cec5SDimitry Andric 
28610b57cec5SDimitry Andric   if (OtherV.ErasableImplicitDef) {
28620b57cec5SDimitry Andric     // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
28630b57cec5SDimitry Andric     // This shouldn't normally happen, but ProcessImplicitDefs can leave such
28640b57cec5SDimitry Andric     // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
28650b57cec5SDimitry Andric     // technically.
28660b57cec5SDimitry Andric     //
28670b57cec5SDimitry Andric     // When it happens, treat that IMPLICIT_DEF as a normal value, and don't try
28680b57cec5SDimitry Andric     // to erase the IMPLICIT_DEF instruction.
28695f757f3fSDimitry Andric     //
28705f757f3fSDimitry Andric     // Additionally we must keep an IMPLICIT_DEF if we're redefining an incoming
28715f757f3fSDimitry Andric     // value.
28725f757f3fSDimitry Andric 
28735f757f3fSDimitry Andric     MachineInstr *OtherImpDef =
28745f757f3fSDimitry Andric         Indexes->getInstructionFromIndex(V.OtherVNI->def);
28755f757f3fSDimitry Andric     MachineBasicBlock *OtherMBB = OtherImpDef->getParent();
28765f757f3fSDimitry Andric     if (DefMI &&
28775f757f3fSDimitry Andric         (DefMI->getParent() != OtherMBB || LIS->isLiveInToMBB(LR, OtherMBB))) {
28780b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
28790b57cec5SDimitry Andric                  << " extends into "
28800b57cec5SDimitry Andric                  << printMBBReference(*DefMI->getParent())
28810b57cec5SDimitry Andric                  << ", keeping it.\n");
28825f757f3fSDimitry Andric       OtherV.mustKeepImplicitDef(*TRI, *OtherImpDef);
288306c3fb27SDimitry Andric     } else if (OtherMBB->hasEHPadSuccessor()) {
288406c3fb27SDimitry Andric       // If OtherV is defined in a basic block that has EH pad successors then
288506c3fb27SDimitry Andric       // we get the same problem not just if OtherV is live beyond its basic
288606c3fb27SDimitry Andric       // block, but beyond the last call instruction in its basic block. Handle
288706c3fb27SDimitry Andric       // this case conservatively.
288806c3fb27SDimitry Andric       LLVM_DEBUG(
288906c3fb27SDimitry Andric           dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
289006c3fb27SDimitry Andric                  << " may be live into EH pad successors, keeping it.\n");
28915f757f3fSDimitry Andric       OtherV.mustKeepImplicitDef(*TRI, *OtherImpDef);
28920b57cec5SDimitry Andric     } else {
28930b57cec5SDimitry Andric       // We deferred clearing these lanes in case we needed to save them
28940b57cec5SDimitry Andric       OtherV.ValidLanes &= ~OtherV.WriteLanes;
28950b57cec5SDimitry Andric     }
28960b57cec5SDimitry Andric   }
28970b57cec5SDimitry Andric 
28980b57cec5SDimitry Andric   // Allow overlapping PHI values. Any real interference would show up in a
28990b57cec5SDimitry Andric   // predecessor, the PHI itself can't introduce any conflicts.
29000b57cec5SDimitry Andric   if (VNI->isPHIDef())
29010b57cec5SDimitry Andric     return CR_Replace;
29020b57cec5SDimitry Andric 
29030b57cec5SDimitry Andric   // Check for simple erasable conflicts.
2904e8d8bef9SDimitry Andric   if (DefMI->isImplicitDef())
29050b57cec5SDimitry Andric     return CR_Erase;
29060b57cec5SDimitry Andric 
29070b57cec5SDimitry Andric   // Include the non-conflict where DefMI is a coalescable copy that kills
29080b57cec5SDimitry Andric   // OtherVNI. We still want the copy erased and value numbers merged.
29090b57cec5SDimitry Andric   if (CP.isCoalescable(DefMI)) {
29100b57cec5SDimitry Andric     // Some of the lanes copied from OtherVNI may be undef, making them undef
29110b57cec5SDimitry Andric     // here too.
29120b57cec5SDimitry Andric     V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
29130b57cec5SDimitry Andric     return CR_Erase;
29140b57cec5SDimitry Andric   }
29150b57cec5SDimitry Andric 
29160b57cec5SDimitry Andric   // This may not be a real conflict if DefMI simply kills Other and defines
29170b57cec5SDimitry Andric   // VNI.
29180b57cec5SDimitry Andric   if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
29190b57cec5SDimitry Andric     return CR_Keep;
29200b57cec5SDimitry Andric 
29210b57cec5SDimitry Andric   // Handle the case where VNI and OtherVNI can be proven to be identical:
29220b57cec5SDimitry Andric   //
29230b57cec5SDimitry Andric   //   %other = COPY %ext
29240b57cec5SDimitry Andric   //   %this  = COPY %ext <-- Erase this copy
29250b57cec5SDimitry Andric   //
29260b57cec5SDimitry Andric   if (DefMI->isFullCopy() && !CP.isPartial() &&
29270b57cec5SDimitry Andric       valuesIdentical(VNI, V.OtherVNI, Other)) {
29280b57cec5SDimitry Andric     V.Identical = true;
29290b57cec5SDimitry Andric     return CR_Erase;
29300b57cec5SDimitry Andric   }
29310b57cec5SDimitry Andric 
29320b57cec5SDimitry Andric   // The remaining checks apply to the lanes, which aren't tracked here.  This
29330b57cec5SDimitry Andric   // was already decided to be OK via the following CR_Replace condition.
29340b57cec5SDimitry Andric   // CR_Replace.
29350b57cec5SDimitry Andric   if (SubRangeJoin)
29360b57cec5SDimitry Andric     return CR_Replace;
29370b57cec5SDimitry Andric 
29380b57cec5SDimitry Andric   // If the lanes written by this instruction were all undef in OtherVNI, it is
29390b57cec5SDimitry Andric   // still safe to join the live ranges. This can't be done with a simple value
29400b57cec5SDimitry Andric   // mapping, though - OtherVNI will map to multiple values:
29410b57cec5SDimitry Andric   //
29420b57cec5SDimitry Andric   //   1 %dst:ssub0 = FOO                <-- OtherVNI
29430b57cec5SDimitry Andric   //   2 %src = BAR                      <-- VNI
29440b57cec5SDimitry Andric   //   3 %dst:ssub1 = COPY killed %src    <-- Eliminate this copy.
29450b57cec5SDimitry Andric   //   4 BAZ killed %dst
29460b57cec5SDimitry Andric   //   5 QUUX killed %src
29470b57cec5SDimitry Andric   //
29480b57cec5SDimitry Andric   // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
29490b57cec5SDimitry Andric   // handles this complex value mapping.
29500b57cec5SDimitry Andric   if ((V.WriteLanes & OtherV.ValidLanes).none())
29510b57cec5SDimitry Andric     return CR_Replace;
29520b57cec5SDimitry Andric 
29530b57cec5SDimitry Andric   // If the other live range is killed by DefMI and the live ranges are still
29540b57cec5SDimitry Andric   // overlapping, it must be because we're looking at an early clobber def:
29550b57cec5SDimitry Andric   //
29560b57cec5SDimitry Andric   //   %dst<def,early-clobber> = ASM killed %src
29570b57cec5SDimitry Andric   //
29580b57cec5SDimitry Andric   // In this case, it is illegal to merge the two live ranges since the early
29590b57cec5SDimitry Andric   // clobber def would clobber %src before it was read.
29600b57cec5SDimitry Andric   if (OtherLRQ.isKill()) {
29610b57cec5SDimitry Andric     // This case where the def doesn't overlap the kill is handled above.
29620b57cec5SDimitry Andric     assert(VNI->def.isEarlyClobber() &&
29630b57cec5SDimitry Andric            "Only early clobber defs can overlap a kill");
29640b57cec5SDimitry Andric     return CR_Impossible;
29650b57cec5SDimitry Andric   }
29660b57cec5SDimitry Andric 
29670b57cec5SDimitry Andric   // VNI is clobbering live lanes in OtherVNI, but there is still the
29680b57cec5SDimitry Andric   // possibility that no instructions actually read the clobbered lanes.
29690b57cec5SDimitry Andric   // If we're clobbering all the lanes in OtherVNI, at least one must be read.
29700b57cec5SDimitry Andric   // Otherwise Other.RI wouldn't be live here.
29710b57cec5SDimitry Andric   if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes).none())
29720b57cec5SDimitry Andric     return CR_Impossible;
29730b57cec5SDimitry Andric 
2974fe6060f1SDimitry Andric   if (TrackSubRegLiveness) {
2975fe6060f1SDimitry Andric     auto &OtherLI = LIS->getInterval(Other.Reg);
2976fe6060f1SDimitry Andric     // If OtherVNI does not have subranges, it means all the lanes of OtherVNI
2977fe6060f1SDimitry Andric     // share the same live range, so we just need to check whether they have
2978fe6060f1SDimitry Andric     // any conflict bit in their LaneMask.
2979fe6060f1SDimitry Andric     if (!OtherLI.hasSubRanges()) {
2980fe6060f1SDimitry Andric       LaneBitmask OtherMask = TRI->getSubRegIndexLaneMask(Other.SubIdx);
2981fe6060f1SDimitry Andric       return (OtherMask & V.WriteLanes).none() ? CR_Replace : CR_Impossible;
2982fe6060f1SDimitry Andric     }
2983fe6060f1SDimitry Andric 
2984fe6060f1SDimitry Andric     // If we are clobbering some active lanes of OtherVNI at VNI->def, it is
2985fe6060f1SDimitry Andric     // impossible to resolve the conflict. Otherwise, we can just replace
2986fe6060f1SDimitry Andric     // OtherVNI because of no real conflict.
2987fe6060f1SDimitry Andric     for (LiveInterval::SubRange &OtherSR : OtherLI.subranges()) {
2988fe6060f1SDimitry Andric       LaneBitmask OtherMask =
2989fe6060f1SDimitry Andric           TRI->composeSubRegIndexLaneMask(Other.SubIdx, OtherSR.LaneMask);
2990fe6060f1SDimitry Andric       if ((OtherMask & V.WriteLanes).none())
2991fe6060f1SDimitry Andric         continue;
2992fe6060f1SDimitry Andric 
2993fe6060f1SDimitry Andric       auto OtherSRQ = OtherSR.Query(VNI->def);
2994fe6060f1SDimitry Andric       if (OtherSRQ.valueIn() && OtherSRQ.endPoint() > VNI->def) {
2995fe6060f1SDimitry Andric         // VNI is clobbering some lanes of OtherVNI, they have real conflict.
2996fe6060f1SDimitry Andric         return CR_Impossible;
2997fe6060f1SDimitry Andric       }
2998fe6060f1SDimitry Andric     }
2999fe6060f1SDimitry Andric 
3000fe6060f1SDimitry Andric     // VNI is NOT clobbering any lane of OtherVNI, just replace OtherVNI.
3001fe6060f1SDimitry Andric     return CR_Replace;
3002fe6060f1SDimitry Andric   }
3003fe6060f1SDimitry Andric 
3004fe6060f1SDimitry Andric   // We need to verify that no instructions are reading the clobbered lanes.
3005fe6060f1SDimitry Andric   // To save compile time, we'll only check that locally. Don't allow the
3006fe6060f1SDimitry Andric   // tainted value to escape the basic block.
30070b57cec5SDimitry Andric   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
30080b57cec5SDimitry Andric   if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
30090b57cec5SDimitry Andric     return CR_Impossible;
30100b57cec5SDimitry Andric 
30110b57cec5SDimitry Andric   // There are still some things that could go wrong besides clobbered lanes
30120b57cec5SDimitry Andric   // being read, for example OtherVNI may be only partially redefined in MBB,
30130b57cec5SDimitry Andric   // and some clobbered lanes could escape the block. Save this analysis for
30140b57cec5SDimitry Andric   // resolveConflicts() when all values have been mapped. We need to know
30150b57cec5SDimitry Andric   // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
30160b57cec5SDimitry Andric   // that now - the recursive analyzeValue() calls must go upwards in the
30170b57cec5SDimitry Andric   // dominator tree.
30180b57cec5SDimitry Andric   return CR_Unresolved;
30190b57cec5SDimitry Andric }
30200b57cec5SDimitry Andric 
30210b57cec5SDimitry Andric void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
30220b57cec5SDimitry Andric   Val &V = Vals[ValNo];
30230b57cec5SDimitry Andric   if (V.isAnalyzed()) {
30240b57cec5SDimitry Andric     // Recursion should always move up the dominator tree, so ValNo is not
30250b57cec5SDimitry Andric     // supposed to reappear before it has been assigned.
30260b57cec5SDimitry Andric     assert(Assignments[ValNo] != -1 && "Bad recursion?");
30270b57cec5SDimitry Andric     return;
30280b57cec5SDimitry Andric   }
30290b57cec5SDimitry Andric   switch ((V.Resolution = analyzeValue(ValNo, Other))) {
30300b57cec5SDimitry Andric   case CR_Erase:
30310b57cec5SDimitry Andric   case CR_Merge:
30320b57cec5SDimitry Andric     // Merge this ValNo into OtherVNI.
30330b57cec5SDimitry Andric     assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
30340b57cec5SDimitry Andric     assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
30350b57cec5SDimitry Andric     Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
30360b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\t\tmerge " << printReg(Reg) << ':' << ValNo << '@'
30370b57cec5SDimitry Andric                       << LR.getValNumInfo(ValNo)->def << " into "
30380b57cec5SDimitry Andric                       << printReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
30390b57cec5SDimitry Andric                       << V.OtherVNI->def << " --> @"
30400b57cec5SDimitry Andric                       << NewVNInfo[Assignments[ValNo]]->def << '\n');
30410b57cec5SDimitry Andric     break;
30420b57cec5SDimitry Andric   case CR_Replace:
30430b57cec5SDimitry Andric   case CR_Unresolved: {
30440b57cec5SDimitry Andric     // The other value is going to be pruned if this join is successful.
30450b57cec5SDimitry Andric     assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
30460b57cec5SDimitry Andric     Val &OtherV = Other.Vals[V.OtherVNI->id];
30470b57cec5SDimitry Andric     OtherV.Pruned = true;
3048bdd1243dSDimitry Andric     [[fallthrough]];
30490b57cec5SDimitry Andric   }
30500b57cec5SDimitry Andric   default:
30510b57cec5SDimitry Andric     // This value number needs to go in the final joined live range.
30520b57cec5SDimitry Andric     Assignments[ValNo] = NewVNInfo.size();
30530b57cec5SDimitry Andric     NewVNInfo.push_back(LR.getValNumInfo(ValNo));
30540b57cec5SDimitry Andric     break;
30550b57cec5SDimitry Andric   }
30560b57cec5SDimitry Andric }
30570b57cec5SDimitry Andric 
30580b57cec5SDimitry Andric bool JoinVals::mapValues(JoinVals &Other) {
30590b57cec5SDimitry Andric   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
30600b57cec5SDimitry Andric     computeAssignment(i, Other);
30610b57cec5SDimitry Andric     if (Vals[i].Resolution == CR_Impossible) {
30620b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\t\tinterference at " << printReg(Reg) << ':' << i
30630b57cec5SDimitry Andric                         << '@' << LR.getValNumInfo(i)->def << '\n');
30640b57cec5SDimitry Andric       return false;
30650b57cec5SDimitry Andric     }
30660b57cec5SDimitry Andric   }
30670b57cec5SDimitry Andric   return true;
30680b57cec5SDimitry Andric }
30690b57cec5SDimitry Andric 
30700b57cec5SDimitry Andric bool JoinVals::
30710b57cec5SDimitry Andric taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
30720b57cec5SDimitry Andric             SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent) {
30730b57cec5SDimitry Andric   VNInfo *VNI = LR.getValNumInfo(ValNo);
30740b57cec5SDimitry Andric   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
30750b57cec5SDimitry Andric   SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
30760b57cec5SDimitry Andric 
30770b57cec5SDimitry Andric   // Scan Other.LR from VNI.def to MBBEnd.
30780b57cec5SDimitry Andric   LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
30790b57cec5SDimitry Andric   assert(OtherI != Other.LR.end() && "No conflict?");
30800b57cec5SDimitry Andric   do {
30810b57cec5SDimitry Andric     // OtherI is pointing to a tainted value. Abort the join if the tainted
30820b57cec5SDimitry Andric     // lanes escape the block.
30830b57cec5SDimitry Andric     SlotIndex End = OtherI->end;
30840b57cec5SDimitry Andric     if (End >= MBBEnd) {
30850b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\t\ttaints global " << printReg(Other.Reg) << ':'
30860b57cec5SDimitry Andric                         << OtherI->valno->id << '@' << OtherI->start << '\n');
30870b57cec5SDimitry Andric       return false;
30880b57cec5SDimitry Andric     }
30890b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\t\ttaints local " << printReg(Other.Reg) << ':'
30900b57cec5SDimitry Andric                       << OtherI->valno->id << '@' << OtherI->start << " to "
30910b57cec5SDimitry Andric                       << End << '\n');
30920b57cec5SDimitry Andric     // A dead def is not a problem.
30930b57cec5SDimitry Andric     if (End.isDead())
30940b57cec5SDimitry Andric       break;
30950b57cec5SDimitry Andric     TaintExtent.push_back(std::make_pair(End, TaintedLanes));
30960b57cec5SDimitry Andric 
30970b57cec5SDimitry Andric     // Check for another def in the MBB.
30980b57cec5SDimitry Andric     if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
30990b57cec5SDimitry Andric       break;
31000b57cec5SDimitry Andric 
31010b57cec5SDimitry Andric     // Lanes written by the new def are no longer tainted.
31020b57cec5SDimitry Andric     const Val &OV = Other.Vals[OtherI->valno->id];
31030b57cec5SDimitry Andric     TaintedLanes &= ~OV.WriteLanes;
31040b57cec5SDimitry Andric     if (!OV.RedefVNI)
31050b57cec5SDimitry Andric       break;
31060b57cec5SDimitry Andric   } while (TaintedLanes.any());
31070b57cec5SDimitry Andric   return true;
31080b57cec5SDimitry Andric }
31090b57cec5SDimitry Andric 
3110e8d8bef9SDimitry Andric bool JoinVals::usesLanes(const MachineInstr &MI, Register Reg, unsigned SubIdx,
31110b57cec5SDimitry Andric                          LaneBitmask Lanes) const {
3112fe6060f1SDimitry Andric   if (MI.isDebugOrPseudoInstr())
31130b57cec5SDimitry Andric     return false;
311406c3fb27SDimitry Andric   for (const MachineOperand &MO : MI.all_uses()) {
311506c3fb27SDimitry Andric     if (MO.getReg() != Reg)
31160b57cec5SDimitry Andric       continue;
31170b57cec5SDimitry Andric     if (!MO.readsReg())
31180b57cec5SDimitry Andric       continue;
31190b57cec5SDimitry Andric     unsigned S = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
31200b57cec5SDimitry Andric     if ((Lanes & TRI->getSubRegIndexLaneMask(S)).any())
31210b57cec5SDimitry Andric       return true;
31220b57cec5SDimitry Andric   }
31230b57cec5SDimitry Andric   return false;
31240b57cec5SDimitry Andric }
31250b57cec5SDimitry Andric 
31260b57cec5SDimitry Andric bool JoinVals::resolveConflicts(JoinVals &Other) {
31270b57cec5SDimitry Andric   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
31280b57cec5SDimitry Andric     Val &V = Vals[i];
31290b57cec5SDimitry Andric     assert(V.Resolution != CR_Impossible && "Unresolvable conflict");
31300b57cec5SDimitry Andric     if (V.Resolution != CR_Unresolved)
31310b57cec5SDimitry Andric       continue;
31320b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\t\tconflict at " << printReg(Reg) << ':' << i << '@'
31335ffd83dbSDimitry Andric                       << LR.getValNumInfo(i)->def
31345ffd83dbSDimitry Andric                       << ' ' << PrintLaneMask(LaneMask) << '\n');
31350b57cec5SDimitry Andric     if (SubRangeJoin)
31360b57cec5SDimitry Andric       return false;
31370b57cec5SDimitry Andric 
31380b57cec5SDimitry Andric     ++NumLaneConflicts;
31390b57cec5SDimitry Andric     assert(V.OtherVNI && "Inconsistent conflict resolution.");
31400b57cec5SDimitry Andric     VNInfo *VNI = LR.getValNumInfo(i);
31410b57cec5SDimitry Andric     const Val &OtherV = Other.Vals[V.OtherVNI->id];
31420b57cec5SDimitry Andric 
31430b57cec5SDimitry Andric     // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
31440b57cec5SDimitry Andric     // join, those lanes will be tainted with a wrong value. Get the extent of
31450b57cec5SDimitry Andric     // the tainted lanes.
31460b57cec5SDimitry Andric     LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
31470b57cec5SDimitry Andric     SmallVector<std::pair<SlotIndex, LaneBitmask>, 8> TaintExtent;
31480b57cec5SDimitry Andric     if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
31490b57cec5SDimitry Andric       // Tainted lanes would extend beyond the basic block.
31500b57cec5SDimitry Andric       return false;
31510b57cec5SDimitry Andric 
31520b57cec5SDimitry Andric     assert(!TaintExtent.empty() && "There should be at least one conflict.");
31530b57cec5SDimitry Andric 
31540b57cec5SDimitry Andric     // Now look at the instructions from VNI->def to TaintExtent (inclusive).
31550b57cec5SDimitry Andric     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
31560b57cec5SDimitry Andric     MachineBasicBlock::iterator MI = MBB->begin();
31570b57cec5SDimitry Andric     if (!VNI->isPHIDef()) {
31580b57cec5SDimitry Andric       MI = Indexes->getInstructionFromIndex(VNI->def);
3159fe6060f1SDimitry Andric       if (!VNI->def.isEarlyClobber()) {
31600b57cec5SDimitry Andric         // No need to check the instruction defining VNI for reads.
31610b57cec5SDimitry Andric         ++MI;
31620b57cec5SDimitry Andric       }
3163fe6060f1SDimitry Andric     }
31640b57cec5SDimitry Andric     assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
31650b57cec5SDimitry Andric            "Interference ends on VNI->def. Should have been handled earlier");
31660b57cec5SDimitry Andric     MachineInstr *LastMI =
31670b57cec5SDimitry Andric       Indexes->getInstructionFromIndex(TaintExtent.front().first);
31680b57cec5SDimitry Andric     assert(LastMI && "Range must end at a proper instruction");
31690b57cec5SDimitry Andric     unsigned TaintNum = 0;
31700b57cec5SDimitry Andric     while (true) {
31710b57cec5SDimitry Andric       assert(MI != MBB->end() && "Bad LastMI");
31720b57cec5SDimitry Andric       if (usesLanes(*MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
31730b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
31740b57cec5SDimitry Andric         return false;
31750b57cec5SDimitry Andric       }
31760b57cec5SDimitry Andric       // LastMI is the last instruction to use the current value.
31770b57cec5SDimitry Andric       if (&*MI == LastMI) {
31780b57cec5SDimitry Andric         if (++TaintNum == TaintExtent.size())
31790b57cec5SDimitry Andric           break;
31800b57cec5SDimitry Andric         LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
31810b57cec5SDimitry Andric         assert(LastMI && "Range must end at a proper instruction");
31820b57cec5SDimitry Andric         TaintedLanes = TaintExtent[TaintNum].second;
31830b57cec5SDimitry Andric       }
31840b57cec5SDimitry Andric       ++MI;
31850b57cec5SDimitry Andric     }
31860b57cec5SDimitry Andric 
31870b57cec5SDimitry Andric     // The tainted lanes are unused.
31880b57cec5SDimitry Andric     V.Resolution = CR_Replace;
31890b57cec5SDimitry Andric     ++NumLaneResolves;
31900b57cec5SDimitry Andric   }
31910b57cec5SDimitry Andric   return true;
31920b57cec5SDimitry Andric }
31930b57cec5SDimitry Andric 
31940b57cec5SDimitry Andric bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
31950b57cec5SDimitry Andric   Val &V = Vals[ValNo];
31960b57cec5SDimitry Andric   if (V.Pruned || V.PrunedComputed)
31970b57cec5SDimitry Andric     return V.Pruned;
31980b57cec5SDimitry Andric 
31990b57cec5SDimitry Andric   if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
32000b57cec5SDimitry Andric     return V.Pruned;
32010b57cec5SDimitry Andric 
32020b57cec5SDimitry Andric   // Follow copies up the dominator tree and check if any intermediate value
32030b57cec5SDimitry Andric   // has been pruned.
32040b57cec5SDimitry Andric   V.PrunedComputed = true;
32050b57cec5SDimitry Andric   V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
32060b57cec5SDimitry Andric   return V.Pruned;
32070b57cec5SDimitry Andric }
32080b57cec5SDimitry Andric 
32090b57cec5SDimitry Andric void JoinVals::pruneValues(JoinVals &Other,
32100b57cec5SDimitry Andric                            SmallVectorImpl<SlotIndex> &EndPoints,
32110b57cec5SDimitry Andric                            bool changeInstrs) {
32120b57cec5SDimitry Andric   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
32130b57cec5SDimitry Andric     SlotIndex Def = LR.getValNumInfo(i)->def;
32140b57cec5SDimitry Andric     switch (Vals[i].Resolution) {
32150b57cec5SDimitry Andric     case CR_Keep:
32160b57cec5SDimitry Andric       break;
32170b57cec5SDimitry Andric     case CR_Replace: {
32180b57cec5SDimitry Andric       // This value takes precedence over the value in Other.LR.
32190b57cec5SDimitry Andric       LIS->pruneValue(Other.LR, Def, &EndPoints);
32200b57cec5SDimitry Andric       // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
32210b57cec5SDimitry Andric       // instructions are only inserted to provide a live-out value for PHI
32220b57cec5SDimitry Andric       // predecessors, so the instruction should simply go away once its value
32230b57cec5SDimitry Andric       // has been replaced.
32240b57cec5SDimitry Andric       Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
32250b57cec5SDimitry Andric       bool EraseImpDef = OtherV.ErasableImplicitDef &&
32260b57cec5SDimitry Andric                          OtherV.Resolution == CR_Keep;
32270b57cec5SDimitry Andric       if (!Def.isBlock()) {
32280b57cec5SDimitry Andric         if (changeInstrs) {
32290b57cec5SDimitry Andric           // Remove <def,read-undef> flags. This def is now a partial redef.
32300b57cec5SDimitry Andric           // Also remove dead flags since the joined live range will
32310b57cec5SDimitry Andric           // continue past this instruction.
32320b57cec5SDimitry Andric           for (MachineOperand &MO :
32330b57cec5SDimitry Andric                Indexes->getInstructionFromIndex(Def)->operands()) {
32340b57cec5SDimitry Andric             if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) {
32350b57cec5SDimitry Andric               if (MO.getSubReg() != 0 && MO.isUndef() && !EraseImpDef)
32360b57cec5SDimitry Andric                 MO.setIsUndef(false);
32370b57cec5SDimitry Andric               MO.setIsDead(false);
32380b57cec5SDimitry Andric             }
32390b57cec5SDimitry Andric           }
32400b57cec5SDimitry Andric         }
32410b57cec5SDimitry Andric         // This value will reach instructions below, but we need to make sure
32420b57cec5SDimitry Andric         // the live range also reaches the instruction at Def.
32430b57cec5SDimitry Andric         if (!EraseImpDef)
32440b57cec5SDimitry Andric           EndPoints.push_back(Def);
32450b57cec5SDimitry Andric       }
32460b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\t\tpruned " << printReg(Other.Reg) << " at " << Def
32470b57cec5SDimitry Andric                         << ": " << Other.LR << '\n');
32480b57cec5SDimitry Andric       break;
32490b57cec5SDimitry Andric     }
32500b57cec5SDimitry Andric     case CR_Erase:
32510b57cec5SDimitry Andric     case CR_Merge:
32520b57cec5SDimitry Andric       if (isPrunedValue(i, Other)) {
32530b57cec5SDimitry Andric         // This value is ultimately a copy of a pruned value in LR or Other.LR.
32540b57cec5SDimitry Andric         // We can no longer trust the value mapping computed by
32550b57cec5SDimitry Andric         // computeAssignment(), the value that was originally copied could have
32560b57cec5SDimitry Andric         // been replaced.
32570b57cec5SDimitry Andric         LIS->pruneValue(LR, Def, &EndPoints);
32580b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "\t\tpruned all of " << printReg(Reg) << " at "
32590b57cec5SDimitry Andric                           << Def << ": " << LR << '\n');
32600b57cec5SDimitry Andric       }
32610b57cec5SDimitry Andric       break;
32620b57cec5SDimitry Andric     case CR_Unresolved:
32630b57cec5SDimitry Andric     case CR_Impossible:
32640b57cec5SDimitry Andric       llvm_unreachable("Unresolved conflicts");
32650b57cec5SDimitry Andric     }
32660b57cec5SDimitry Andric   }
32670b57cec5SDimitry Andric }
32680b57cec5SDimitry Andric 
3269fe6060f1SDimitry Andric // Check if the segment consists of a copied live-through value (i.e. the copy
3270fe6060f1SDimitry Andric // in the block only extended the liveness, of an undef value which we may need
3271fe6060f1SDimitry Andric // to handle).
3272fe6060f1SDimitry Andric static bool isLiveThrough(const LiveQueryResult Q) {
3273fe6060f1SDimitry Andric   return Q.valueIn() && Q.valueIn()->isPHIDef() && Q.valueIn() == Q.valueOut();
3274fe6060f1SDimitry Andric }
3275fe6060f1SDimitry Andric 
32760b57cec5SDimitry Andric /// Consider the following situation when coalescing the copy between
32770b57cec5SDimitry Andric /// %31 and %45 at 800. (The vertical lines represent live range segments.)
32780b57cec5SDimitry Andric ///
32790b57cec5SDimitry Andric ///                              Main range         Subrange 0004 (sub2)
32800b57cec5SDimitry Andric ///                              %31    %45           %31    %45
32810b57cec5SDimitry Andric ///  544    %45 = COPY %28               +                    +
32820b57cec5SDimitry Andric ///                                      | v1                 | v1
32830b57cec5SDimitry Andric ///  560B bb.1:                          +                    +
32840b57cec5SDimitry Andric ///  624        = %45.sub2               | v2                 | v2
32850b57cec5SDimitry Andric ///  800    %31 = COPY %45        +      +             +      +
32860b57cec5SDimitry Andric ///                               | v0                 | v0
32870b57cec5SDimitry Andric ///  816    %31.sub1 = ...        +                    |
32880b57cec5SDimitry Andric ///  880    %30 = COPY %31        | v1                 +
32890b57cec5SDimitry Andric ///  928    %45 = COPY %30        |      +                    +
32900b57cec5SDimitry Andric ///                               |      | v0                 | v0  <--+
32910b57cec5SDimitry Andric ///  992B   ; backedge -> bb.1    |      +                    +        |
32920b57cec5SDimitry Andric /// 1040        = %31.sub0        +                                    |
32930b57cec5SDimitry Andric ///                                                 This value must remain
32940b57cec5SDimitry Andric ///                                                 live-out!
32950b57cec5SDimitry Andric ///
32960b57cec5SDimitry Andric /// Assuming that %31 is coalesced into %45, the copy at 928 becomes
32970b57cec5SDimitry Andric /// redundant, since it copies the value from %45 back into it. The
32980b57cec5SDimitry Andric /// conflict resolution for the main range determines that %45.v0 is
32990b57cec5SDimitry Andric /// to be erased, which is ok since %31.v1 is identical to it.
33000b57cec5SDimitry Andric /// The problem happens with the subrange for sub2: it has to be live
33010b57cec5SDimitry Andric /// on exit from the block, but since 928 was actually a point of
33020b57cec5SDimitry Andric /// definition of %45.sub2, %45.sub2 was not live immediately prior
33030b57cec5SDimitry Andric /// to that definition. As a result, when 928 was erased, the value v0
33040b57cec5SDimitry Andric /// for %45.sub2 was pruned in pruneSubRegValues. Consequently, an
33050b57cec5SDimitry Andric /// IMPLICIT_DEF was inserted as a "backedge" definition for %45.sub2,
33060b57cec5SDimitry Andric /// providing an incorrect value to the use at 624.
33070b57cec5SDimitry Andric ///
33080b57cec5SDimitry Andric /// Since the main-range values %31.v1 and %45.v0 were proved to be
33090b57cec5SDimitry Andric /// identical, the corresponding values in subranges must also be the
33100b57cec5SDimitry Andric /// same. A redundant copy is removed because it's not needed, and not
33110b57cec5SDimitry Andric /// because it copied an undefined value, so any liveness that originated
33120b57cec5SDimitry Andric /// from that copy cannot disappear. When pruning a value that started
33130b57cec5SDimitry Andric /// at the removed copy, the corresponding identical value must be
33140b57cec5SDimitry Andric /// extended to replace it.
33150b57cec5SDimitry Andric void JoinVals::pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask) {
33160b57cec5SDimitry Andric   // Look for values being erased.
33170b57cec5SDimitry Andric   bool DidPrune = false;
33180b57cec5SDimitry Andric   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
33190b57cec5SDimitry Andric     Val &V = Vals[i];
33200b57cec5SDimitry Andric     // We should trigger in all cases in which eraseInstrs() does something.
33210b57cec5SDimitry Andric     // match what eraseInstrs() is doing, print a message so
33220b57cec5SDimitry Andric     if (V.Resolution != CR_Erase &&
33230b57cec5SDimitry Andric         (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned))
33240b57cec5SDimitry Andric       continue;
33250b57cec5SDimitry Andric 
33260b57cec5SDimitry Andric     // Check subranges at the point where the copy will be removed.
33270b57cec5SDimitry Andric     SlotIndex Def = LR.getValNumInfo(i)->def;
33280b57cec5SDimitry Andric     SlotIndex OtherDef;
33290b57cec5SDimitry Andric     if (V.Identical)
33300b57cec5SDimitry Andric       OtherDef = V.OtherVNI->def;
33310b57cec5SDimitry Andric 
33320b57cec5SDimitry Andric     // Print message so mismatches with eraseInstrs() can be diagnosed.
33330b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\t\tExpecting instruction removal at " << Def
33340b57cec5SDimitry Andric                       << '\n');
33350b57cec5SDimitry Andric     for (LiveInterval::SubRange &S : LI.subranges()) {
33360b57cec5SDimitry Andric       LiveQueryResult Q = S.Query(Def);
33370b57cec5SDimitry Andric 
33380b57cec5SDimitry Andric       // If a subrange starts at the copy then an undefined value has been
33390b57cec5SDimitry Andric       // copied and we must remove that subrange value as well.
33400b57cec5SDimitry Andric       VNInfo *ValueOut = Q.valueOutOrDead();
33410b57cec5SDimitry Andric       if (ValueOut != nullptr && (Q.valueIn() == nullptr ||
33420b57cec5SDimitry Andric                                   (V.Identical && V.Resolution == CR_Erase &&
33430b57cec5SDimitry Andric                                    ValueOut->def == Def))) {
33440b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask)
33450b57cec5SDimitry Andric                           << " at " << Def << "\n");
33460b57cec5SDimitry Andric         SmallVector<SlotIndex,8> EndPoints;
33470b57cec5SDimitry Andric         LIS->pruneValue(S, Def, &EndPoints);
33480b57cec5SDimitry Andric         DidPrune = true;
33490b57cec5SDimitry Andric         // Mark value number as unused.
33500b57cec5SDimitry Andric         ValueOut->markUnused();
33510b57cec5SDimitry Andric 
33520b57cec5SDimitry Andric         if (V.Identical && S.Query(OtherDef).valueOutOrDead()) {
33530b57cec5SDimitry Andric           // If V is identical to V.OtherVNI (and S was live at OtherDef),
33540b57cec5SDimitry Andric           // then we can't simply prune V from S. V needs to be replaced
33550b57cec5SDimitry Andric           // with V.OtherVNI.
33560b57cec5SDimitry Andric           LIS->extendToIndices(S, EndPoints);
33570b57cec5SDimitry Andric         }
3358fe6060f1SDimitry Andric 
3359fe6060f1SDimitry Andric         // We may need to eliminate the subrange if the copy introduced a live
3360fe6060f1SDimitry Andric         // out undef value.
3361fe6060f1SDimitry Andric         if (ValueOut->isPHIDef())
3362fe6060f1SDimitry Andric           ShrinkMask |= S.LaneMask;
33630b57cec5SDimitry Andric         continue;
33640b57cec5SDimitry Andric       }
3365fe6060f1SDimitry Andric 
33660b57cec5SDimitry Andric       // If a subrange ends at the copy, then a value was copied but only
33670b57cec5SDimitry Andric       // partially used later. Shrink the subregister range appropriately.
3368fe6060f1SDimitry Andric       //
3369fe6060f1SDimitry Andric       // Ultimately this calls shrinkToUses, so assuming ShrinkMask is
3370fe6060f1SDimitry Andric       // conservatively correct.
3371fe6060f1SDimitry Andric       if ((Q.valueIn() != nullptr && Q.valueOut() == nullptr) ||
3372fe6060f1SDimitry Andric           (V.Resolution == CR_Erase && isLiveThrough(Q))) {
33730b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "\t\tDead uses at sublane "
33740b57cec5SDimitry Andric                           << PrintLaneMask(S.LaneMask) << " at " << Def
33750b57cec5SDimitry Andric                           << "\n");
33760b57cec5SDimitry Andric         ShrinkMask |= S.LaneMask;
33770b57cec5SDimitry Andric       }
33780b57cec5SDimitry Andric     }
33790b57cec5SDimitry Andric   }
33800b57cec5SDimitry Andric   if (DidPrune)
33810b57cec5SDimitry Andric     LI.removeEmptySubRanges();
33820b57cec5SDimitry Andric }
33830b57cec5SDimitry Andric 
33840b57cec5SDimitry Andric /// Check if any of the subranges of @p LI contain a definition at @p Def.
33850b57cec5SDimitry Andric static bool isDefInSubRange(LiveInterval &LI, SlotIndex Def) {
33860b57cec5SDimitry Andric   for (LiveInterval::SubRange &SR : LI.subranges()) {
33870b57cec5SDimitry Andric     if (VNInfo *VNI = SR.Query(Def).valueOutOrDead())
33880b57cec5SDimitry Andric       if (VNI->def == Def)
33890b57cec5SDimitry Andric         return true;
33900b57cec5SDimitry Andric   }
33910b57cec5SDimitry Andric   return false;
33920b57cec5SDimitry Andric }
33930b57cec5SDimitry Andric 
33940b57cec5SDimitry Andric void JoinVals::pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange) {
33950b57cec5SDimitry Andric   assert(&static_cast<LiveRange&>(LI) == &LR);
33960b57cec5SDimitry Andric 
33970b57cec5SDimitry Andric   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
33980b57cec5SDimitry Andric     if (Vals[i].Resolution != CR_Keep)
33990b57cec5SDimitry Andric       continue;
34000b57cec5SDimitry Andric     VNInfo *VNI = LR.getValNumInfo(i);
34010b57cec5SDimitry Andric     if (VNI->isUnused() || VNI->isPHIDef() || isDefInSubRange(LI, VNI->def))
34020b57cec5SDimitry Andric       continue;
34030b57cec5SDimitry Andric     Vals[i].Pruned = true;
34040b57cec5SDimitry Andric     ShrinkMainRange = true;
34050b57cec5SDimitry Andric   }
34060b57cec5SDimitry Andric }
34070b57cec5SDimitry Andric 
34080b57cec5SDimitry Andric void JoinVals::removeImplicitDefs() {
34090b57cec5SDimitry Andric   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
34100b57cec5SDimitry Andric     Val &V = Vals[i];
34110b57cec5SDimitry Andric     if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
34120b57cec5SDimitry Andric       continue;
34130b57cec5SDimitry Andric 
34140b57cec5SDimitry Andric     VNInfo *VNI = LR.getValNumInfo(i);
34150b57cec5SDimitry Andric     VNI->markUnused();
34160b57cec5SDimitry Andric     LR.removeValNo(VNI);
34170b57cec5SDimitry Andric   }
34180b57cec5SDimitry Andric }
34190b57cec5SDimitry Andric 
34200b57cec5SDimitry Andric void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
34215ffd83dbSDimitry Andric                            SmallVectorImpl<Register> &ShrinkRegs,
34220b57cec5SDimitry Andric                            LiveInterval *LI) {
34230b57cec5SDimitry Andric   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
34240b57cec5SDimitry Andric     // Get the def location before markUnused() below invalidates it.
3425480093f4SDimitry Andric     VNInfo *VNI = LR.getValNumInfo(i);
3426480093f4SDimitry Andric     SlotIndex Def = VNI->def;
34270b57cec5SDimitry Andric     switch (Vals[i].Resolution) {
34280b57cec5SDimitry Andric     case CR_Keep: {
34290b57cec5SDimitry Andric       // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
34300b57cec5SDimitry Andric       // longer. The IMPLICIT_DEF instructions are only inserted by
34310b57cec5SDimitry Andric       // PHIElimination to guarantee that all PHI predecessors have a value.
34320b57cec5SDimitry Andric       if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
34330b57cec5SDimitry Andric         break;
34340b57cec5SDimitry Andric       // Remove value number i from LR.
34350b57cec5SDimitry Andric       // For intervals with subranges, removing a segment from the main range
34360b57cec5SDimitry Andric       // may require extending the previous segment: for each definition of
34370b57cec5SDimitry Andric       // a subregister, there will be a corresponding def in the main range.
34380b57cec5SDimitry Andric       // That def may fall in the middle of a segment from another subrange.
34390b57cec5SDimitry Andric       // In such cases, removing this def from the main range must be
34400b57cec5SDimitry Andric       // complemented by extending the main range to account for the liveness
34410b57cec5SDimitry Andric       // of the other subrange.
34420b57cec5SDimitry Andric       // The new end point of the main range segment to be extended.
34430b57cec5SDimitry Andric       SlotIndex NewEnd;
34440b57cec5SDimitry Andric       if (LI != nullptr) {
34450b57cec5SDimitry Andric         LiveRange::iterator I = LR.FindSegmentContaining(Def);
34460b57cec5SDimitry Andric         assert(I != LR.end());
34470b57cec5SDimitry Andric         // Do not extend beyond the end of the segment being removed.
34480b57cec5SDimitry Andric         // The segment may have been pruned in preparation for joining
34490b57cec5SDimitry Andric         // live ranges.
34500b57cec5SDimitry Andric         NewEnd = I->end;
34510b57cec5SDimitry Andric       }
34520b57cec5SDimitry Andric 
34530b57cec5SDimitry Andric       LR.removeValNo(VNI);
34540b57cec5SDimitry Andric       // Note that this VNInfo is reused and still referenced in NewVNInfo,
34550b57cec5SDimitry Andric       // make it appear like an unused value number.
34560b57cec5SDimitry Andric       VNI->markUnused();
34570b57cec5SDimitry Andric 
34580b57cec5SDimitry Andric       if (LI != nullptr && LI->hasSubRanges()) {
34590b57cec5SDimitry Andric         assert(static_cast<LiveRange*>(LI) == &LR);
34600b57cec5SDimitry Andric         // Determine the end point based on the subrange information:
34610b57cec5SDimitry Andric         // minimum of (earliest def of next segment,
34620b57cec5SDimitry Andric         //             latest end point of containing segment)
34630b57cec5SDimitry Andric         SlotIndex ED, LE;
34640b57cec5SDimitry Andric         for (LiveInterval::SubRange &SR : LI->subranges()) {
34650b57cec5SDimitry Andric           LiveRange::iterator I = SR.find(Def);
34660b57cec5SDimitry Andric           if (I == SR.end())
34670b57cec5SDimitry Andric             continue;
34680b57cec5SDimitry Andric           if (I->start > Def)
34690b57cec5SDimitry Andric             ED = ED.isValid() ? std::min(ED, I->start) : I->start;
34700b57cec5SDimitry Andric           else
34710b57cec5SDimitry Andric             LE = LE.isValid() ? std::max(LE, I->end) : I->end;
34720b57cec5SDimitry Andric         }
34730b57cec5SDimitry Andric         if (LE.isValid())
34740b57cec5SDimitry Andric           NewEnd = std::min(NewEnd, LE);
34750b57cec5SDimitry Andric         if (ED.isValid())
34760b57cec5SDimitry Andric           NewEnd = std::min(NewEnd, ED);
34770b57cec5SDimitry Andric 
34780b57cec5SDimitry Andric         // We only want to do the extension if there was a subrange that
34790b57cec5SDimitry Andric         // was live across Def.
34800b57cec5SDimitry Andric         if (LE.isValid()) {
34810b57cec5SDimitry Andric           LiveRange::iterator S = LR.find(Def);
34820b57cec5SDimitry Andric           if (S != LR.begin())
34830b57cec5SDimitry Andric             std::prev(S)->end = NewEnd;
34840b57cec5SDimitry Andric         }
34850b57cec5SDimitry Andric       }
34860b57cec5SDimitry Andric       LLVM_DEBUG({
34870b57cec5SDimitry Andric         dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n';
34880b57cec5SDimitry Andric         if (LI != nullptr)
34890b57cec5SDimitry Andric           dbgs() << "\t\t  LHS = " << *LI << '\n';
34900b57cec5SDimitry Andric       });
3491bdd1243dSDimitry Andric       [[fallthrough]];
34920b57cec5SDimitry Andric     }
34930b57cec5SDimitry Andric 
34940b57cec5SDimitry Andric     case CR_Erase: {
34950b57cec5SDimitry Andric       MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
34960b57cec5SDimitry Andric       assert(MI && "No instruction to erase");
34970b57cec5SDimitry Andric       if (MI->isCopy()) {
34988bcb0991SDimitry Andric         Register Reg = MI->getOperand(1).getReg();
3499bdd1243dSDimitry Andric         if (Reg.isVirtual() && Reg != CP.getSrcReg() && Reg != CP.getDstReg())
35000b57cec5SDimitry Andric           ShrinkRegs.push_back(Reg);
35010b57cec5SDimitry Andric       }
35020b57cec5SDimitry Andric       ErasedInstrs.insert(MI);
35030b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
35040b57cec5SDimitry Andric       LIS->RemoveMachineInstrFromMaps(*MI);
35050b57cec5SDimitry Andric       MI->eraseFromParent();
35060b57cec5SDimitry Andric       break;
35070b57cec5SDimitry Andric     }
35080b57cec5SDimitry Andric     default:
35090b57cec5SDimitry Andric       break;
35100b57cec5SDimitry Andric     }
35110b57cec5SDimitry Andric   }
35120b57cec5SDimitry Andric }
35130b57cec5SDimitry Andric 
35140b57cec5SDimitry Andric void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
35150b57cec5SDimitry Andric                                          LaneBitmask LaneMask,
35160b57cec5SDimitry Andric                                          const CoalescerPair &CP) {
35170b57cec5SDimitry Andric   SmallVector<VNInfo*, 16> NewVNInfo;
35180b57cec5SDimitry Andric   JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask,
35190b57cec5SDimitry Andric                    NewVNInfo, CP, LIS, TRI, true, true);
35200b57cec5SDimitry Andric   JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
35210b57cec5SDimitry Andric                    NewVNInfo, CP, LIS, TRI, true, true);
35220b57cec5SDimitry Andric 
35230b57cec5SDimitry Andric   // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
35240b57cec5SDimitry Andric   // We should be able to resolve all conflicts here as we could successfully do
35250b57cec5SDimitry Andric   // it on the mainrange already. There is however a problem when multiple
35260b57cec5SDimitry Andric   // ranges get mapped to the "overflow" lane mask bit which creates unexpected
35270b57cec5SDimitry Andric   // interferences.
35280b57cec5SDimitry Andric   if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
35290b57cec5SDimitry Andric     // We already determined that it is legal to merge the intervals, so this
35300b57cec5SDimitry Andric     // should never fail.
35310b57cec5SDimitry Andric     llvm_unreachable("*** Couldn't join subrange!\n");
35320b57cec5SDimitry Andric   }
35330b57cec5SDimitry Andric   if (!LHSVals.resolveConflicts(RHSVals) ||
35340b57cec5SDimitry Andric       !RHSVals.resolveConflicts(LHSVals)) {
35350b57cec5SDimitry Andric     // We already determined that it is legal to merge the intervals, so this
35360b57cec5SDimitry Andric     // should never fail.
35370b57cec5SDimitry Andric     llvm_unreachable("*** Couldn't join subrange!\n");
35380b57cec5SDimitry Andric   }
35390b57cec5SDimitry Andric 
35400b57cec5SDimitry Andric   // The merging algorithm in LiveInterval::join() can't handle conflicting
35410b57cec5SDimitry Andric   // value mappings, so we need to remove any live ranges that overlap a
35420b57cec5SDimitry Andric   // CR_Replace resolution. Collect a set of end points that can be used to
35430b57cec5SDimitry Andric   // restore the live range after joining.
35440b57cec5SDimitry Andric   SmallVector<SlotIndex, 8> EndPoints;
35450b57cec5SDimitry Andric   LHSVals.pruneValues(RHSVals, EndPoints, false);
35460b57cec5SDimitry Andric   RHSVals.pruneValues(LHSVals, EndPoints, false);
35470b57cec5SDimitry Andric 
35480b57cec5SDimitry Andric   LHSVals.removeImplicitDefs();
35490b57cec5SDimitry Andric   RHSVals.removeImplicitDefs();
35500b57cec5SDimitry Andric 
35510b57cec5SDimitry Andric   LRange.verify();
35520b57cec5SDimitry Andric   RRange.verify();
35530b57cec5SDimitry Andric 
35540b57cec5SDimitry Andric   // Join RRange into LHS.
35550b57cec5SDimitry Andric   LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
35560b57cec5SDimitry Andric               NewVNInfo);
35570b57cec5SDimitry Andric 
35580b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\t\tjoined lanes: " << PrintLaneMask(LaneMask)
35590b57cec5SDimitry Andric                     << ' ' << LRange << "\n");
35600b57cec5SDimitry Andric   if (EndPoints.empty())
35610b57cec5SDimitry Andric     return;
35620b57cec5SDimitry Andric 
35630b57cec5SDimitry Andric   // Recompute the parts of the live range we had to remove because of
35640b57cec5SDimitry Andric   // CR_Replace conflicts.
35650b57cec5SDimitry Andric   LLVM_DEBUG({
35660b57cec5SDimitry Andric     dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
35670b57cec5SDimitry Andric     for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
35680b57cec5SDimitry Andric       dbgs() << EndPoints[i];
35690b57cec5SDimitry Andric       if (i != n-1)
35700b57cec5SDimitry Andric         dbgs() << ',';
35710b57cec5SDimitry Andric     }
35720b57cec5SDimitry Andric     dbgs() << ":  " << LRange << '\n';
35730b57cec5SDimitry Andric   });
35740b57cec5SDimitry Andric   LIS->extendToIndices(LRange, EndPoints);
35750b57cec5SDimitry Andric }
35760b57cec5SDimitry Andric 
35770b57cec5SDimitry Andric void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
35780b57cec5SDimitry Andric                                           const LiveRange &ToMerge,
35790b57cec5SDimitry Andric                                           LaneBitmask LaneMask,
3580480093f4SDimitry Andric                                           CoalescerPair &CP,
3581480093f4SDimitry Andric                                           unsigned ComposeSubRegIdx) {
35820b57cec5SDimitry Andric   BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
35830b57cec5SDimitry Andric   LI.refineSubRanges(
35840b57cec5SDimitry Andric       Allocator, LaneMask,
35850b57cec5SDimitry Andric       [this, &Allocator, &ToMerge, &CP](LiveInterval::SubRange &SR) {
35860b57cec5SDimitry Andric         if (SR.empty()) {
35870b57cec5SDimitry Andric           SR.assign(ToMerge, Allocator);
35880b57cec5SDimitry Andric         } else {
35890b57cec5SDimitry Andric           // joinSubRegRange() destroys the merged range, so we need a copy.
35900b57cec5SDimitry Andric           LiveRange RangeCopy(ToMerge, Allocator);
35910b57cec5SDimitry Andric           joinSubRegRanges(SR, RangeCopy, SR.LaneMask, CP);
35920b57cec5SDimitry Andric         }
35930b57cec5SDimitry Andric       },
3594480093f4SDimitry Andric       *LIS->getSlotIndexes(), *TRI, ComposeSubRegIdx);
35950b57cec5SDimitry Andric }
35960b57cec5SDimitry Andric 
35970b57cec5SDimitry Andric bool RegisterCoalescer::isHighCostLiveInterval(LiveInterval &LI) {
35980b57cec5SDimitry Andric   if (LI.valnos.size() < LargeIntervalSizeThreshold)
35990b57cec5SDimitry Andric     return false;
3600e8d8bef9SDimitry Andric   auto &Counter = LargeLIVisitCounter[LI.reg()];
36010b57cec5SDimitry Andric   if (Counter < LargeIntervalFreqThreshold) {
36020b57cec5SDimitry Andric     Counter++;
36030b57cec5SDimitry Andric     return false;
36040b57cec5SDimitry Andric   }
36050b57cec5SDimitry Andric   return true;
36060b57cec5SDimitry Andric }
36070b57cec5SDimitry Andric 
36080b57cec5SDimitry Andric bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
36090b57cec5SDimitry Andric   SmallVector<VNInfo*, 16> NewVNInfo;
36100b57cec5SDimitry Andric   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
36110b57cec5SDimitry Andric   LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
36120b57cec5SDimitry Andric   bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC());
36130b57cec5SDimitry Andric   JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), LaneBitmask::getNone(),
36140b57cec5SDimitry Andric                    NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
36150b57cec5SDimitry Andric   JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), LaneBitmask::getNone(),
36160b57cec5SDimitry Andric                    NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
36170b57cec5SDimitry Andric 
36180b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << "\n\t\tLHS = " << LHS << '\n');
36190b57cec5SDimitry Andric 
36200b57cec5SDimitry Andric   if (isHighCostLiveInterval(LHS) || isHighCostLiveInterval(RHS))
36210b57cec5SDimitry Andric     return false;
36220b57cec5SDimitry Andric 
36230b57cec5SDimitry Andric   // First compute NewVNInfo and the simple value mappings.
36240b57cec5SDimitry Andric   // Detect impossible conflicts early.
36250b57cec5SDimitry Andric   if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
36260b57cec5SDimitry Andric     return false;
36270b57cec5SDimitry Andric 
36280b57cec5SDimitry Andric   // Some conflicts can only be resolved after all values have been mapped.
36290b57cec5SDimitry Andric   if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
36300b57cec5SDimitry Andric     return false;
36310b57cec5SDimitry Andric 
36320b57cec5SDimitry Andric   // All clear, the live ranges can be merged.
36330b57cec5SDimitry Andric   if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
36340b57cec5SDimitry Andric     BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
36350b57cec5SDimitry Andric 
36360b57cec5SDimitry Andric     // Transform lanemasks from the LHS to masks in the coalesced register and
36370b57cec5SDimitry Andric     // create initial subranges if necessary.
36380b57cec5SDimitry Andric     unsigned DstIdx = CP.getDstIdx();
36390b57cec5SDimitry Andric     if (!LHS.hasSubRanges()) {
36400b57cec5SDimitry Andric       LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
36410b57cec5SDimitry Andric                                      : TRI->getSubRegIndexLaneMask(DstIdx);
36420b57cec5SDimitry Andric       // LHS must support subregs or we wouldn't be in this codepath.
36430b57cec5SDimitry Andric       assert(Mask.any());
36440b57cec5SDimitry Andric       LHS.createSubRangeFrom(Allocator, Mask, LHS);
36450b57cec5SDimitry Andric     } else if (DstIdx != 0) {
36460b57cec5SDimitry Andric       // Transform LHS lanemasks to new register class if necessary.
36470b57cec5SDimitry Andric       for (LiveInterval::SubRange &R : LHS.subranges()) {
36480b57cec5SDimitry Andric         LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
36490b57cec5SDimitry Andric         R.LaneMask = Mask;
36500b57cec5SDimitry Andric       }
36510b57cec5SDimitry Andric     }
36520b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\t\tLHST = " << printReg(CP.getDstReg()) << ' ' << LHS
36530b57cec5SDimitry Andric                       << '\n');
36540b57cec5SDimitry Andric 
36550b57cec5SDimitry Andric     // Determine lanemasks of RHS in the coalesced register and merge subranges.
36560b57cec5SDimitry Andric     unsigned SrcIdx = CP.getSrcIdx();
36570b57cec5SDimitry Andric     if (!RHS.hasSubRanges()) {
36580b57cec5SDimitry Andric       LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
36590b57cec5SDimitry Andric                                      : TRI->getSubRegIndexLaneMask(SrcIdx);
3660480093f4SDimitry Andric       mergeSubRangeInto(LHS, RHS, Mask, CP, DstIdx);
36610b57cec5SDimitry Andric     } else {
36620b57cec5SDimitry Andric       // Pair up subranges and merge.
36630b57cec5SDimitry Andric       for (LiveInterval::SubRange &R : RHS.subranges()) {
36640b57cec5SDimitry Andric         LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
3665480093f4SDimitry Andric         mergeSubRangeInto(LHS, R, Mask, CP, DstIdx);
36660b57cec5SDimitry Andric       }
36670b57cec5SDimitry Andric     }
36680b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
36690b57cec5SDimitry Andric 
36700b57cec5SDimitry Andric     // Pruning implicit defs from subranges may result in the main range
36710b57cec5SDimitry Andric     // having stale segments.
36720b57cec5SDimitry Andric     LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
36730b57cec5SDimitry Andric 
36740b57cec5SDimitry Andric     LHSVals.pruneSubRegValues(LHS, ShrinkMask);
36750b57cec5SDimitry Andric     RHSVals.pruneSubRegValues(LHS, ShrinkMask);
3676*52418fc2SDimitry Andric   } else if (TrackSubRegLiveness && !CP.getDstIdx() && CP.getSrcIdx()) {
3677*52418fc2SDimitry Andric     LHS.createSubRangeFrom(LIS->getVNInfoAllocator(),
3678*52418fc2SDimitry Andric                            CP.getNewRC()->getLaneMask(), LHS);
3679*52418fc2SDimitry Andric     mergeSubRangeInto(LHS, RHS, TRI->getSubRegIndexLaneMask(CP.getSrcIdx()), CP,
3680*52418fc2SDimitry Andric                       CP.getDstIdx());
3681*52418fc2SDimitry Andric     LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
3682*52418fc2SDimitry Andric     LHSVals.pruneSubRegValues(LHS, ShrinkMask);
36830b57cec5SDimitry Andric   }
36840b57cec5SDimitry Andric 
36850b57cec5SDimitry Andric   // The merging algorithm in LiveInterval::join() can't handle conflicting
36860b57cec5SDimitry Andric   // value mappings, so we need to remove any live ranges that overlap a
36870b57cec5SDimitry Andric   // CR_Replace resolution. Collect a set of end points that can be used to
36880b57cec5SDimitry Andric   // restore the live range after joining.
36890b57cec5SDimitry Andric   SmallVector<SlotIndex, 8> EndPoints;
36900b57cec5SDimitry Andric   LHSVals.pruneValues(RHSVals, EndPoints, true);
36910b57cec5SDimitry Andric   RHSVals.pruneValues(LHSVals, EndPoints, true);
36920b57cec5SDimitry Andric 
36930b57cec5SDimitry Andric   // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
36940b57cec5SDimitry Andric   // registers to require trimming.
36955ffd83dbSDimitry Andric   SmallVector<Register, 8> ShrinkRegs;
36960b57cec5SDimitry Andric   LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs, &LHS);
36970b57cec5SDimitry Andric   RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
36980b57cec5SDimitry Andric   while (!ShrinkRegs.empty())
36990b57cec5SDimitry Andric     shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
37000b57cec5SDimitry Andric 
3701480093f4SDimitry Andric   // Scan and mark undef any DBG_VALUEs that would refer to a different value.
3702480093f4SDimitry Andric   checkMergingChangesDbgValues(CP, LHS, LHSVals, RHS, RHSVals);
3703480093f4SDimitry Andric 
3704fe6060f1SDimitry Andric   // If the RHS covers any PHI locations that were tracked for debug-info, we
3705fe6060f1SDimitry Andric   // must update tracking information to reflect the join.
3706fe6060f1SDimitry Andric   auto RegIt = RegToPHIIdx.find(CP.getSrcReg());
3707fe6060f1SDimitry Andric   if (RegIt != RegToPHIIdx.end()) {
3708fe6060f1SDimitry Andric     // Iterate over all the debug instruction numbers assigned this register.
3709fe6060f1SDimitry Andric     for (unsigned InstID : RegIt->second) {
3710fe6060f1SDimitry Andric       auto PHIIt = PHIValToPos.find(InstID);
3711fe6060f1SDimitry Andric       assert(PHIIt != PHIValToPos.end());
3712fe6060f1SDimitry Andric       const SlotIndex &SI = PHIIt->second.SI;
3713fe6060f1SDimitry Andric 
3714fe6060f1SDimitry Andric       // Does the RHS cover the position of this PHI?
3715fe6060f1SDimitry Andric       auto LII = RHS.find(SI);
3716fe6060f1SDimitry Andric       if (LII == RHS.end() || LII->start > SI)
3717fe6060f1SDimitry Andric         continue;
3718fe6060f1SDimitry Andric 
3719fe6060f1SDimitry Andric       // Accept two kinds of subregister movement:
3720fe6060f1SDimitry Andric       //  * When we merge from one register class into a larger register:
3721fe6060f1SDimitry Andric       //        %1:gr16 = some-inst
3722fe6060f1SDimitry Andric       //                ->
3723fe6060f1SDimitry Andric       //        %2:gr32.sub_16bit = some-inst
3724fe6060f1SDimitry Andric       //  * When the PHI is already in a subregister, and the larger class
3725fe6060f1SDimitry Andric       //    is coalesced:
3726fe6060f1SDimitry Andric       //        %2:gr32.sub_16bit = some-inst
3727fe6060f1SDimitry Andric       //        %3:gr32 = COPY %2
3728fe6060f1SDimitry Andric       //                ->
3729fe6060f1SDimitry Andric       //        %3:gr32.sub_16bit = some-inst
3730fe6060f1SDimitry Andric       // Test for subregister move:
3731fe6060f1SDimitry Andric       if (CP.getSrcIdx() != 0 || CP.getDstIdx() != 0)
3732fe6060f1SDimitry Andric         // If we're moving between different subregisters, ignore this join.
3733fe6060f1SDimitry Andric         // The PHI will not get a location, dropping variable locations.
3734fe6060f1SDimitry Andric         if (PHIIt->second.SubReg && PHIIt->second.SubReg != CP.getSrcIdx())
3735fe6060f1SDimitry Andric           continue;
3736fe6060f1SDimitry Andric 
3737fe6060f1SDimitry Andric       // Update our tracking of where the PHI is.
3738fe6060f1SDimitry Andric       PHIIt->second.Reg = CP.getDstReg();
3739fe6060f1SDimitry Andric 
3740fe6060f1SDimitry Andric       // If we merge into a sub-register of a larger class (test above),
3741fe6060f1SDimitry Andric       // update SubReg.
3742fe6060f1SDimitry Andric       if (CP.getSrcIdx() != 0)
3743fe6060f1SDimitry Andric         PHIIt->second.SubReg = CP.getSrcIdx();
3744fe6060f1SDimitry Andric     }
3745fe6060f1SDimitry Andric 
3746fe6060f1SDimitry Andric     // Rebuild the register index in RegToPHIIdx to account for PHIs tracking
3747fe6060f1SDimitry Andric     // different VRegs now. Copy old collection of debug instruction numbers and
3748fe6060f1SDimitry Andric     // erase the old one:
3749fe6060f1SDimitry Andric     auto InstrNums = RegIt->second;
3750fe6060f1SDimitry Andric     RegToPHIIdx.erase(RegIt);
3751fe6060f1SDimitry Andric 
3752fe6060f1SDimitry Andric     // There might already be PHIs being tracked in the destination VReg. Insert
3753fe6060f1SDimitry Andric     // into an existing tracking collection, or insert a new one.
3754fe6060f1SDimitry Andric     RegIt = RegToPHIIdx.find(CP.getDstReg());
3755fe6060f1SDimitry Andric     if (RegIt != RegToPHIIdx.end())
3756fe6060f1SDimitry Andric       RegIt->second.insert(RegIt->second.end(), InstrNums.begin(),
3757fe6060f1SDimitry Andric                            InstrNums.end());
3758fe6060f1SDimitry Andric     else
3759fe6060f1SDimitry Andric       RegToPHIIdx.insert({CP.getDstReg(), InstrNums});
3760fe6060f1SDimitry Andric   }
3761fe6060f1SDimitry Andric 
37620b57cec5SDimitry Andric   // Join RHS into LHS.
37630b57cec5SDimitry Andric   LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
37640b57cec5SDimitry Andric 
37650b57cec5SDimitry Andric   // Kill flags are going to be wrong if the live ranges were overlapping.
37660b57cec5SDimitry Andric   // Eventually, we should simply clear all kill flags when computing live
37670b57cec5SDimitry Andric   // ranges. They are reinserted after register allocation.
3768e8d8bef9SDimitry Andric   MRI->clearKillFlags(LHS.reg());
3769e8d8bef9SDimitry Andric   MRI->clearKillFlags(RHS.reg());
37700b57cec5SDimitry Andric 
37710b57cec5SDimitry Andric   if (!EndPoints.empty()) {
37720b57cec5SDimitry Andric     // Recompute the parts of the live range we had to remove because of
37730b57cec5SDimitry Andric     // CR_Replace conflicts.
37740b57cec5SDimitry Andric     LLVM_DEBUG({
37750b57cec5SDimitry Andric       dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
37760b57cec5SDimitry Andric       for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
37770b57cec5SDimitry Andric         dbgs() << EndPoints[i];
37780b57cec5SDimitry Andric         if (i != n-1)
37790b57cec5SDimitry Andric           dbgs() << ',';
37800b57cec5SDimitry Andric       }
37810b57cec5SDimitry Andric       dbgs() << ":  " << LHS << '\n';
37820b57cec5SDimitry Andric     });
37830b57cec5SDimitry Andric     LIS->extendToIndices((LiveRange&)LHS, EndPoints);
37840b57cec5SDimitry Andric   }
37850b57cec5SDimitry Andric 
37860b57cec5SDimitry Andric   return true;
37870b57cec5SDimitry Andric }
37880b57cec5SDimitry Andric 
37890b57cec5SDimitry Andric bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
37900b57cec5SDimitry Andric   return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
37910b57cec5SDimitry Andric }
37920b57cec5SDimitry Andric 
3793480093f4SDimitry Andric void RegisterCoalescer::buildVRegToDbgValueMap(MachineFunction &MF)
3794480093f4SDimitry Andric {
3795480093f4SDimitry Andric   const SlotIndexes &Slots = *LIS->getSlotIndexes();
3796480093f4SDimitry Andric   SmallVector<MachineInstr *, 8> ToInsert;
3797480093f4SDimitry Andric 
3798480093f4SDimitry Andric   // After collecting a block of DBG_VALUEs into ToInsert, enter them into the
3799480093f4SDimitry Andric   // vreg => DbgValueLoc map.
3800480093f4SDimitry Andric   auto CloseNewDVRange = [this, &ToInsert](SlotIndex Slot) {
3801fe6060f1SDimitry Andric     for (auto *X : ToInsert) {
3802349cc55cSDimitry Andric       for (const auto &Op : X->debug_operands()) {
3803fe6060f1SDimitry Andric         if (Op.isReg() && Op.getReg().isVirtual())
3804fe6060f1SDimitry Andric           DbgVRegToValues[Op.getReg()].push_back({Slot, X});
3805fe6060f1SDimitry Andric       }
3806fe6060f1SDimitry Andric     }
3807480093f4SDimitry Andric 
3808480093f4SDimitry Andric     ToInsert.clear();
3809480093f4SDimitry Andric   };
3810480093f4SDimitry Andric 
3811480093f4SDimitry Andric   // Iterate over all instructions, collecting them into the ToInsert vector.
3812480093f4SDimitry Andric   // Once a non-debug instruction is found, record the slot index of the
3813480093f4SDimitry Andric   // collected DBG_VALUEs.
3814480093f4SDimitry Andric   for (auto &MBB : MF) {
3815480093f4SDimitry Andric     SlotIndex CurrentSlot = Slots.getMBBStartIdx(&MBB);
3816480093f4SDimitry Andric 
3817480093f4SDimitry Andric     for (auto &MI : MBB) {
3818fe6060f1SDimitry Andric       if (MI.isDebugValue()) {
3819fe6060f1SDimitry Andric         if (any_of(MI.debug_operands(), [](const MachineOperand &MO) {
3820fe6060f1SDimitry Andric               return MO.isReg() && MO.getReg().isVirtual();
3821fe6060f1SDimitry Andric             }))
3822480093f4SDimitry Andric           ToInsert.push_back(&MI);
3823fe6060f1SDimitry Andric       } else if (!MI.isDebugOrPseudoInstr()) {
3824480093f4SDimitry Andric         CurrentSlot = Slots.getInstructionIndex(MI);
3825480093f4SDimitry Andric         CloseNewDVRange(CurrentSlot);
3826480093f4SDimitry Andric       }
3827480093f4SDimitry Andric     }
3828480093f4SDimitry Andric 
3829480093f4SDimitry Andric     // Close range of DBG_VALUEs at the end of blocks.
3830480093f4SDimitry Andric     CloseNewDVRange(Slots.getMBBEndIdx(&MBB));
3831480093f4SDimitry Andric   }
3832480093f4SDimitry Andric 
3833480093f4SDimitry Andric   // Sort all DBG_VALUEs we've seen by slot number.
3834480093f4SDimitry Andric   for (auto &Pair : DbgVRegToValues)
3835480093f4SDimitry Andric     llvm::sort(Pair.second);
3836480093f4SDimitry Andric }
3837480093f4SDimitry Andric 
3838480093f4SDimitry Andric void RegisterCoalescer::checkMergingChangesDbgValues(CoalescerPair &CP,
3839480093f4SDimitry Andric                                                      LiveRange &LHS,
3840480093f4SDimitry Andric                                                      JoinVals &LHSVals,
3841480093f4SDimitry Andric                                                      LiveRange &RHS,
3842480093f4SDimitry Andric                                                      JoinVals &RHSVals) {
3843e8d8bef9SDimitry Andric   auto ScanForDstReg = [&](Register Reg) {
3844480093f4SDimitry Andric     checkMergingChangesDbgValuesImpl(Reg, RHS, LHS, LHSVals);
3845480093f4SDimitry Andric   };
3846480093f4SDimitry Andric 
3847e8d8bef9SDimitry Andric   auto ScanForSrcReg = [&](Register Reg) {
3848480093f4SDimitry Andric     checkMergingChangesDbgValuesImpl(Reg, LHS, RHS, RHSVals);
3849480093f4SDimitry Andric   };
3850480093f4SDimitry Andric 
3851480093f4SDimitry Andric   // Scan for unsound updates of both the source and destination register.
385206c3fb27SDimitry Andric   ScanForSrcReg(CP.getSrcReg());
385306c3fb27SDimitry Andric   ScanForDstReg(CP.getDstReg());
3854480093f4SDimitry Andric }
3855480093f4SDimitry Andric 
3856e8d8bef9SDimitry Andric void RegisterCoalescer::checkMergingChangesDbgValuesImpl(Register Reg,
3857480093f4SDimitry Andric                                                          LiveRange &OtherLR,
3858480093f4SDimitry Andric                                                          LiveRange &RegLR,
3859480093f4SDimitry Andric                                                          JoinVals &RegVals) {
3860480093f4SDimitry Andric   // Are there any DBG_VALUEs to examine?
3861480093f4SDimitry Andric   auto VRegMapIt = DbgVRegToValues.find(Reg);
3862480093f4SDimitry Andric   if (VRegMapIt == DbgVRegToValues.end())
3863480093f4SDimitry Andric     return;
3864480093f4SDimitry Andric 
3865480093f4SDimitry Andric   auto &DbgValueSet = VRegMapIt->second;
3866480093f4SDimitry Andric   auto DbgValueSetIt = DbgValueSet.begin();
3867480093f4SDimitry Andric   auto SegmentIt = OtherLR.begin();
3868480093f4SDimitry Andric 
3869480093f4SDimitry Andric   bool LastUndefResult = false;
3870480093f4SDimitry Andric   SlotIndex LastUndefIdx;
3871480093f4SDimitry Andric 
3872480093f4SDimitry Andric   // If the "Other" register is live at a slot Idx, test whether Reg can
3873480093f4SDimitry Andric   // safely be merged with it, or should be marked undef.
3874480093f4SDimitry Andric   auto ShouldUndef = [&RegVals, &RegLR, &LastUndefResult,
3875480093f4SDimitry Andric                       &LastUndefIdx](SlotIndex Idx) -> bool {
3876480093f4SDimitry Andric     // Our worst-case performance typically happens with asan, causing very
3877480093f4SDimitry Andric     // many DBG_VALUEs of the same location. Cache a copy of the most recent
3878480093f4SDimitry Andric     // result for this edge-case.
3879480093f4SDimitry Andric     if (LastUndefIdx == Idx)
3880480093f4SDimitry Andric       return LastUndefResult;
3881480093f4SDimitry Andric 
3882480093f4SDimitry Andric     // If the other range was live, and Reg's was not, the register coalescer
3883480093f4SDimitry Andric     // will not have tried to resolve any conflicts. We don't know whether
3884480093f4SDimitry Andric     // the DBG_VALUE will refer to the same value number, so it must be made
3885480093f4SDimitry Andric     // undef.
3886480093f4SDimitry Andric     auto OtherIt = RegLR.find(Idx);
3887480093f4SDimitry Andric     if (OtherIt == RegLR.end())
3888480093f4SDimitry Andric       return true;
3889480093f4SDimitry Andric 
3890480093f4SDimitry Andric     // Both the registers were live: examine the conflict resolution record for
3891480093f4SDimitry Andric     // the value number Reg refers to. CR_Keep meant that this value number
3892480093f4SDimitry Andric     // "won" and the merged register definitely refers to that value. CR_Erase
3893480093f4SDimitry Andric     // means the value number was a redundant copy of the other value, which
3894480093f4SDimitry Andric     // was coalesced and Reg deleted. It's safe to refer to the other register
3895480093f4SDimitry Andric     // (which will be the source of the copy).
3896480093f4SDimitry Andric     auto Resolution = RegVals.getResolution(OtherIt->valno->id);
3897480093f4SDimitry Andric     LastUndefResult = Resolution != JoinVals::CR_Keep &&
3898480093f4SDimitry Andric                       Resolution != JoinVals::CR_Erase;
3899480093f4SDimitry Andric     LastUndefIdx = Idx;
3900480093f4SDimitry Andric     return LastUndefResult;
3901480093f4SDimitry Andric   };
3902480093f4SDimitry Andric 
3903480093f4SDimitry Andric   // Iterate over both the live-range of the "Other" register, and the set of
3904480093f4SDimitry Andric   // DBG_VALUEs for Reg at the same time. Advance whichever one has the lowest
3905480093f4SDimitry Andric   // slot index. This relies on the DbgValueSet being ordered.
3906480093f4SDimitry Andric   while (DbgValueSetIt != DbgValueSet.end() && SegmentIt != OtherLR.end()) {
3907480093f4SDimitry Andric     if (DbgValueSetIt->first < SegmentIt->end) {
3908480093f4SDimitry Andric       // "Other" is live and there is a DBG_VALUE of Reg: test if we should
3909480093f4SDimitry Andric       // set it undef.
3910fe6060f1SDimitry Andric       if (DbgValueSetIt->first >= SegmentIt->start) {
3911fe6060f1SDimitry Andric         bool HasReg = DbgValueSetIt->second->hasDebugOperandForReg(Reg);
3912fe6060f1SDimitry Andric         bool ShouldUndefReg = ShouldUndef(DbgValueSetIt->first);
3913fe6060f1SDimitry Andric         if (HasReg && ShouldUndefReg) {
3914480093f4SDimitry Andric           // Mark undef, erase record of this DBG_VALUE to avoid revisiting.
39155ffd83dbSDimitry Andric           DbgValueSetIt->second->setDebugValueUndef();
3916480093f4SDimitry Andric           continue;
3917480093f4SDimitry Andric         }
3918fe6060f1SDimitry Andric       }
3919480093f4SDimitry Andric       ++DbgValueSetIt;
3920480093f4SDimitry Andric     } else {
3921480093f4SDimitry Andric       ++SegmentIt;
3922480093f4SDimitry Andric     }
3923480093f4SDimitry Andric   }
3924480093f4SDimitry Andric }
3925480093f4SDimitry Andric 
39260b57cec5SDimitry Andric namespace {
39270b57cec5SDimitry Andric 
39280b57cec5SDimitry Andric /// Information concerning MBB coalescing priority.
39290b57cec5SDimitry Andric struct MBBPriorityInfo {
39300b57cec5SDimitry Andric   MachineBasicBlock *MBB;
39310b57cec5SDimitry Andric   unsigned Depth;
39320b57cec5SDimitry Andric   bool IsSplit;
39330b57cec5SDimitry Andric 
39340b57cec5SDimitry Andric   MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
39350b57cec5SDimitry Andric     : MBB(mbb), Depth(depth), IsSplit(issplit) {}
39360b57cec5SDimitry Andric };
39370b57cec5SDimitry Andric 
39380b57cec5SDimitry Andric } // end anonymous namespace
39390b57cec5SDimitry Andric 
39400b57cec5SDimitry Andric /// C-style comparator that sorts first based on the loop depth of the basic
39410b57cec5SDimitry Andric /// block (the unsigned), and then on the MBB number.
39420b57cec5SDimitry Andric ///
39430b57cec5SDimitry Andric /// EnableGlobalCopies assumes that the primary sort key is loop depth.
39440b57cec5SDimitry Andric static int compareMBBPriority(const MBBPriorityInfo *LHS,
39450b57cec5SDimitry Andric                               const MBBPriorityInfo *RHS) {
39460b57cec5SDimitry Andric   // Deeper loops first
39470b57cec5SDimitry Andric   if (LHS->Depth != RHS->Depth)
39480b57cec5SDimitry Andric     return LHS->Depth > RHS->Depth ? -1 : 1;
39490b57cec5SDimitry Andric 
39500b57cec5SDimitry Andric   // Try to unsplit critical edges next.
39510b57cec5SDimitry Andric   if (LHS->IsSplit != RHS->IsSplit)
39520b57cec5SDimitry Andric     return LHS->IsSplit ? -1 : 1;
39530b57cec5SDimitry Andric 
39540b57cec5SDimitry Andric   // Prefer blocks that are more connected in the CFG. This takes care of
39550b57cec5SDimitry Andric   // the most difficult copies first while intervals are short.
39560b57cec5SDimitry Andric   unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
39570b57cec5SDimitry Andric   unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
39580b57cec5SDimitry Andric   if (cl != cr)
39590b57cec5SDimitry Andric     return cl > cr ? -1 : 1;
39600b57cec5SDimitry Andric 
39610b57cec5SDimitry Andric   // As a last resort, sort by block number.
39620b57cec5SDimitry Andric   return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
39630b57cec5SDimitry Andric }
39640b57cec5SDimitry Andric 
39650b57cec5SDimitry Andric /// \returns true if the given copy uses or defines a local live range.
39660b57cec5SDimitry Andric static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
39670b57cec5SDimitry Andric   if (!Copy->isCopy())
39680b57cec5SDimitry Andric     return false;
39690b57cec5SDimitry Andric 
39700b57cec5SDimitry Andric   if (Copy->getOperand(1).isUndef())
39710b57cec5SDimitry Andric     return false;
39720b57cec5SDimitry Andric 
39738bcb0991SDimitry Andric   Register SrcReg = Copy->getOperand(1).getReg();
39748bcb0991SDimitry Andric   Register DstReg = Copy->getOperand(0).getReg();
3975bdd1243dSDimitry Andric   if (SrcReg.isPhysical() || DstReg.isPhysical())
39760b57cec5SDimitry Andric     return false;
39770b57cec5SDimitry Andric 
39780b57cec5SDimitry Andric   return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
39790b57cec5SDimitry Andric     || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
39800b57cec5SDimitry Andric }
39810b57cec5SDimitry Andric 
39820b57cec5SDimitry Andric void RegisterCoalescer::lateLiveIntervalUpdate() {
3983e8d8bef9SDimitry Andric   for (Register reg : ToBeUpdated) {
39840b57cec5SDimitry Andric     if (!LIS->hasInterval(reg))
39850b57cec5SDimitry Andric       continue;
39860b57cec5SDimitry Andric     LiveInterval &LI = LIS->getInterval(reg);
39870b57cec5SDimitry Andric     shrinkToUses(&LI, &DeadDefs);
39880b57cec5SDimitry Andric     if (!DeadDefs.empty())
39890b57cec5SDimitry Andric       eliminateDeadDefs();
39900b57cec5SDimitry Andric   }
39910b57cec5SDimitry Andric   ToBeUpdated.clear();
39920b57cec5SDimitry Andric }
39930b57cec5SDimitry Andric 
39940b57cec5SDimitry Andric bool RegisterCoalescer::
39950b57cec5SDimitry Andric copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
39960b57cec5SDimitry Andric   bool Progress = false;
399774626c16SDimitry Andric   SmallPtrSet<MachineInstr *, 4> CurrentErasedInstrs;
39984824e7fdSDimitry Andric   for (MachineInstr *&MI : CurrList) {
39994824e7fdSDimitry Andric     if (!MI)
40000b57cec5SDimitry Andric       continue;
40010b57cec5SDimitry Andric     // Skip instruction pointers that have already been erased, for example by
40020b57cec5SDimitry Andric     // dead code elimination.
400374626c16SDimitry Andric     if (ErasedInstrs.count(MI) || CurrentErasedInstrs.count(MI)) {
40044824e7fdSDimitry Andric       MI = nullptr;
40050b57cec5SDimitry Andric       continue;
40060b57cec5SDimitry Andric     }
40070b57cec5SDimitry Andric     bool Again = false;
400874626c16SDimitry Andric     bool Success = joinCopy(MI, Again, CurrentErasedInstrs);
40090b57cec5SDimitry Andric     Progress |= Success;
40100b57cec5SDimitry Andric     if (Success || !Again)
40114824e7fdSDimitry Andric       MI = nullptr;
40120b57cec5SDimitry Andric   }
401374626c16SDimitry Andric   // Clear instructions not recorded in `ErasedInstrs` but erased.
401474626c16SDimitry Andric   if (!CurrentErasedInstrs.empty()) {
401574626c16SDimitry Andric     for (MachineInstr *&MI : CurrList) {
401674626c16SDimitry Andric       if (MI && CurrentErasedInstrs.count(MI))
401774626c16SDimitry Andric         MI = nullptr;
401874626c16SDimitry Andric     }
401974626c16SDimitry Andric     for (MachineInstr *&MI : WorkList) {
402074626c16SDimitry Andric       if (MI && CurrentErasedInstrs.count(MI))
402174626c16SDimitry Andric         MI = nullptr;
402274626c16SDimitry Andric     }
402374626c16SDimitry Andric   }
40240b57cec5SDimitry Andric   return Progress;
40250b57cec5SDimitry Andric }
40260b57cec5SDimitry Andric 
40270b57cec5SDimitry Andric /// Check if DstReg is a terminal node.
40280b57cec5SDimitry Andric /// I.e., it does not have any affinity other than \p Copy.
4029e8d8bef9SDimitry Andric static bool isTerminalReg(Register DstReg, const MachineInstr &Copy,
40300b57cec5SDimitry Andric                           const MachineRegisterInfo *MRI) {
40310b57cec5SDimitry Andric   assert(Copy.isCopyLike());
40320b57cec5SDimitry Andric   // Check if the destination of this copy as any other affinity.
40330b57cec5SDimitry Andric   for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg))
40340b57cec5SDimitry Andric     if (&MI != &Copy && MI.isCopyLike())
40350b57cec5SDimitry Andric       return false;
40360b57cec5SDimitry Andric   return true;
40370b57cec5SDimitry Andric }
40380b57cec5SDimitry Andric 
40390b57cec5SDimitry Andric bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const {
40400b57cec5SDimitry Andric   assert(Copy.isCopyLike());
40410b57cec5SDimitry Andric   if (!UseTerminalRule)
40420b57cec5SDimitry Andric     return false;
4043e8d8bef9SDimitry Andric   Register SrcReg, DstReg;
4044e8d8bef9SDimitry Andric   unsigned SrcSubReg = 0, DstSubReg = 0;
40450b57cec5SDimitry Andric   if (!isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg))
40460b57cec5SDimitry Andric     return false;
40470b57cec5SDimitry Andric   // Check if the destination of this copy has any other affinity.
4048e8d8bef9SDimitry Andric   if (DstReg.isPhysical() ||
40490b57cec5SDimitry Andric       // If SrcReg is a physical register, the copy won't be coalesced.
40500b57cec5SDimitry Andric       // Ignoring it may have other side effect (like missing
40510b57cec5SDimitry Andric       // rematerialization). So keep it.
4052e8d8bef9SDimitry Andric       SrcReg.isPhysical() || !isTerminalReg(DstReg, Copy, MRI))
40530b57cec5SDimitry Andric     return false;
40540b57cec5SDimitry Andric 
40550b57cec5SDimitry Andric   // DstReg is a terminal node. Check if it interferes with any other
40560b57cec5SDimitry Andric   // copy involving SrcReg.
40570b57cec5SDimitry Andric   const MachineBasicBlock *OrigBB = Copy.getParent();
40580b57cec5SDimitry Andric   const LiveInterval &DstLI = LIS->getInterval(DstReg);
40590b57cec5SDimitry Andric   for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) {
40600b57cec5SDimitry Andric     // Technically we should check if the weight of the new copy is
40610b57cec5SDimitry Andric     // interesting compared to the other one and update the weight
40620b57cec5SDimitry Andric     // of the copies accordingly. However, this would only work if
40630b57cec5SDimitry Andric     // we would gather all the copies first then coalesce, whereas
40640b57cec5SDimitry Andric     // right now we interleave both actions.
40650b57cec5SDimitry Andric     // For now, just consider the copies that are in the same block.
40660b57cec5SDimitry Andric     if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB)
40670b57cec5SDimitry Andric       continue;
4068e8d8bef9SDimitry Andric     Register OtherSrcReg, OtherReg;
4069e8d8bef9SDimitry Andric     unsigned OtherSrcSubReg = 0, OtherSubReg = 0;
40700b57cec5SDimitry Andric     if (!isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg,
40710b57cec5SDimitry Andric                 OtherSubReg))
40720b57cec5SDimitry Andric       return false;
40730b57cec5SDimitry Andric     if (OtherReg == SrcReg)
40740b57cec5SDimitry Andric       OtherReg = OtherSrcReg;
40750b57cec5SDimitry Andric     // Check if OtherReg is a non-terminal.
4076bdd1243dSDimitry Andric     if (OtherReg.isPhysical() || isTerminalReg(OtherReg, MI, MRI))
40770b57cec5SDimitry Andric       continue;
40780b57cec5SDimitry Andric     // Check that OtherReg interfere with DstReg.
40790b57cec5SDimitry Andric     if (LIS->getInterval(OtherReg).overlaps(DstLI)) {
40800b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Apply terminal rule for: " << printReg(DstReg)
40810b57cec5SDimitry Andric                         << '\n');
40820b57cec5SDimitry Andric       return true;
40830b57cec5SDimitry Andric     }
40840b57cec5SDimitry Andric   }
40850b57cec5SDimitry Andric   return false;
40860b57cec5SDimitry Andric }
40870b57cec5SDimitry Andric 
40880b57cec5SDimitry Andric void
40890b57cec5SDimitry Andric RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
40900b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << MBB->getName() << ":\n");
40910b57cec5SDimitry Andric 
40920b57cec5SDimitry Andric   // Collect all copy-like instructions in MBB. Don't start coalescing anything
40930b57cec5SDimitry Andric   // yet, it might invalidate the iterator.
40940b57cec5SDimitry Andric   const unsigned PrevSize = WorkList.size();
40950b57cec5SDimitry Andric   if (JoinGlobalCopies) {
40960b57cec5SDimitry Andric     SmallVector<MachineInstr*, 2> LocalTerminals;
40970b57cec5SDimitry Andric     SmallVector<MachineInstr*, 2> GlobalTerminals;
40980b57cec5SDimitry Andric     // Coalesce copies bottom-up to coalesce local defs before local uses. They
40990b57cec5SDimitry Andric     // are not inherently easier to resolve, but slightly preferable until we
41000b57cec5SDimitry Andric     // have local live range splitting. In particular this is required by
41010b57cec5SDimitry Andric     // cmp+jmp macro fusion.
4102fe6060f1SDimitry Andric     for (MachineInstr &MI : *MBB) {
4103fe6060f1SDimitry Andric       if (!MI.isCopyLike())
41040b57cec5SDimitry Andric         continue;
4105fe6060f1SDimitry Andric       bool ApplyTerminalRule = applyTerminalRule(MI);
4106fe6060f1SDimitry Andric       if (isLocalCopy(&MI, LIS)) {
41070b57cec5SDimitry Andric         if (ApplyTerminalRule)
4108fe6060f1SDimitry Andric           LocalTerminals.push_back(&MI);
41090b57cec5SDimitry Andric         else
4110fe6060f1SDimitry Andric           LocalWorkList.push_back(&MI);
41110b57cec5SDimitry Andric       } else {
41120b57cec5SDimitry Andric         if (ApplyTerminalRule)
4113fe6060f1SDimitry Andric           GlobalTerminals.push_back(&MI);
41140b57cec5SDimitry Andric         else
4115fe6060f1SDimitry Andric           WorkList.push_back(&MI);
41160b57cec5SDimitry Andric       }
41170b57cec5SDimitry Andric     }
41180b57cec5SDimitry Andric     // Append the copies evicted by the terminal rule at the end of the list.
41190b57cec5SDimitry Andric     LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end());
41200b57cec5SDimitry Andric     WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end());
41210b57cec5SDimitry Andric   }
41220b57cec5SDimitry Andric   else {
41230b57cec5SDimitry Andric     SmallVector<MachineInstr*, 2> Terminals;
41240b57cec5SDimitry Andric     for (MachineInstr &MII : *MBB)
41250b57cec5SDimitry Andric       if (MII.isCopyLike()) {
41260b57cec5SDimitry Andric         if (applyTerminalRule(MII))
41270b57cec5SDimitry Andric           Terminals.push_back(&MII);
41280b57cec5SDimitry Andric         else
41290b57cec5SDimitry Andric           WorkList.push_back(&MII);
41300b57cec5SDimitry Andric       }
41310b57cec5SDimitry Andric     // Append the copies evicted by the terminal rule at the end of the list.
41320b57cec5SDimitry Andric     WorkList.append(Terminals.begin(), Terminals.end());
41330b57cec5SDimitry Andric   }
41340b57cec5SDimitry Andric   // Try coalescing the collected copies immediately, and remove the nulls.
41350b57cec5SDimitry Andric   // This prevents the WorkList from getting too large since most copies are
41360b57cec5SDimitry Andric   // joinable on the first attempt.
41370b57cec5SDimitry Andric   MutableArrayRef<MachineInstr*>
41380b57cec5SDimitry Andric     CurrList(WorkList.begin() + PrevSize, WorkList.end());
41390b57cec5SDimitry Andric   if (copyCoalesceWorkList(CurrList))
41400b57cec5SDimitry Andric     WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
41410b57cec5SDimitry Andric                                nullptr), WorkList.end());
41420b57cec5SDimitry Andric }
41430b57cec5SDimitry Andric 
41440b57cec5SDimitry Andric void RegisterCoalescer::coalesceLocals() {
41450b57cec5SDimitry Andric   copyCoalesceWorkList(LocalWorkList);
41460fca6ea1SDimitry Andric   for (MachineInstr *MI : LocalWorkList) {
41470fca6ea1SDimitry Andric     if (MI)
41480fca6ea1SDimitry Andric       WorkList.push_back(MI);
41490b57cec5SDimitry Andric   }
41500b57cec5SDimitry Andric   LocalWorkList.clear();
41510b57cec5SDimitry Andric }
41520b57cec5SDimitry Andric 
41530b57cec5SDimitry Andric void RegisterCoalescer::joinAllIntervals() {
41540b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
41550b57cec5SDimitry Andric   assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
41560b57cec5SDimitry Andric 
41570b57cec5SDimitry Andric   std::vector<MBBPriorityInfo> MBBs;
41580b57cec5SDimitry Andric   MBBs.reserve(MF->size());
4159fe6060f1SDimitry Andric   for (MachineBasicBlock &MBB : *MF) {
4160fe6060f1SDimitry Andric     MBBs.push_back(MBBPriorityInfo(&MBB, Loops->getLoopDepth(&MBB),
4161fe6060f1SDimitry Andric                                    JoinSplitEdges && isSplitEdge(&MBB)));
41620b57cec5SDimitry Andric   }
41630b57cec5SDimitry Andric   array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
41640b57cec5SDimitry Andric 
41650b57cec5SDimitry Andric   // Coalesce intervals in MBB priority order.
41660b57cec5SDimitry Andric   unsigned CurrDepth = std::numeric_limits<unsigned>::max();
41670eae32dcSDimitry Andric   for (MBBPriorityInfo &MBB : MBBs) {
41680b57cec5SDimitry Andric     // Try coalescing the collected local copies for deeper loops.
41690eae32dcSDimitry Andric     if (JoinGlobalCopies && MBB.Depth < CurrDepth) {
41700b57cec5SDimitry Andric       coalesceLocals();
41710eae32dcSDimitry Andric       CurrDepth = MBB.Depth;
41720b57cec5SDimitry Andric     }
41730eae32dcSDimitry Andric     copyCoalesceInMBB(MBB.MBB);
41740b57cec5SDimitry Andric   }
41750b57cec5SDimitry Andric   lateLiveIntervalUpdate();
41760b57cec5SDimitry Andric   coalesceLocals();
41770b57cec5SDimitry Andric 
41780b57cec5SDimitry Andric   // Joining intervals can allow other intervals to be joined.  Iteratively join
41790b57cec5SDimitry Andric   // until we make no progress.
41800b57cec5SDimitry Andric   while (copyCoalesceWorkList(WorkList))
41810b57cec5SDimitry Andric     /* empty */ ;
41820b57cec5SDimitry Andric   lateLiveIntervalUpdate();
41830b57cec5SDimitry Andric }
41840b57cec5SDimitry Andric 
41850b57cec5SDimitry Andric void RegisterCoalescer::releaseMemory() {
41860b57cec5SDimitry Andric   ErasedInstrs.clear();
41870b57cec5SDimitry Andric   WorkList.clear();
41880b57cec5SDimitry Andric   DeadDefs.clear();
41890b57cec5SDimitry Andric   InflateRegs.clear();
41900b57cec5SDimitry Andric   LargeLIVisitCounter.clear();
41910b57cec5SDimitry Andric }
41920b57cec5SDimitry Andric 
41930b57cec5SDimitry Andric bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
419406c3fb27SDimitry Andric   LLVM_DEBUG(dbgs() << "********** REGISTER COALESCER **********\n"
41955ffd83dbSDimitry Andric                     << "********** Function: " << fn.getName() << '\n');
41965ffd83dbSDimitry Andric 
41975ffd83dbSDimitry Andric   // Variables changed between a setjmp and a longjump can have undefined value
41985ffd83dbSDimitry Andric   // after the longjmp. This behaviour can be observed if such a variable is
41995ffd83dbSDimitry Andric   // spilled, so longjmp won't restore the value in the spill slot.
42005ffd83dbSDimitry Andric   // RegisterCoalescer should not run in functions with a setjmp to avoid
42015ffd83dbSDimitry Andric   // merging such undefined variables with predictable ones.
42025ffd83dbSDimitry Andric   //
42035ffd83dbSDimitry Andric   // TODO: Could specifically disable coalescing registers live across setjmp
42045ffd83dbSDimitry Andric   // calls
42055ffd83dbSDimitry Andric   if (fn.exposesReturnsTwice()) {
42065ffd83dbSDimitry Andric     LLVM_DEBUG(
4207bdd1243dSDimitry Andric         dbgs() << "* Skipped as it exposes functions that returns twice.\n");
42085ffd83dbSDimitry Andric     return false;
42095ffd83dbSDimitry Andric   }
42105ffd83dbSDimitry Andric 
42110b57cec5SDimitry Andric   MF = &fn;
42120b57cec5SDimitry Andric   MRI = &fn.getRegInfo();
42130b57cec5SDimitry Andric   const TargetSubtargetInfo &STI = fn.getSubtarget();
42140b57cec5SDimitry Andric   TRI = STI.getRegisterInfo();
42150b57cec5SDimitry Andric   TII = STI.getInstrInfo();
42160fca6ea1SDimitry Andric   LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
42170b57cec5SDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
42180fca6ea1SDimitry Andric   Loops = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
42190b57cec5SDimitry Andric   if (EnableGlobalCopies == cl::BOU_UNSET)
42200b57cec5SDimitry Andric     JoinGlobalCopies = STI.enableJoinGlobalCopies();
42210b57cec5SDimitry Andric   else
42220b57cec5SDimitry Andric     JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
42230b57cec5SDimitry Andric 
4224fe6060f1SDimitry Andric   // If there are PHIs tracked by debug-info, they will need updating during
4225fe6060f1SDimitry Andric   // coalescing. Build an index of those PHIs to ease updating.
4226fe6060f1SDimitry Andric   SlotIndexes *Slots = LIS->getSlotIndexes();
4227fe6060f1SDimitry Andric   for (const auto &DebugPHI : MF->DebugPHIPositions) {
4228fe6060f1SDimitry Andric     MachineBasicBlock *MBB = DebugPHI.second.MBB;
4229fe6060f1SDimitry Andric     Register Reg = DebugPHI.second.Reg;
4230fe6060f1SDimitry Andric     unsigned SubReg = DebugPHI.second.SubReg;
4231fe6060f1SDimitry Andric     SlotIndex SI = Slots->getMBBStartIdx(MBB);
4232fe6060f1SDimitry Andric     PHIValPos P = {SI, Reg, SubReg};
4233fe6060f1SDimitry Andric     PHIValToPos.insert(std::make_pair(DebugPHI.first, P));
4234fe6060f1SDimitry Andric     RegToPHIIdx[Reg].push_back(DebugPHI.first);
4235fe6060f1SDimitry Andric   }
4236fe6060f1SDimitry Andric 
42370b57cec5SDimitry Andric   // The MachineScheduler does not currently require JoinSplitEdges. This will
42380b57cec5SDimitry Andric   // either be enabled unconditionally or replaced by a more general live range
42390b57cec5SDimitry Andric   // splitting optimization.
42400b57cec5SDimitry Andric   JoinSplitEdges = EnableJoinSplits;
42410b57cec5SDimitry Andric 
42420b57cec5SDimitry Andric   if (VerifyCoalescing)
42430b57cec5SDimitry Andric     MF->verify(this, "Before register coalescing");
42440b57cec5SDimitry Andric 
4245480093f4SDimitry Andric   DbgVRegToValues.clear();
4246480093f4SDimitry Andric   buildVRegToDbgValueMap(fn);
4247480093f4SDimitry Andric 
42480b57cec5SDimitry Andric   RegClassInfo.runOnMachineFunction(fn);
42490b57cec5SDimitry Andric 
42500b57cec5SDimitry Andric   // Join (coalesce) intervals if requested.
42510b57cec5SDimitry Andric   if (EnableJoining)
42520b57cec5SDimitry Andric     joinAllIntervals();
42530b57cec5SDimitry Andric 
42540b57cec5SDimitry Andric   // After deleting a lot of copies, register classes may be less constrained.
42550b57cec5SDimitry Andric   // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
42560b57cec5SDimitry Andric   // DPR inflation.
42570b57cec5SDimitry Andric   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
42580fca6ea1SDimitry Andric   InflateRegs.erase(llvm::unique(InflateRegs), InflateRegs.end());
42590b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size()
42600b57cec5SDimitry Andric                     << " regs.\n");
4261cb14a3feSDimitry Andric   for (Register Reg : InflateRegs) {
42620b57cec5SDimitry Andric     if (MRI->reg_nodbg_empty(Reg))
42630b57cec5SDimitry Andric       continue;
42640b57cec5SDimitry Andric     if (MRI->recomputeRegClass(Reg)) {
42650b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << printReg(Reg) << " inflated to "
42660b57cec5SDimitry Andric                         << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
42670b57cec5SDimitry Andric       ++NumInflated;
42680b57cec5SDimitry Andric 
42690b57cec5SDimitry Andric       LiveInterval &LI = LIS->getInterval(Reg);
42700b57cec5SDimitry Andric       if (LI.hasSubRanges()) {
42710b57cec5SDimitry Andric         // If the inflated register class does not support subregisters anymore
42720b57cec5SDimitry Andric         // remove the subranges.
42730b57cec5SDimitry Andric         if (!MRI->shouldTrackSubRegLiveness(Reg)) {
42740b57cec5SDimitry Andric           LI.clearSubRanges();
42750b57cec5SDimitry Andric         } else {
42760b57cec5SDimitry Andric #ifndef NDEBUG
42770b57cec5SDimitry Andric           LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
42780b57cec5SDimitry Andric           // If subranges are still supported, then the same subregs
42790b57cec5SDimitry Andric           // should still be supported.
42800b57cec5SDimitry Andric           for (LiveInterval::SubRange &S : LI.subranges()) {
42810b57cec5SDimitry Andric             assert((S.LaneMask & ~MaxMask).none());
42820b57cec5SDimitry Andric           }
42830b57cec5SDimitry Andric #endif
42840b57cec5SDimitry Andric         }
42850b57cec5SDimitry Andric       }
42860b57cec5SDimitry Andric     }
42870b57cec5SDimitry Andric   }
42880b57cec5SDimitry Andric 
4289fe6060f1SDimitry Andric   // After coalescing, update any PHIs that are being tracked by debug-info
4290fe6060f1SDimitry Andric   // with their new VReg locations.
4291fe6060f1SDimitry Andric   for (auto &p : MF->DebugPHIPositions) {
4292fe6060f1SDimitry Andric     auto it = PHIValToPos.find(p.first);
4293fe6060f1SDimitry Andric     assert(it != PHIValToPos.end());
4294fe6060f1SDimitry Andric     p.second.Reg = it->second.Reg;
4295fe6060f1SDimitry Andric     p.second.SubReg = it->second.SubReg;
4296fe6060f1SDimitry Andric   }
4297fe6060f1SDimitry Andric 
4298fe6060f1SDimitry Andric   PHIValToPos.clear();
4299fe6060f1SDimitry Andric   RegToPHIIdx.clear();
4300fe6060f1SDimitry Andric 
43010b57cec5SDimitry Andric   LLVM_DEBUG(dump());
43020b57cec5SDimitry Andric   if (VerifyCoalescing)
43030b57cec5SDimitry Andric     MF->verify(this, "After register coalescing");
43040b57cec5SDimitry Andric   return true;
43050b57cec5SDimitry Andric }
43060b57cec5SDimitry Andric 
43070b57cec5SDimitry Andric void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
43080fca6ea1SDimitry Andric   LIS->print(O);
43090b57cec5SDimitry Andric }
4310