xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/MachineCopyPropagation.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
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 is an extremely simple MachineInstr-level copy propagation pass.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric // This pass forwards the source of COPYs to the users of their destinations
120b57cec5SDimitry Andric // when doing so is legal.  For example:
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric //   %reg1 = COPY %reg0
150b57cec5SDimitry Andric //   ...
160b57cec5SDimitry Andric //   ... = OP %reg1
170b57cec5SDimitry Andric //
180b57cec5SDimitry Andric // If
190b57cec5SDimitry Andric //   - %reg0 has not been clobbered by the time of the use of %reg1
200b57cec5SDimitry Andric //   - the register class constraints are satisfied
210b57cec5SDimitry Andric //   - the COPY def is the only value that reaches OP
220b57cec5SDimitry Andric // then this pass replaces the above with:
230b57cec5SDimitry Andric //
240b57cec5SDimitry Andric //   %reg1 = COPY %reg0
250b57cec5SDimitry Andric //   ...
260b57cec5SDimitry Andric //   ... = OP %reg0
270b57cec5SDimitry Andric //
280b57cec5SDimitry Andric // This pass also removes some redundant COPYs.  For example:
290b57cec5SDimitry Andric //
300b57cec5SDimitry Andric //    %R1 = COPY %R0
310b57cec5SDimitry Andric //    ... // No clobber of %R1
320b57cec5SDimitry Andric //    %R0 = COPY %R1 <<< Removed
330b57cec5SDimitry Andric //
340b57cec5SDimitry Andric // or
350b57cec5SDimitry Andric //
360b57cec5SDimitry Andric //    %R1 = COPY %R0
370b57cec5SDimitry Andric //    ... // No clobber of %R0
380b57cec5SDimitry Andric //    %R1 = COPY %R0 <<< Removed
390b57cec5SDimitry Andric //
40480093f4SDimitry Andric // or
41480093f4SDimitry Andric //
42480093f4SDimitry Andric //    $R0 = OP ...
43480093f4SDimitry Andric //    ... // No read/clobber of $R0 and $R1
44480093f4SDimitry Andric //    $R1 = COPY $R0 // $R0 is killed
45480093f4SDimitry Andric // Replace $R0 with $R1 and remove the COPY
46480093f4SDimitry Andric //    $R1 = OP ...
47480093f4SDimitry Andric //    ...
48480093f4SDimitry Andric //
490b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
520b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
530b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
545ffd83dbSDimitry Andric #include "llvm/ADT/SmallSet.h"
550b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
560b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
570b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
580b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
590b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
600b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
610b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
620b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
630b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
640b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
650b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
660b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
67480093f4SDimitry Andric #include "llvm/InitializePasses.h"
68*0fca6ea1SDimitry Andric #include "llvm/MC/MCRegister.h"
690b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
700b57cec5SDimitry Andric #include "llvm/Pass.h"
710b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
720b57cec5SDimitry Andric #include "llvm/Support/DebugCounter.h"
730b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
740b57cec5SDimitry Andric #include <cassert>
750b57cec5SDimitry Andric #include <iterator>
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric using namespace llvm;
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric #define DEBUG_TYPE "machine-cp"
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric STATISTIC(NumDeletes, "Number of dead copies deleted");
820b57cec5SDimitry Andric STATISTIC(NumCopyForwards, "Number of copy uses forwarded");
83480093f4SDimitry Andric STATISTIC(NumCopyBackwardPropagated, "Number of copy defs backward propagated");
8406c3fb27SDimitry Andric STATISTIC(SpillageChainsLength, "Length of spillage chains");
8506c3fb27SDimitry Andric STATISTIC(NumSpillageChains, "Number of spillage chains");
860b57cec5SDimitry Andric DEBUG_COUNTER(FwdCounter, "machine-cp-fwd",
870b57cec5SDimitry Andric               "Controls which register COPYs are forwarded");
880b57cec5SDimitry Andric 
8981ad6265SDimitry Andric static cl::opt<bool> MCPUseCopyInstr("mcp-use-is-copy-instr", cl::init(false),
9081ad6265SDimitry Andric                                      cl::Hidden);
9106c3fb27SDimitry Andric static cl::opt<cl::boolOrDefault>
9206c3fb27SDimitry Andric     EnableSpillageCopyElimination("enable-spill-copy-elim", cl::Hidden);
9381ad6265SDimitry Andric 
940b57cec5SDimitry Andric namespace {
950b57cec5SDimitry Andric 
96bdd1243dSDimitry Andric static std::optional<DestSourcePair> isCopyInstr(const MachineInstr &MI,
9781ad6265SDimitry Andric                                                  const TargetInstrInfo &TII,
9881ad6265SDimitry Andric                                                  bool UseCopyInstr) {
9981ad6265SDimitry Andric   if (UseCopyInstr)
10081ad6265SDimitry Andric     return TII.isCopyInstr(MI);
10181ad6265SDimitry Andric 
10281ad6265SDimitry Andric   if (MI.isCopy())
103bdd1243dSDimitry Andric     return std::optional<DestSourcePair>(
10481ad6265SDimitry Andric         DestSourcePair{MI.getOperand(0), MI.getOperand(1)});
10581ad6265SDimitry Andric 
106bdd1243dSDimitry Andric   return std::nullopt;
10781ad6265SDimitry Andric }
10881ad6265SDimitry Andric 
1090b57cec5SDimitry Andric class CopyTracker {
1100b57cec5SDimitry Andric   struct CopyInfo {
11106c3fb27SDimitry Andric     MachineInstr *MI, *LastSeenUseInCopy;
112e8d8bef9SDimitry Andric     SmallVector<MCRegister, 4> DefRegs;
1130b57cec5SDimitry Andric     bool Avail;
1140b57cec5SDimitry Andric   };
1150b57cec5SDimitry Andric 
116*0fca6ea1SDimitry Andric   DenseMap<MCRegUnit, CopyInfo> Copies;
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric public:
1190b57cec5SDimitry Andric   /// Mark all of the given registers and their subregisters as unavailable for
1200b57cec5SDimitry Andric   /// copying.
121e8d8bef9SDimitry Andric   void markRegsUnavailable(ArrayRef<MCRegister> Regs,
1220b57cec5SDimitry Andric                            const TargetRegisterInfo &TRI) {
123e8d8bef9SDimitry Andric     for (MCRegister Reg : Regs) {
1240b57cec5SDimitry Andric       // Source of copy is no longer available for propagation.
12506c3fb27SDimitry Andric       for (MCRegUnit Unit : TRI.regunits(Reg)) {
12606c3fb27SDimitry Andric         auto CI = Copies.find(Unit);
1270b57cec5SDimitry Andric         if (CI != Copies.end())
1280b57cec5SDimitry Andric           CI->second.Avail = false;
1290b57cec5SDimitry Andric       }
1300b57cec5SDimitry Andric     }
1310b57cec5SDimitry Andric   }
1320b57cec5SDimitry Andric 
133480093f4SDimitry Andric   /// Remove register from copy maps.
13481ad6265SDimitry Andric   void invalidateRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
13581ad6265SDimitry Andric                           const TargetInstrInfo &TII, bool UseCopyInstr) {
136480093f4SDimitry Andric     // Since Reg might be a subreg of some registers, only invalidate Reg is not
137480093f4SDimitry Andric     // enough. We have to find the COPY defines Reg or registers defined by Reg
1385f757f3fSDimitry Andric     // and invalidate all of them. Similarly, we must invalidate all of the
1395f757f3fSDimitry Andric     // the subregisters used in the source of the COPY.
1405f757f3fSDimitry Andric     SmallSet<MCRegUnit, 8> RegUnitsToInvalidate;
1415f757f3fSDimitry Andric     auto InvalidateCopy = [&](MachineInstr *MI) {
142bdd1243dSDimitry Andric       std::optional<DestSourcePair> CopyOperands =
14381ad6265SDimitry Andric           isCopyInstr(*MI, TII, UseCopyInstr);
14481ad6265SDimitry Andric       assert(CopyOperands && "Expect copy");
14581ad6265SDimitry Andric 
1465f757f3fSDimitry Andric       auto Dest = TRI.regunits(CopyOperands->Destination->getReg().asMCReg());
1475f757f3fSDimitry Andric       auto Src = TRI.regunits(CopyOperands->Source->getReg().asMCReg());
1485f757f3fSDimitry Andric       RegUnitsToInvalidate.insert(Dest.begin(), Dest.end());
1495f757f3fSDimitry Andric       RegUnitsToInvalidate.insert(Src.begin(), Src.end());
1505f757f3fSDimitry Andric     };
1515f757f3fSDimitry Andric 
1525f757f3fSDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Reg)) {
1535f757f3fSDimitry Andric       auto I = Copies.find(Unit);
1545f757f3fSDimitry Andric       if (I != Copies.end()) {
1555f757f3fSDimitry Andric         if (MachineInstr *MI = I->second.MI)
1565f757f3fSDimitry Andric           InvalidateCopy(MI);
1575f757f3fSDimitry Andric         if (MachineInstr *MI = I->second.LastSeenUseInCopy)
1585f757f3fSDimitry Andric           InvalidateCopy(MI);
159480093f4SDimitry Andric       }
160480093f4SDimitry Andric     }
1615f757f3fSDimitry Andric     for (MCRegUnit Unit : RegUnitsToInvalidate)
16206c3fb27SDimitry Andric       Copies.erase(Unit);
163480093f4SDimitry Andric   }
164480093f4SDimitry Andric 
1650b57cec5SDimitry Andric   /// Clobber a single register, removing it from the tracker's copy maps.
16681ad6265SDimitry Andric   void clobberRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
16781ad6265SDimitry Andric                        const TargetInstrInfo &TII, bool UseCopyInstr) {
16806c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Reg)) {
16906c3fb27SDimitry Andric       auto I = Copies.find(Unit);
1700b57cec5SDimitry Andric       if (I != Copies.end()) {
1710b57cec5SDimitry Andric         // When we clobber the source of a copy, we need to clobber everything
1720b57cec5SDimitry Andric         // it defined.
1730b57cec5SDimitry Andric         markRegsUnavailable(I->second.DefRegs, TRI);
1740b57cec5SDimitry Andric         // When we clobber the destination of a copy, we need to clobber the
1750b57cec5SDimitry Andric         // whole register it defined.
17681ad6265SDimitry Andric         if (MachineInstr *MI = I->second.MI) {
177bdd1243dSDimitry Andric           std::optional<DestSourcePair> CopyOperands =
17881ad6265SDimitry Andric               isCopyInstr(*MI, TII, UseCopyInstr);
179647cbc5dSDimitry Andric 
180647cbc5dSDimitry Andric           MCRegister Def = CopyOperands->Destination->getReg().asMCReg();
181647cbc5dSDimitry Andric           MCRegister Src = CopyOperands->Source->getReg().asMCReg();
182647cbc5dSDimitry Andric 
183647cbc5dSDimitry Andric           markRegsUnavailable(Def, TRI);
184647cbc5dSDimitry Andric 
185647cbc5dSDimitry Andric           // Since we clobber the destination of a copy, the semantic of Src's
186647cbc5dSDimitry Andric           // "DefRegs" to contain Def is no longer effectual. We will also need
187647cbc5dSDimitry Andric           // to remove the record from the copy maps that indicates Src defined
188647cbc5dSDimitry Andric           // Def. Failing to do so might cause the target to miss some
189647cbc5dSDimitry Andric           // opportunities to further eliminate redundant copy instructions.
190647cbc5dSDimitry Andric           // Consider the following sequence during the
191647cbc5dSDimitry Andric           // ForwardCopyPropagateBlock procedure:
192647cbc5dSDimitry Andric           // L1: r0 = COPY r9     <- TrackMI
193647cbc5dSDimitry Andric           // L2: r0 = COPY r8     <- TrackMI (Remove r9 defined r0 from tracker)
194647cbc5dSDimitry Andric           // L3: use r0           <- Remove L2 from MaybeDeadCopies
195647cbc5dSDimitry Andric           // L4: early-clobber r9 <- Clobber r9 (L2 is still valid in tracker)
196647cbc5dSDimitry Andric           // L5: r0 = COPY r8     <- Remove NopCopy
197647cbc5dSDimitry Andric           for (MCRegUnit SrcUnit : TRI.regunits(Src)) {
198647cbc5dSDimitry Andric             auto SrcCopy = Copies.find(SrcUnit);
199647cbc5dSDimitry Andric             if (SrcCopy != Copies.end() && SrcCopy->second.LastSeenUseInCopy) {
200647cbc5dSDimitry Andric               // If SrcCopy defines multiple values, we only need
201647cbc5dSDimitry Andric               // to erase the record for Def in DefRegs.
202647cbc5dSDimitry Andric               for (auto itr = SrcCopy->second.DefRegs.begin();
203647cbc5dSDimitry Andric                    itr != SrcCopy->second.DefRegs.end(); itr++) {
204647cbc5dSDimitry Andric                 if (*itr == Def) {
205647cbc5dSDimitry Andric                   SrcCopy->second.DefRegs.erase(itr);
206647cbc5dSDimitry Andric                   // If DefReg becomes empty after removal, we can remove the
207647cbc5dSDimitry Andric                   // SrcCopy from the tracker's copy maps. We only remove those
208647cbc5dSDimitry Andric                   // entries solely record the Def is defined by Src. If an
209647cbc5dSDimitry Andric                   // entry also contains the definition record of other Def'
210647cbc5dSDimitry Andric                   // registers, it cannot be cleared.
211647cbc5dSDimitry Andric                   if (SrcCopy->second.DefRegs.empty() && !SrcCopy->second.MI) {
212647cbc5dSDimitry Andric                     Copies.erase(SrcCopy);
213647cbc5dSDimitry Andric                   }
214647cbc5dSDimitry Andric                   break;
215647cbc5dSDimitry Andric                 }
216647cbc5dSDimitry Andric               }
217647cbc5dSDimitry Andric             }
218647cbc5dSDimitry Andric           }
21981ad6265SDimitry Andric         }
2200b57cec5SDimitry Andric         // Now we can erase the copy.
2210b57cec5SDimitry Andric         Copies.erase(I);
2220b57cec5SDimitry Andric       }
2230b57cec5SDimitry Andric     }
2240b57cec5SDimitry Andric   }
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric   /// Add this copy's registers into the tracker's copy maps.
22781ad6265SDimitry Andric   void trackCopy(MachineInstr *MI, const TargetRegisterInfo &TRI,
22881ad6265SDimitry Andric                  const TargetInstrInfo &TII, bool UseCopyInstr) {
229bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
230bdd1243dSDimitry Andric         isCopyInstr(*MI, TII, UseCopyInstr);
23181ad6265SDimitry Andric     assert(CopyOperands && "Tracking non-copy?");
2320b57cec5SDimitry Andric 
23381ad6265SDimitry Andric     MCRegister Src = CopyOperands->Source->getReg().asMCReg();
23481ad6265SDimitry Andric     MCRegister Def = CopyOperands->Destination->getReg().asMCReg();
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric     // Remember Def is defined by the copy.
23706c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Def))
23806c3fb27SDimitry Andric       Copies[Unit] = {MI, nullptr, {}, true};
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric     // Remember source that's copied to Def. Once it's clobbered, then
2410b57cec5SDimitry Andric     // it's no longer available for copy propagation.
24206c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Src)) {
24306c3fb27SDimitry Andric       auto I = Copies.insert({Unit, {nullptr, nullptr, {}, false}});
2440b57cec5SDimitry Andric       auto &Copy = I.first->second;
2450b57cec5SDimitry Andric       if (!is_contained(Copy.DefRegs, Def))
2460b57cec5SDimitry Andric         Copy.DefRegs.push_back(Def);
24706c3fb27SDimitry Andric       Copy.LastSeenUseInCopy = MI;
2480b57cec5SDimitry Andric     }
2490b57cec5SDimitry Andric   }
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric   bool hasAnyCopies() {
2520b57cec5SDimitry Andric     return !Copies.empty();
2530b57cec5SDimitry Andric   }
2540b57cec5SDimitry Andric 
255*0fca6ea1SDimitry Andric   MachineInstr *findCopyForUnit(MCRegUnit RegUnit,
256e8d8bef9SDimitry Andric                                 const TargetRegisterInfo &TRI,
2570b57cec5SDimitry Andric                                 bool MustBeAvailable = false) {
2580b57cec5SDimitry Andric     auto CI = Copies.find(RegUnit);
2590b57cec5SDimitry Andric     if (CI == Copies.end())
2600b57cec5SDimitry Andric       return nullptr;
2610b57cec5SDimitry Andric     if (MustBeAvailable && !CI->second.Avail)
2620b57cec5SDimitry Andric       return nullptr;
2630b57cec5SDimitry Andric     return CI->second.MI;
2640b57cec5SDimitry Andric   }
2650b57cec5SDimitry Andric 
266*0fca6ea1SDimitry Andric   MachineInstr *findCopyDefViaUnit(MCRegUnit RegUnit,
267480093f4SDimitry Andric                                    const TargetRegisterInfo &TRI) {
268480093f4SDimitry Andric     auto CI = Copies.find(RegUnit);
269480093f4SDimitry Andric     if (CI == Copies.end())
270480093f4SDimitry Andric       return nullptr;
271480093f4SDimitry Andric     if (CI->second.DefRegs.size() != 1)
272480093f4SDimitry Andric       return nullptr;
27306c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(CI->second.DefRegs[0]).begin();
27406c3fb27SDimitry Andric     return findCopyForUnit(RU, TRI, true);
275480093f4SDimitry Andric   }
276480093f4SDimitry Andric 
277e8d8bef9SDimitry Andric   MachineInstr *findAvailBackwardCopy(MachineInstr &I, MCRegister Reg,
27881ad6265SDimitry Andric                                       const TargetRegisterInfo &TRI,
27981ad6265SDimitry Andric                                       const TargetInstrInfo &TII,
28081ad6265SDimitry Andric                                       bool UseCopyInstr) {
28106c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
28206c3fb27SDimitry Andric     MachineInstr *AvailCopy = findCopyDefViaUnit(RU, TRI);
28381ad6265SDimitry Andric 
28481ad6265SDimitry Andric     if (!AvailCopy)
285480093f4SDimitry Andric       return nullptr;
286480093f4SDimitry Andric 
287bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
28881ad6265SDimitry Andric         isCopyInstr(*AvailCopy, TII, UseCopyInstr);
28981ad6265SDimitry Andric     Register AvailSrc = CopyOperands->Source->getReg();
29081ad6265SDimitry Andric     Register AvailDef = CopyOperands->Destination->getReg();
29181ad6265SDimitry Andric     if (!TRI.isSubRegisterEq(AvailSrc, Reg))
29281ad6265SDimitry Andric       return nullptr;
29381ad6265SDimitry Andric 
294480093f4SDimitry Andric     for (const MachineInstr &MI :
295480093f4SDimitry Andric          make_range(AvailCopy->getReverseIterator(), I.getReverseIterator()))
296480093f4SDimitry Andric       for (const MachineOperand &MO : MI.operands())
297480093f4SDimitry Andric         if (MO.isRegMask())
298480093f4SDimitry Andric           // FIXME: Shall we simultaneously invalidate AvailSrc or AvailDef?
299480093f4SDimitry Andric           if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
300480093f4SDimitry Andric             return nullptr;
301480093f4SDimitry Andric 
302480093f4SDimitry Andric     return AvailCopy;
303480093f4SDimitry Andric   }
304480093f4SDimitry Andric 
305e8d8bef9SDimitry Andric   MachineInstr *findAvailCopy(MachineInstr &DestCopy, MCRegister Reg,
30681ad6265SDimitry Andric                               const TargetRegisterInfo &TRI,
30781ad6265SDimitry Andric                               const TargetInstrInfo &TII, bool UseCopyInstr) {
3080b57cec5SDimitry Andric     // We check the first RegUnit here, since we'll only be interested in the
3090b57cec5SDimitry Andric     // copy if it copies the entire register anyway.
31006c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
3110b57cec5SDimitry Andric     MachineInstr *AvailCopy =
31206c3fb27SDimitry Andric         findCopyForUnit(RU, TRI, /*MustBeAvailable=*/true);
31381ad6265SDimitry Andric 
31481ad6265SDimitry Andric     if (!AvailCopy)
31581ad6265SDimitry Andric       return nullptr;
31681ad6265SDimitry Andric 
317bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
31881ad6265SDimitry Andric         isCopyInstr(*AvailCopy, TII, UseCopyInstr);
31981ad6265SDimitry Andric     Register AvailSrc = CopyOperands->Source->getReg();
32081ad6265SDimitry Andric     Register AvailDef = CopyOperands->Destination->getReg();
32181ad6265SDimitry Andric     if (!TRI.isSubRegisterEq(AvailDef, Reg))
3220b57cec5SDimitry Andric       return nullptr;
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric     // Check that the available copy isn't clobbered by any regmasks between
3250b57cec5SDimitry Andric     // itself and the destination.
3260b57cec5SDimitry Andric     for (const MachineInstr &MI :
3270b57cec5SDimitry Andric          make_range(AvailCopy->getIterator(), DestCopy.getIterator()))
3280b57cec5SDimitry Andric       for (const MachineOperand &MO : MI.operands())
3290b57cec5SDimitry Andric         if (MO.isRegMask())
3300b57cec5SDimitry Andric           if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
3310b57cec5SDimitry Andric             return nullptr;
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric     return AvailCopy;
3340b57cec5SDimitry Andric   }
3350b57cec5SDimitry Andric 
33606c3fb27SDimitry Andric   // Find last COPY that defines Reg before Current MachineInstr.
33706c3fb27SDimitry Andric   MachineInstr *findLastSeenDefInCopy(const MachineInstr &Current,
33806c3fb27SDimitry Andric                                       MCRegister Reg,
33906c3fb27SDimitry Andric                                       const TargetRegisterInfo &TRI,
34006c3fb27SDimitry Andric                                       const TargetInstrInfo &TII,
34106c3fb27SDimitry Andric                                       bool UseCopyInstr) {
34206c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
34306c3fb27SDimitry Andric     auto CI = Copies.find(RU);
34406c3fb27SDimitry Andric     if (CI == Copies.end() || !CI->second.Avail)
34506c3fb27SDimitry Andric       return nullptr;
34606c3fb27SDimitry Andric 
34706c3fb27SDimitry Andric     MachineInstr *DefCopy = CI->second.MI;
34806c3fb27SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
34906c3fb27SDimitry Andric         isCopyInstr(*DefCopy, TII, UseCopyInstr);
35006c3fb27SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
35106c3fb27SDimitry Andric     if (!TRI.isSubRegisterEq(Def, Reg))
35206c3fb27SDimitry Andric       return nullptr;
35306c3fb27SDimitry Andric 
35406c3fb27SDimitry Andric     for (const MachineInstr &MI :
35506c3fb27SDimitry Andric          make_range(static_cast<const MachineInstr *>(DefCopy)->getIterator(),
35606c3fb27SDimitry Andric                     Current.getIterator()))
35706c3fb27SDimitry Andric       for (const MachineOperand &MO : MI.operands())
35806c3fb27SDimitry Andric         if (MO.isRegMask())
35906c3fb27SDimitry Andric           if (MO.clobbersPhysReg(Def)) {
36006c3fb27SDimitry Andric             LLVM_DEBUG(dbgs() << "MCP: Removed tracking of "
36106c3fb27SDimitry Andric                               << printReg(Def, &TRI) << "\n");
36206c3fb27SDimitry Andric             return nullptr;
36306c3fb27SDimitry Andric           }
36406c3fb27SDimitry Andric 
36506c3fb27SDimitry Andric     return DefCopy;
36606c3fb27SDimitry Andric   }
36706c3fb27SDimitry Andric 
36806c3fb27SDimitry Andric   // Find last COPY that uses Reg.
36906c3fb27SDimitry Andric   MachineInstr *findLastSeenUseInCopy(MCRegister Reg,
37006c3fb27SDimitry Andric                                       const TargetRegisterInfo &TRI) {
37106c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
37206c3fb27SDimitry Andric     auto CI = Copies.find(RU);
37306c3fb27SDimitry Andric     if (CI == Copies.end())
37406c3fb27SDimitry Andric       return nullptr;
37506c3fb27SDimitry Andric     return CI->second.LastSeenUseInCopy;
37606c3fb27SDimitry Andric   }
37706c3fb27SDimitry Andric 
3780b57cec5SDimitry Andric   void clear() {
3790b57cec5SDimitry Andric     Copies.clear();
3800b57cec5SDimitry Andric   }
3810b57cec5SDimitry Andric };
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric class MachineCopyPropagation : public MachineFunctionPass {
38406c3fb27SDimitry Andric   const TargetRegisterInfo *TRI = nullptr;
38506c3fb27SDimitry Andric   const TargetInstrInfo *TII = nullptr;
38606c3fb27SDimitry Andric   const MachineRegisterInfo *MRI = nullptr;
3870b57cec5SDimitry Andric 
38881ad6265SDimitry Andric   // Return true if this is a copy instruction and false otherwise.
38981ad6265SDimitry Andric   bool UseCopyInstr;
39081ad6265SDimitry Andric 
3910b57cec5SDimitry Andric public:
3920b57cec5SDimitry Andric   static char ID; // Pass identification, replacement for typeid
3930b57cec5SDimitry Andric 
39481ad6265SDimitry Andric   MachineCopyPropagation(bool CopyInstr = false)
39581ad6265SDimitry Andric       : MachineFunctionPass(ID), UseCopyInstr(CopyInstr || MCPUseCopyInstr) {
3960b57cec5SDimitry Andric     initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
3970b57cec5SDimitry Andric   }
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
4000b57cec5SDimitry Andric     AU.setPreservesCFG();
4010b57cec5SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
4020b57cec5SDimitry Andric   }
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric   MachineFunctionProperties getRequiredProperties() const override {
4070b57cec5SDimitry Andric     return MachineFunctionProperties().set(
4080b57cec5SDimitry Andric         MachineFunctionProperties::Property::NoVRegs);
4090b57cec5SDimitry Andric   }
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric private:
4128bcb0991SDimitry Andric   typedef enum { DebugUse = false, RegularUse = true } DebugType;
4138bcb0991SDimitry Andric 
414e8d8bef9SDimitry Andric   void ReadRegister(MCRegister Reg, MachineInstr &Reader, DebugType DT);
415*0fca6ea1SDimitry Andric   void readSuccessorLiveIns(const MachineBasicBlock &MBB);
416480093f4SDimitry Andric   void ForwardCopyPropagateBlock(MachineBasicBlock &MBB);
417480093f4SDimitry Andric   void BackwardCopyPropagateBlock(MachineBasicBlock &MBB);
41806c3fb27SDimitry Andric   void EliminateSpillageCopies(MachineBasicBlock &MBB);
419e8d8bef9SDimitry Andric   bool eraseIfRedundant(MachineInstr &Copy, MCRegister Src, MCRegister Def);
4200b57cec5SDimitry Andric   void forwardUses(MachineInstr &MI);
421480093f4SDimitry Andric   void propagateDefs(MachineInstr &MI);
4220b57cec5SDimitry Andric   bool isForwardableRegClassCopy(const MachineInstr &Copy,
4230b57cec5SDimitry Andric                                  const MachineInstr &UseI, unsigned UseIdx);
424480093f4SDimitry Andric   bool isBackwardPropagatableRegClassCopy(const MachineInstr &Copy,
425480093f4SDimitry Andric                                           const MachineInstr &UseI,
426480093f4SDimitry Andric                                           unsigned UseIdx);
4270b57cec5SDimitry Andric   bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use);
428e8d8bef9SDimitry Andric   bool hasOverlappingMultipleDef(const MachineInstr &MI,
429e8d8bef9SDimitry Andric                                  const MachineOperand &MODef, Register Def);
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric   /// Candidates for deletion.
4320b57cec5SDimitry Andric   SmallSetVector<MachineInstr *, 8> MaybeDeadCopies;
4330b57cec5SDimitry Andric 
4348bcb0991SDimitry Andric   /// Multimap tracking debug users in current BB
435fe6060f1SDimitry Andric   DenseMap<MachineInstr *, SmallSet<MachineInstr *, 2>> CopyDbgUsers;
4368bcb0991SDimitry Andric 
4370b57cec5SDimitry Andric   CopyTracker Tracker;
4380b57cec5SDimitry Andric 
43906c3fb27SDimitry Andric   bool Changed = false;
4400b57cec5SDimitry Andric };
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric } // end anonymous namespace
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric char MachineCopyPropagation::ID = 0;
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
4470b57cec5SDimitry Andric 
4480b57cec5SDimitry Andric INITIALIZE_PASS(MachineCopyPropagation, DEBUG_TYPE,
4490b57cec5SDimitry Andric                 "Machine Copy Propagation Pass", false, false)
4500b57cec5SDimitry Andric 
451e8d8bef9SDimitry Andric void MachineCopyPropagation::ReadRegister(MCRegister Reg, MachineInstr &Reader,
4528bcb0991SDimitry Andric                                           DebugType DT) {
4530b57cec5SDimitry Andric   // If 'Reg' is defined by a copy, the copy is no longer a candidate
4548bcb0991SDimitry Andric   // for elimination. If a copy is "read" by a debug user, record the user
4558bcb0991SDimitry Andric   // for propagation.
45606c3fb27SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(Reg)) {
45706c3fb27SDimitry Andric     if (MachineInstr *Copy = Tracker.findCopyForUnit(Unit, *TRI)) {
4588bcb0991SDimitry Andric       if (DT == RegularUse) {
4590b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy->dump());
4600b57cec5SDimitry Andric         MaybeDeadCopies.remove(Copy);
4618bcb0991SDimitry Andric       } else {
462fe6060f1SDimitry Andric         CopyDbgUsers[Copy].insert(&Reader);
4638bcb0991SDimitry Andric       }
4640b57cec5SDimitry Andric     }
4650b57cec5SDimitry Andric   }
4660b57cec5SDimitry Andric }
4670b57cec5SDimitry Andric 
468*0fca6ea1SDimitry Andric void MachineCopyPropagation::readSuccessorLiveIns(
469*0fca6ea1SDimitry Andric     const MachineBasicBlock &MBB) {
470*0fca6ea1SDimitry Andric   if (MaybeDeadCopies.empty())
471*0fca6ea1SDimitry Andric     return;
472*0fca6ea1SDimitry Andric 
473*0fca6ea1SDimitry Andric   // If a copy result is livein to a successor, it is not dead.
474*0fca6ea1SDimitry Andric   for (const MachineBasicBlock *Succ : MBB.successors()) {
475*0fca6ea1SDimitry Andric     for (const auto &LI : Succ->liveins()) {
476*0fca6ea1SDimitry Andric       for (MCRegUnit Unit : TRI->regunits(LI.PhysReg)) {
477*0fca6ea1SDimitry Andric         if (MachineInstr *Copy = Tracker.findCopyForUnit(Unit, *TRI))
478*0fca6ea1SDimitry Andric           MaybeDeadCopies.remove(Copy);
479*0fca6ea1SDimitry Andric       }
480*0fca6ea1SDimitry Andric     }
481*0fca6ea1SDimitry Andric   }
482*0fca6ea1SDimitry Andric }
483*0fca6ea1SDimitry Andric 
4840b57cec5SDimitry Andric /// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
4850b57cec5SDimitry Andric /// This fact may have been obscured by sub register usage or may not be true at
4860b57cec5SDimitry Andric /// all even though Src and Def are subregisters of the registers used in
4870b57cec5SDimitry Andric /// PreviousCopy. e.g.
4880b57cec5SDimitry Andric /// isNopCopy("ecx = COPY eax", AX, CX) == true
4890b57cec5SDimitry Andric /// isNopCopy("ecx = COPY eax", AH, CL) == false
490e8d8bef9SDimitry Andric static bool isNopCopy(const MachineInstr &PreviousCopy, MCRegister Src,
49181ad6265SDimitry Andric                       MCRegister Def, const TargetRegisterInfo *TRI,
49281ad6265SDimitry Andric                       const TargetInstrInfo *TII, bool UseCopyInstr) {
49381ad6265SDimitry Andric 
494bdd1243dSDimitry Andric   std::optional<DestSourcePair> CopyOperands =
49581ad6265SDimitry Andric       isCopyInstr(PreviousCopy, *TII, UseCopyInstr);
49681ad6265SDimitry Andric   MCRegister PreviousSrc = CopyOperands->Source->getReg().asMCReg();
49781ad6265SDimitry Andric   MCRegister PreviousDef = CopyOperands->Destination->getReg().asMCReg();
49816d6b3b3SDimitry Andric   if (Src == PreviousSrc && Def == PreviousDef)
4990b57cec5SDimitry Andric     return true;
5000b57cec5SDimitry Andric   if (!TRI->isSubRegister(PreviousSrc, Src))
5010b57cec5SDimitry Andric     return false;
5020b57cec5SDimitry Andric   unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
5030b57cec5SDimitry Andric   return SubIdx == TRI->getSubRegIndex(PreviousDef, Def);
5040b57cec5SDimitry Andric }
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric /// Remove instruction \p Copy if there exists a previous copy that copies the
5070b57cec5SDimitry Andric /// register \p Src to the register \p Def; This may happen indirectly by
5080b57cec5SDimitry Andric /// copying the super registers.
509e8d8bef9SDimitry Andric bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy,
510e8d8bef9SDimitry Andric                                               MCRegister Src, MCRegister Def) {
5110b57cec5SDimitry Andric   // Avoid eliminating a copy from/to a reserved registers as we cannot predict
5120b57cec5SDimitry Andric   // the value (Example: The sparc zero register is writable but stays zero).
5130b57cec5SDimitry Andric   if (MRI->isReserved(Src) || MRI->isReserved(Def))
5140b57cec5SDimitry Andric     return false;
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric   // Search for an existing copy.
51781ad6265SDimitry Andric   MachineInstr *PrevCopy =
51881ad6265SDimitry Andric       Tracker.findAvailCopy(Copy, Def, *TRI, *TII, UseCopyInstr);
5190b57cec5SDimitry Andric   if (!PrevCopy)
5200b57cec5SDimitry Andric     return false;
5210b57cec5SDimitry Andric 
52281ad6265SDimitry Andric   auto PrevCopyOperands = isCopyInstr(*PrevCopy, *TII, UseCopyInstr);
5230b57cec5SDimitry Andric   // Check that the existing copy uses the correct sub registers.
52481ad6265SDimitry Andric   if (PrevCopyOperands->Destination->isDead())
5250b57cec5SDimitry Andric     return false;
52681ad6265SDimitry Andric   if (!isNopCopy(*PrevCopy, Src, Def, TRI, TII, UseCopyInstr))
5270b57cec5SDimitry Andric     return false;
5280b57cec5SDimitry Andric 
5290b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric   // Copy was redundantly redefining either Src or Def. Remove earlier kill
5320b57cec5SDimitry Andric   // flags between Copy and PrevCopy because the value will be reused now.
533bdd1243dSDimitry Andric   std::optional<DestSourcePair> CopyOperands =
534bdd1243dSDimitry Andric       isCopyInstr(Copy, *TII, UseCopyInstr);
53581ad6265SDimitry Andric   assert(CopyOperands);
53681ad6265SDimitry Andric 
53781ad6265SDimitry Andric   Register CopyDef = CopyOperands->Destination->getReg();
5380b57cec5SDimitry Andric   assert(CopyDef == Src || CopyDef == Def);
5390b57cec5SDimitry Andric   for (MachineInstr &MI :
5400b57cec5SDimitry Andric        make_range(PrevCopy->getIterator(), Copy.getIterator()))
5410b57cec5SDimitry Andric     MI.clearRegisterKills(CopyDef, TRI);
5420b57cec5SDimitry Andric 
54306c3fb27SDimitry Andric   // Clear undef flag from remaining copy if needed.
54406c3fb27SDimitry Andric   if (!CopyOperands->Source->isUndef()) {
54506c3fb27SDimitry Andric     PrevCopy->getOperand(PrevCopyOperands->Source->getOperandNo())
54606c3fb27SDimitry Andric         .setIsUndef(false);
54706c3fb27SDimitry Andric   }
54806c3fb27SDimitry Andric 
5490b57cec5SDimitry Andric   Copy.eraseFromParent();
5500b57cec5SDimitry Andric   Changed = true;
5510b57cec5SDimitry Andric   ++NumDeletes;
5520b57cec5SDimitry Andric   return true;
5530b57cec5SDimitry Andric }
5540b57cec5SDimitry Andric 
555480093f4SDimitry Andric bool MachineCopyPropagation::isBackwardPropagatableRegClassCopy(
556480093f4SDimitry Andric     const MachineInstr &Copy, const MachineInstr &UseI, unsigned UseIdx) {
557bdd1243dSDimitry Andric   std::optional<DestSourcePair> CopyOperands =
558bdd1243dSDimitry Andric       isCopyInstr(Copy, *TII, UseCopyInstr);
55981ad6265SDimitry Andric   Register Def = CopyOperands->Destination->getReg();
560480093f4SDimitry Andric 
561480093f4SDimitry Andric   if (const TargetRegisterClass *URC =
562480093f4SDimitry Andric           UseI.getRegClassConstraint(UseIdx, TII, TRI))
563480093f4SDimitry Andric     return URC->contains(Def);
564480093f4SDimitry Andric 
565480093f4SDimitry Andric   // We don't process further if UseI is a COPY, since forward copy propagation
566480093f4SDimitry Andric   // should handle that.
567480093f4SDimitry Andric   return false;
568480093f4SDimitry Andric }
569480093f4SDimitry Andric 
5700b57cec5SDimitry Andric /// Decide whether we should forward the source of \param Copy to its use in
5710b57cec5SDimitry Andric /// \param UseI based on the physical register class constraints of the opcode
5720b57cec5SDimitry Andric /// and avoiding introducing more cross-class COPYs.
5730b57cec5SDimitry Andric bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
5740b57cec5SDimitry Andric                                                        const MachineInstr &UseI,
5750b57cec5SDimitry Andric                                                        unsigned UseIdx) {
576bdd1243dSDimitry Andric   std::optional<DestSourcePair> CopyOperands =
577bdd1243dSDimitry Andric       isCopyInstr(Copy, *TII, UseCopyInstr);
57881ad6265SDimitry Andric   Register CopySrcReg = CopyOperands->Source->getReg();
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric   // If the new register meets the opcode register constraints, then allow
5810b57cec5SDimitry Andric   // forwarding.
5820b57cec5SDimitry Andric   if (const TargetRegisterClass *URC =
5830b57cec5SDimitry Andric           UseI.getRegClassConstraint(UseIdx, TII, TRI))
5840b57cec5SDimitry Andric     return URC->contains(CopySrcReg);
5850b57cec5SDimitry Andric 
58681ad6265SDimitry Andric   auto UseICopyOperands = isCopyInstr(UseI, *TII, UseCopyInstr);
58781ad6265SDimitry Andric   if (!UseICopyOperands)
5880b57cec5SDimitry Andric     return false;
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric   /// COPYs don't have register class constraints, so if the user instruction
5910b57cec5SDimitry Andric   /// is a COPY, we just try to avoid introducing additional cross-class
5920b57cec5SDimitry Andric   /// COPYs.  For example:
5930b57cec5SDimitry Andric   ///
5940b57cec5SDimitry Andric   ///   RegClassA = COPY RegClassB  // Copy parameter
5950b57cec5SDimitry Andric   ///   ...
5960b57cec5SDimitry Andric   ///   RegClassB = COPY RegClassA  // UseI parameter
5970b57cec5SDimitry Andric   ///
5980b57cec5SDimitry Andric   /// which after forwarding becomes
5990b57cec5SDimitry Andric   ///
6000b57cec5SDimitry Andric   ///   RegClassA = COPY RegClassB
6010b57cec5SDimitry Andric   ///   ...
6020b57cec5SDimitry Andric   ///   RegClassB = COPY RegClassB
6030b57cec5SDimitry Andric   ///
6040b57cec5SDimitry Andric   /// so we have reduced the number of cross-class COPYs and potentially
6050b57cec5SDimitry Andric   /// introduced a nop COPY that can be removed.
6060b57cec5SDimitry Andric 
60781ad6265SDimitry Andric   // Allow forwarding if src and dst belong to any common class, so long as they
60881ad6265SDimitry Andric   // don't belong to any (possibly smaller) common class that requires copies to
60981ad6265SDimitry Andric   // go via a different class.
61081ad6265SDimitry Andric   Register UseDstReg = UseICopyOperands->Destination->getReg();
61181ad6265SDimitry Andric   bool Found = false;
61281ad6265SDimitry Andric   bool IsCrossClass = false;
61381ad6265SDimitry Andric   for (const TargetRegisterClass *RC : TRI->regclasses()) {
61481ad6265SDimitry Andric     if (RC->contains(CopySrcReg) && RC->contains(UseDstReg)) {
61581ad6265SDimitry Andric       Found = true;
61681ad6265SDimitry Andric       if (TRI->getCrossCopyRegClass(RC) != RC) {
61781ad6265SDimitry Andric         IsCrossClass = true;
61881ad6265SDimitry Andric         break;
61981ad6265SDimitry Andric       }
62081ad6265SDimitry Andric     }
62181ad6265SDimitry Andric   }
62281ad6265SDimitry Andric   if (!Found)
62381ad6265SDimitry Andric     return false;
62481ad6265SDimitry Andric   if (!IsCrossClass)
62581ad6265SDimitry Andric     return true;
62681ad6265SDimitry Andric   // The forwarded copy would be cross-class. Only do this if the original copy
62781ad6265SDimitry Andric   // was also cross-class.
62881ad6265SDimitry Andric   Register CopyDstReg = CopyOperands->Destination->getReg();
62981ad6265SDimitry Andric   for (const TargetRegisterClass *RC : TRI->regclasses()) {
63081ad6265SDimitry Andric     if (RC->contains(CopySrcReg) && RC->contains(CopyDstReg) &&
63181ad6265SDimitry Andric         TRI->getCrossCopyRegClass(RC) != RC)
63281ad6265SDimitry Andric       return true;
63381ad6265SDimitry Andric   }
6340b57cec5SDimitry Andric   return false;
6350b57cec5SDimitry Andric }
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric /// Check that \p MI does not have implicit uses that overlap with it's \p Use
6380b57cec5SDimitry Andric /// operand (the register being replaced), since these can sometimes be
6390b57cec5SDimitry Andric /// implicitly tied to other operands.  For example, on AMDGPU:
6400b57cec5SDimitry Andric ///
6410b57cec5SDimitry Andric /// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
6420b57cec5SDimitry Andric ///
6430b57cec5SDimitry Andric /// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
6440b57cec5SDimitry Andric /// way of knowing we need to update the latter when updating the former.
6450b57cec5SDimitry Andric bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
6460b57cec5SDimitry Andric                                                 const MachineOperand &Use) {
6470b57cec5SDimitry Andric   for (const MachineOperand &MIUse : MI.uses())
6480b57cec5SDimitry Andric     if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
6490b57cec5SDimitry Andric         MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
6500b57cec5SDimitry Andric       return true;
6510b57cec5SDimitry Andric 
6520b57cec5SDimitry Andric   return false;
6530b57cec5SDimitry Andric }
6540b57cec5SDimitry Andric 
655e8d8bef9SDimitry Andric /// For an MI that has multiple definitions, check whether \p MI has
656e8d8bef9SDimitry Andric /// a definition that overlaps with another of its definitions.
657e8d8bef9SDimitry Andric /// For example, on ARM: umull   r9, r9, lr, r0
658e8d8bef9SDimitry Andric /// The umull instruction is unpredictable unless RdHi and RdLo are different.
659e8d8bef9SDimitry Andric bool MachineCopyPropagation::hasOverlappingMultipleDef(
660e8d8bef9SDimitry Andric     const MachineInstr &MI, const MachineOperand &MODef, Register Def) {
661*0fca6ea1SDimitry Andric   for (const MachineOperand &MIDef : MI.all_defs()) {
662e8d8bef9SDimitry Andric     if ((&MIDef != &MODef) && MIDef.isReg() &&
663e8d8bef9SDimitry Andric         TRI->regsOverlap(Def, MIDef.getReg()))
664e8d8bef9SDimitry Andric       return true;
665e8d8bef9SDimitry Andric   }
666e8d8bef9SDimitry Andric 
667e8d8bef9SDimitry Andric   return false;
668e8d8bef9SDimitry Andric }
669e8d8bef9SDimitry Andric 
6700b57cec5SDimitry Andric /// Look for available copies whose destination register is used by \p MI and
6710b57cec5SDimitry Andric /// replace the use in \p MI with the copy's source register.
6720b57cec5SDimitry Andric void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
6730b57cec5SDimitry Andric   if (!Tracker.hasAnyCopies())
6740b57cec5SDimitry Andric     return;
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric   // Look for non-tied explicit vreg uses that have an active COPY
6770b57cec5SDimitry Andric   // instruction that defines the physical register allocated to them.
6780b57cec5SDimitry Andric   // Replace the vreg with the source of the active COPY.
6790b57cec5SDimitry Andric   for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
6800b57cec5SDimitry Andric        ++OpIdx) {
6810b57cec5SDimitry Andric     MachineOperand &MOUse = MI.getOperand(OpIdx);
6820b57cec5SDimitry Andric     // Don't forward into undef use operands since doing so can cause problems
6830b57cec5SDimitry Andric     // with the machine verifier, since it doesn't treat undef reads as reads,
6840b57cec5SDimitry Andric     // so we can end up with a live range that ends on an undef read, leading to
6850b57cec5SDimitry Andric     // an error that the live range doesn't end on a read of the live range
6860b57cec5SDimitry Andric     // register.
6870b57cec5SDimitry Andric     if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
6880b57cec5SDimitry Andric         MOUse.isImplicit())
6890b57cec5SDimitry Andric       continue;
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric     if (!MOUse.getReg())
6920b57cec5SDimitry Andric       continue;
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric     // Check that the register is marked 'renamable' so we know it is safe to
6950b57cec5SDimitry Andric     // rename it without violating any constraints that aren't expressed in the
6960b57cec5SDimitry Andric     // IR (e.g. ABI or opcode requirements).
6970b57cec5SDimitry Andric     if (!MOUse.isRenamable())
6980b57cec5SDimitry Andric       continue;
6990b57cec5SDimitry Andric 
70081ad6265SDimitry Andric     MachineInstr *Copy = Tracker.findAvailCopy(MI, MOUse.getReg().asMCReg(),
70181ad6265SDimitry Andric                                                *TRI, *TII, UseCopyInstr);
7020b57cec5SDimitry Andric     if (!Copy)
7030b57cec5SDimitry Andric       continue;
7040b57cec5SDimitry Andric 
705bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
70681ad6265SDimitry Andric         isCopyInstr(*Copy, *TII, UseCopyInstr);
70781ad6265SDimitry Andric     Register CopyDstReg = CopyOperands->Destination->getReg();
70881ad6265SDimitry Andric     const MachineOperand &CopySrc = *CopyOperands->Source;
7098bcb0991SDimitry Andric     Register CopySrcReg = CopySrc.getReg();
7100b57cec5SDimitry Andric 
71106c3fb27SDimitry Andric     Register ForwardedReg = CopySrcReg;
71206c3fb27SDimitry Andric     // MI might use a sub-register of the Copy destination, in which case the
71306c3fb27SDimitry Andric     // forwarded register is the matching sub-register of the Copy source.
7140b57cec5SDimitry Andric     if (MOUse.getReg() != CopyDstReg) {
71506c3fb27SDimitry Andric       unsigned SubRegIdx = TRI->getSubRegIndex(CopyDstReg, MOUse.getReg());
71606c3fb27SDimitry Andric       assert(SubRegIdx &&
71706c3fb27SDimitry Andric              "MI source is not a sub-register of Copy destination");
71806c3fb27SDimitry Andric       ForwardedReg = TRI->getSubReg(CopySrcReg, SubRegIdx);
71906c3fb27SDimitry Andric       if (!ForwardedReg) {
72006c3fb27SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Copy source does not have sub-register "
72106c3fb27SDimitry Andric                           << TRI->getSubRegIndexName(SubRegIdx) << '\n');
7220b57cec5SDimitry Andric         continue;
7230b57cec5SDimitry Andric       }
72406c3fb27SDimitry Andric     }
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric     // Don't forward COPYs of reserved regs unless they are constant.
7270b57cec5SDimitry Andric     if (MRI->isReserved(CopySrcReg) && !MRI->isConstantPhysReg(CopySrcReg))
7280b57cec5SDimitry Andric       continue;
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric     if (!isForwardableRegClassCopy(*Copy, MI, OpIdx))
7310b57cec5SDimitry Andric       continue;
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric     if (hasImplicitOverlap(MI, MOUse))
7340b57cec5SDimitry Andric       continue;
7350b57cec5SDimitry Andric 
736480093f4SDimitry Andric     // Check that the instruction is not a copy that partially overwrites the
737480093f4SDimitry Andric     // original copy source that we are about to use. The tracker mechanism
738480093f4SDimitry Andric     // cannot cope with that.
73981ad6265SDimitry Andric     if (isCopyInstr(MI, *TII, UseCopyInstr) &&
74081ad6265SDimitry Andric         MI.modifiesRegister(CopySrcReg, TRI) &&
741*0fca6ea1SDimitry Andric         !MI.definesRegister(CopySrcReg, /*TRI=*/nullptr)) {
742480093f4SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Copy source overlap with dest in " << MI);
743480093f4SDimitry Andric       continue;
744480093f4SDimitry Andric     }
745480093f4SDimitry Andric 
7460b57cec5SDimitry Andric     if (!DebugCounter::shouldExecute(FwdCounter)) {
7470b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n  "
7480b57cec5SDimitry Andric                         << MI);
7490b57cec5SDimitry Andric       continue;
7500b57cec5SDimitry Andric     }
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
75306c3fb27SDimitry Andric                       << "\n     with " << printReg(ForwardedReg, TRI)
7540b57cec5SDimitry Andric                       << "\n     in " << MI << "     from " << *Copy);
7550b57cec5SDimitry Andric 
75606c3fb27SDimitry Andric     MOUse.setReg(ForwardedReg);
75706c3fb27SDimitry Andric 
7580b57cec5SDimitry Andric     if (!CopySrc.isRenamable())
7590b57cec5SDimitry Andric       MOUse.setIsRenamable(false);
760349cc55cSDimitry Andric     MOUse.setIsUndef(CopySrc.isUndef());
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric     // Clear kill markers that may have been invalidated.
7650b57cec5SDimitry Andric     for (MachineInstr &KMI :
7660b57cec5SDimitry Andric          make_range(Copy->getIterator(), std::next(MI.getIterator())))
7670b57cec5SDimitry Andric       KMI.clearRegisterKills(CopySrcReg, TRI);
7680b57cec5SDimitry Andric 
7690b57cec5SDimitry Andric     ++NumCopyForwards;
7700b57cec5SDimitry Andric     Changed = true;
7710b57cec5SDimitry Andric   }
7720b57cec5SDimitry Andric }
7730b57cec5SDimitry Andric 
774480093f4SDimitry Andric void MachineCopyPropagation::ForwardCopyPropagateBlock(MachineBasicBlock &MBB) {
775480093f4SDimitry Andric   LLVM_DEBUG(dbgs() << "MCP: ForwardCopyPropagateBlock " << MBB.getName()
776480093f4SDimitry Andric                     << "\n");
7770b57cec5SDimitry Andric 
778349cc55cSDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
7790b57cec5SDimitry Andric     // Analyze copies (which don't overlap themselves).
780bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
781bdd1243dSDimitry Andric         isCopyInstr(MI, *TII, UseCopyInstr);
78281ad6265SDimitry Andric     if (CopyOperands) {
78381ad6265SDimitry Andric 
78481ad6265SDimitry Andric       Register RegSrc = CopyOperands->Source->getReg();
78581ad6265SDimitry Andric       Register RegDef = CopyOperands->Destination->getReg();
78681ad6265SDimitry Andric 
78781ad6265SDimitry Andric       if (!TRI->regsOverlap(RegDef, RegSrc)) {
78881ad6265SDimitry Andric         assert(RegDef.isPhysical() && RegSrc.isPhysical() &&
7890b57cec5SDimitry Andric               "MachineCopyPropagation should be run after register allocation!");
7900b57cec5SDimitry Andric 
79181ad6265SDimitry Andric         MCRegister Def = RegDef.asMCReg();
79281ad6265SDimitry Andric         MCRegister Src = RegSrc.asMCReg();
793e8d8bef9SDimitry Andric 
7940b57cec5SDimitry Andric         // The two copies cancel out and the source of the first copy
7950b57cec5SDimitry Andric         // hasn't been overridden, eliminate the second one. e.g.
7960b57cec5SDimitry Andric         //  %ecx = COPY %eax
7970b57cec5SDimitry Andric         //  ... nothing clobbered eax.
7980b57cec5SDimitry Andric         //  %eax = COPY %ecx
7990b57cec5SDimitry Andric         // =>
8000b57cec5SDimitry Andric         //  %ecx = COPY %eax
8010b57cec5SDimitry Andric         //
8020b57cec5SDimitry Andric         // or
8030b57cec5SDimitry Andric         //
8040b57cec5SDimitry Andric         //  %ecx = COPY %eax
8050b57cec5SDimitry Andric         //  ... nothing clobbered eax.
8060b57cec5SDimitry Andric         //  %ecx = COPY %eax
8070b57cec5SDimitry Andric         // =>
8080b57cec5SDimitry Andric         //  %ecx = COPY %eax
809349cc55cSDimitry Andric         if (eraseIfRedundant(MI, Def, Src) || eraseIfRedundant(MI, Src, Def))
8100b57cec5SDimitry Andric           continue;
8110b57cec5SDimitry Andric 
812349cc55cSDimitry Andric         forwardUses(MI);
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric         // Src may have been changed by forwardUses()
81581ad6265SDimitry Andric         CopyOperands = isCopyInstr(MI, *TII, UseCopyInstr);
81681ad6265SDimitry Andric         Src = CopyOperands->Source->getReg().asMCReg();
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric         // If Src is defined by a previous copy, the previous copy cannot be
8190b57cec5SDimitry Andric         // eliminated.
820349cc55cSDimitry Andric         ReadRegister(Src, MI, RegularUse);
821349cc55cSDimitry Andric         for (const MachineOperand &MO : MI.implicit_operands()) {
8220b57cec5SDimitry Andric           if (!MO.isReg() || !MO.readsReg())
8230b57cec5SDimitry Andric             continue;
824e8d8bef9SDimitry Andric           MCRegister Reg = MO.getReg().asMCReg();
8250b57cec5SDimitry Andric           if (!Reg)
8260b57cec5SDimitry Andric             continue;
827349cc55cSDimitry Andric           ReadRegister(Reg, MI, RegularUse);
8280b57cec5SDimitry Andric         }
8290b57cec5SDimitry Andric 
830349cc55cSDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI.dump());
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric         // Copy is now a candidate for deletion.
8330b57cec5SDimitry Andric         if (!MRI->isReserved(Def))
834349cc55cSDimitry Andric           MaybeDeadCopies.insert(&MI);
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric         // If 'Def' is previously source of another copy, then this earlier copy's
8370b57cec5SDimitry Andric         // source is no longer available. e.g.
8380b57cec5SDimitry Andric         // %xmm9 = copy %xmm2
8390b57cec5SDimitry Andric         // ...
8400b57cec5SDimitry Andric         // %xmm2 = copy %xmm0
8410b57cec5SDimitry Andric         // ...
8420b57cec5SDimitry Andric         // %xmm2 = copy %xmm9
84381ad6265SDimitry Andric         Tracker.clobberRegister(Def, *TRI, *TII, UseCopyInstr);
844349cc55cSDimitry Andric         for (const MachineOperand &MO : MI.implicit_operands()) {
8450b57cec5SDimitry Andric           if (!MO.isReg() || !MO.isDef())
8460b57cec5SDimitry Andric             continue;
847e8d8bef9SDimitry Andric           MCRegister Reg = MO.getReg().asMCReg();
8480b57cec5SDimitry Andric           if (!Reg)
8490b57cec5SDimitry Andric             continue;
85081ad6265SDimitry Andric           Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
8510b57cec5SDimitry Andric         }
8520b57cec5SDimitry Andric 
85381ad6265SDimitry Andric         Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric         continue;
8560b57cec5SDimitry Andric       }
85781ad6265SDimitry Andric     }
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric     // Clobber any earlyclobber regs first.
860349cc55cSDimitry Andric     for (const MachineOperand &MO : MI.operands())
8610b57cec5SDimitry Andric       if (MO.isReg() && MO.isEarlyClobber()) {
862e8d8bef9SDimitry Andric         MCRegister Reg = MO.getReg().asMCReg();
8630b57cec5SDimitry Andric         // If we have a tied earlyclobber, that means it is also read by this
8640b57cec5SDimitry Andric         // instruction, so we need to make sure we don't remove it as dead
8650b57cec5SDimitry Andric         // later.
8660b57cec5SDimitry Andric         if (MO.isTied())
867349cc55cSDimitry Andric           ReadRegister(Reg, MI, RegularUse);
86881ad6265SDimitry Andric         Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
8690b57cec5SDimitry Andric       }
8700b57cec5SDimitry Andric 
871349cc55cSDimitry Andric     forwardUses(MI);
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric     // Not a copy.
8747a6dacacSDimitry Andric     SmallVector<Register, 4> Defs;
8750b57cec5SDimitry Andric     const MachineOperand *RegMask = nullptr;
876349cc55cSDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
8770b57cec5SDimitry Andric       if (MO.isRegMask())
8780b57cec5SDimitry Andric         RegMask = &MO;
8790b57cec5SDimitry Andric       if (!MO.isReg())
8800b57cec5SDimitry Andric         continue;
8818bcb0991SDimitry Andric       Register Reg = MO.getReg();
8820b57cec5SDimitry Andric       if (!Reg)
8830b57cec5SDimitry Andric         continue;
8840b57cec5SDimitry Andric 
885e8d8bef9SDimitry Andric       assert(!Reg.isVirtual() &&
8860b57cec5SDimitry Andric              "MachineCopyPropagation should be run after register allocation!");
8870b57cec5SDimitry Andric 
8880b57cec5SDimitry Andric       if (MO.isDef() && !MO.isEarlyClobber()) {
889e8d8bef9SDimitry Andric         Defs.push_back(Reg.asMCReg());
8900b57cec5SDimitry Andric         continue;
8918bcb0991SDimitry Andric       } else if (MO.readsReg())
892349cc55cSDimitry Andric         ReadRegister(Reg.asMCReg(), MI, MO.isDebug() ? DebugUse : RegularUse);
8930b57cec5SDimitry Andric     }
8940b57cec5SDimitry Andric 
8950b57cec5SDimitry Andric     // The instruction has a register mask operand which means that it clobbers
8960b57cec5SDimitry Andric     // a large set of registers.  Treat clobbered registers the same way as
8970b57cec5SDimitry Andric     // defined registers.
8980b57cec5SDimitry Andric     if (RegMask) {
8990b57cec5SDimitry Andric       // Erase any MaybeDeadCopies whose destination register is clobbered.
9000b57cec5SDimitry Andric       for (SmallSetVector<MachineInstr *, 8>::iterator DI =
9010b57cec5SDimitry Andric                MaybeDeadCopies.begin();
9020b57cec5SDimitry Andric            DI != MaybeDeadCopies.end();) {
9030b57cec5SDimitry Andric         MachineInstr *MaybeDead = *DI;
904bdd1243dSDimitry Andric         std::optional<DestSourcePair> CopyOperands =
90581ad6265SDimitry Andric             isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
90681ad6265SDimitry Andric         MCRegister Reg = CopyOperands->Destination->getReg().asMCReg();
9070b57cec5SDimitry Andric         assert(!MRI->isReserved(Reg));
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric         if (!RegMask->clobbersPhysReg(Reg)) {
9100b57cec5SDimitry Andric           ++DI;
9110b57cec5SDimitry Andric           continue;
9120b57cec5SDimitry Andric         }
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
9150b57cec5SDimitry Andric                    MaybeDead->dump());
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric         // Make sure we invalidate any entries in the copy maps before erasing
9180b57cec5SDimitry Andric         // the instruction.
91981ad6265SDimitry Andric         Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric         // erase() will return the next valid iterator pointing to the next
9220b57cec5SDimitry Andric         // element after the erased one.
9230b57cec5SDimitry Andric         DI = MaybeDeadCopies.erase(DI);
9240b57cec5SDimitry Andric         MaybeDead->eraseFromParent();
9250b57cec5SDimitry Andric         Changed = true;
9260b57cec5SDimitry Andric         ++NumDeletes;
9270b57cec5SDimitry Andric       }
9280b57cec5SDimitry Andric     }
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric     // Any previous copy definition or reading the Defs is no longer available.
931e8d8bef9SDimitry Andric     for (MCRegister Reg : Defs)
93281ad6265SDimitry Andric       Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
9330b57cec5SDimitry Andric   }
9340b57cec5SDimitry Andric 
935*0fca6ea1SDimitry Andric   bool TracksLiveness = MRI->tracksLiveness();
936*0fca6ea1SDimitry Andric 
937*0fca6ea1SDimitry Andric   // If liveness is tracked, we can use the live-in lists to know which
938*0fca6ea1SDimitry Andric   // copies aren't dead.
939*0fca6ea1SDimitry Andric   if (TracksLiveness)
940*0fca6ea1SDimitry Andric     readSuccessorLiveIns(MBB);
941*0fca6ea1SDimitry Andric 
942*0fca6ea1SDimitry Andric   // If MBB doesn't have succesor, delete copies whose defs are not used.
943*0fca6ea1SDimitry Andric   // If MBB does have successors, we can only delete copies if we are able to
944*0fca6ea1SDimitry Andric   // use liveness information from successors to confirm they are really dead.
945*0fca6ea1SDimitry Andric   if (MBB.succ_empty() || TracksLiveness) {
9460b57cec5SDimitry Andric     for (MachineInstr *MaybeDead : MaybeDeadCopies) {
9470b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
9480b57cec5SDimitry Andric                  MaybeDead->dump());
94981ad6265SDimitry Andric 
950bdd1243dSDimitry Andric       std::optional<DestSourcePair> CopyOperands =
95181ad6265SDimitry Andric           isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
95281ad6265SDimitry Andric       assert(CopyOperands);
95381ad6265SDimitry Andric 
95481ad6265SDimitry Andric       Register SrcReg = CopyOperands->Source->getReg();
95581ad6265SDimitry Andric       Register DestReg = CopyOperands->Destination->getReg();
95681ad6265SDimitry Andric       assert(!MRI->isReserved(DestReg));
9570b57cec5SDimitry Andric 
9588bcb0991SDimitry Andric       // Update matching debug values, if any.
959fe6060f1SDimitry Andric       SmallVector<MachineInstr *> MaybeDeadDbgUsers(
960fe6060f1SDimitry Andric           CopyDbgUsers[MaybeDead].begin(), CopyDbgUsers[MaybeDead].end());
961fe6060f1SDimitry Andric       MRI->updateDbgUsersToReg(DestReg.asMCReg(), SrcReg.asMCReg(),
962fe6060f1SDimitry Andric                                MaybeDeadDbgUsers);
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric       MaybeDead->eraseFromParent();
9650b57cec5SDimitry Andric       Changed = true;
9660b57cec5SDimitry Andric       ++NumDeletes;
9670b57cec5SDimitry Andric     }
9680b57cec5SDimitry Andric   }
9690b57cec5SDimitry Andric 
9700b57cec5SDimitry Andric   MaybeDeadCopies.clear();
9718bcb0991SDimitry Andric   CopyDbgUsers.clear();
9720b57cec5SDimitry Andric   Tracker.clear();
9730b57cec5SDimitry Andric }
9740b57cec5SDimitry Andric 
97506c3fb27SDimitry Andric static bool isBackwardPropagatableCopy(const DestSourcePair &CopyOperands,
976*0fca6ea1SDimitry Andric                                        const MachineRegisterInfo &MRI) {
97706c3fb27SDimitry Andric   Register Def = CopyOperands.Destination->getReg();
97806c3fb27SDimitry Andric   Register Src = CopyOperands.Source->getReg();
979480093f4SDimitry Andric 
980480093f4SDimitry Andric   if (!Def || !Src)
981480093f4SDimitry Andric     return false;
982480093f4SDimitry Andric 
983480093f4SDimitry Andric   if (MRI.isReserved(Def) || MRI.isReserved(Src))
984480093f4SDimitry Andric     return false;
985480093f4SDimitry Andric 
98606c3fb27SDimitry Andric   return CopyOperands.Source->isRenamable() && CopyOperands.Source->isKill();
987480093f4SDimitry Andric }
988480093f4SDimitry Andric 
989480093f4SDimitry Andric void MachineCopyPropagation::propagateDefs(MachineInstr &MI) {
990480093f4SDimitry Andric   if (!Tracker.hasAnyCopies())
991480093f4SDimitry Andric     return;
992480093f4SDimitry Andric 
993480093f4SDimitry Andric   for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx != OpEnd;
994480093f4SDimitry Andric        ++OpIdx) {
995480093f4SDimitry Andric     MachineOperand &MODef = MI.getOperand(OpIdx);
996480093f4SDimitry Andric 
997480093f4SDimitry Andric     if (!MODef.isReg() || MODef.isUse())
998480093f4SDimitry Andric       continue;
999480093f4SDimitry Andric 
1000480093f4SDimitry Andric     // Ignore non-trivial cases.
1001480093f4SDimitry Andric     if (MODef.isTied() || MODef.isUndef() || MODef.isImplicit())
1002480093f4SDimitry Andric       continue;
1003480093f4SDimitry Andric 
1004480093f4SDimitry Andric     if (!MODef.getReg())
1005480093f4SDimitry Andric       continue;
1006480093f4SDimitry Andric 
1007480093f4SDimitry Andric     // We only handle if the register comes from a vreg.
1008480093f4SDimitry Andric     if (!MODef.isRenamable())
1009480093f4SDimitry Andric       continue;
1010480093f4SDimitry Andric 
101181ad6265SDimitry Andric     MachineInstr *Copy = Tracker.findAvailBackwardCopy(
101281ad6265SDimitry Andric         MI, MODef.getReg().asMCReg(), *TRI, *TII, UseCopyInstr);
1013480093f4SDimitry Andric     if (!Copy)
1014480093f4SDimitry Andric       continue;
1015480093f4SDimitry Andric 
1016bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
101781ad6265SDimitry Andric         isCopyInstr(*Copy, *TII, UseCopyInstr);
101881ad6265SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
101981ad6265SDimitry Andric     Register Src = CopyOperands->Source->getReg();
1020480093f4SDimitry Andric 
1021480093f4SDimitry Andric     if (MODef.getReg() != Src)
1022480093f4SDimitry Andric       continue;
1023480093f4SDimitry Andric 
1024480093f4SDimitry Andric     if (!isBackwardPropagatableRegClassCopy(*Copy, MI, OpIdx))
1025480093f4SDimitry Andric       continue;
1026480093f4SDimitry Andric 
1027480093f4SDimitry Andric     if (hasImplicitOverlap(MI, MODef))
1028480093f4SDimitry Andric       continue;
1029480093f4SDimitry Andric 
1030e8d8bef9SDimitry Andric     if (hasOverlappingMultipleDef(MI, MODef, Def))
1031e8d8bef9SDimitry Andric       continue;
1032e8d8bef9SDimitry Andric 
1033480093f4SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MODef.getReg(), TRI)
1034480093f4SDimitry Andric                       << "\n     with " << printReg(Def, TRI) << "\n     in "
1035480093f4SDimitry Andric                       << MI << "     from " << *Copy);
1036480093f4SDimitry Andric 
1037480093f4SDimitry Andric     MODef.setReg(Def);
103881ad6265SDimitry Andric     MODef.setIsRenamable(CopyOperands->Destination->isRenamable());
1039480093f4SDimitry Andric 
1040480093f4SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
1041480093f4SDimitry Andric     MaybeDeadCopies.insert(Copy);
1042480093f4SDimitry Andric     Changed = true;
1043480093f4SDimitry Andric     ++NumCopyBackwardPropagated;
1044480093f4SDimitry Andric   }
1045480093f4SDimitry Andric }
1046480093f4SDimitry Andric 
1047480093f4SDimitry Andric void MachineCopyPropagation::BackwardCopyPropagateBlock(
1048480093f4SDimitry Andric     MachineBasicBlock &MBB) {
1049480093f4SDimitry Andric   LLVM_DEBUG(dbgs() << "MCP: BackwardCopyPropagateBlock " << MBB.getName()
1050480093f4SDimitry Andric                     << "\n");
1051480093f4SDimitry Andric 
10520eae32dcSDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(MBB))) {
1053480093f4SDimitry Andric     // Ignore non-trivial COPYs.
1054bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
1055bdd1243dSDimitry Andric         isCopyInstr(MI, *TII, UseCopyInstr);
105681ad6265SDimitry Andric     if (CopyOperands && MI.getNumOperands() == 2) {
105781ad6265SDimitry Andric       Register DefReg = CopyOperands->Destination->getReg();
105881ad6265SDimitry Andric       Register SrcReg = CopyOperands->Source->getReg();
1059480093f4SDimitry Andric 
106081ad6265SDimitry Andric       if (!TRI->regsOverlap(DefReg, SrcReg)) {
1061480093f4SDimitry Andric         // Unlike forward cp, we don't invoke propagateDefs here,
1062480093f4SDimitry Andric         // just let forward cp do COPY-to-COPY propagation.
1063*0fca6ea1SDimitry Andric         if (isBackwardPropagatableCopy(*CopyOperands, *MRI)) {
106406c3fb27SDimitry Andric           Tracker.invalidateRegister(SrcReg.asMCReg(), *TRI, *TII,
106506c3fb27SDimitry Andric                                      UseCopyInstr);
106606c3fb27SDimitry Andric           Tracker.invalidateRegister(DefReg.asMCReg(), *TRI, *TII,
106706c3fb27SDimitry Andric                                      UseCopyInstr);
106881ad6265SDimitry Andric           Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
1069480093f4SDimitry Andric           continue;
1070480093f4SDimitry Andric         }
1071480093f4SDimitry Andric       }
107281ad6265SDimitry Andric     }
1073480093f4SDimitry Andric 
1074480093f4SDimitry Andric     // Invalidate any earlyclobber regs first.
10750eae32dcSDimitry Andric     for (const MachineOperand &MO : MI.operands())
1076480093f4SDimitry Andric       if (MO.isReg() && MO.isEarlyClobber()) {
1077e8d8bef9SDimitry Andric         MCRegister Reg = MO.getReg().asMCReg();
1078480093f4SDimitry Andric         if (!Reg)
1079480093f4SDimitry Andric           continue;
108081ad6265SDimitry Andric         Tracker.invalidateRegister(Reg, *TRI, *TII, UseCopyInstr);
1081480093f4SDimitry Andric       }
1082480093f4SDimitry Andric 
10830eae32dcSDimitry Andric     propagateDefs(MI);
10840eae32dcSDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
1085480093f4SDimitry Andric       if (!MO.isReg())
1086480093f4SDimitry Andric         continue;
1087480093f4SDimitry Andric 
1088480093f4SDimitry Andric       if (!MO.getReg())
1089480093f4SDimitry Andric         continue;
1090480093f4SDimitry Andric 
1091480093f4SDimitry Andric       if (MO.isDef())
109281ad6265SDimitry Andric         Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
109381ad6265SDimitry Andric                                    UseCopyInstr);
1094480093f4SDimitry Andric 
1095fe6060f1SDimitry Andric       if (MO.readsReg()) {
1096fe6060f1SDimitry Andric         if (MO.isDebug()) {
1097fe6060f1SDimitry Andric           //  Check if the register in the debug instruction is utilized
1098fe6060f1SDimitry Andric           // in a copy instruction, so we can update the debug info if the
1099fe6060f1SDimitry Andric           // register is changed.
110006c3fb27SDimitry Andric           for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
110106c3fb27SDimitry Andric             if (auto *Copy = Tracker.findCopyDefViaUnit(Unit, *TRI)) {
11020eae32dcSDimitry Andric               CopyDbgUsers[Copy].insert(&MI);
1103fe6060f1SDimitry Andric             }
1104fe6060f1SDimitry Andric           }
1105fe6060f1SDimitry Andric         } else {
110681ad6265SDimitry Andric           Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
110781ad6265SDimitry Andric                                      UseCopyInstr);
1108480093f4SDimitry Andric         }
1109480093f4SDimitry Andric       }
1110fe6060f1SDimitry Andric     }
1111fe6060f1SDimitry Andric   }
1112480093f4SDimitry Andric 
1113480093f4SDimitry Andric   for (auto *Copy : MaybeDeadCopies) {
1114bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
111581ad6265SDimitry Andric         isCopyInstr(*Copy, *TII, UseCopyInstr);
111681ad6265SDimitry Andric     Register Src = CopyOperands->Source->getReg();
111781ad6265SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
1118fe6060f1SDimitry Andric     SmallVector<MachineInstr *> MaybeDeadDbgUsers(CopyDbgUsers[Copy].begin(),
1119fe6060f1SDimitry Andric                                                   CopyDbgUsers[Copy].end());
1120fe6060f1SDimitry Andric 
1121fe6060f1SDimitry Andric     MRI->updateDbgUsersToReg(Src.asMCReg(), Def.asMCReg(), MaybeDeadDbgUsers);
1122480093f4SDimitry Andric     Copy->eraseFromParent();
1123480093f4SDimitry Andric     ++NumDeletes;
1124480093f4SDimitry Andric   }
1125480093f4SDimitry Andric 
1126480093f4SDimitry Andric   MaybeDeadCopies.clear();
1127480093f4SDimitry Andric   CopyDbgUsers.clear();
1128480093f4SDimitry Andric   Tracker.clear();
1129480093f4SDimitry Andric }
1130480093f4SDimitry Andric 
113106c3fb27SDimitry Andric static void LLVM_ATTRIBUTE_UNUSED printSpillReloadChain(
113206c3fb27SDimitry Andric     DenseMap<MachineInstr *, SmallVector<MachineInstr *>> &SpillChain,
113306c3fb27SDimitry Andric     DenseMap<MachineInstr *, SmallVector<MachineInstr *>> &ReloadChain,
113406c3fb27SDimitry Andric     MachineInstr *Leader) {
113506c3fb27SDimitry Andric   auto &SC = SpillChain[Leader];
113606c3fb27SDimitry Andric   auto &RC = ReloadChain[Leader];
113706c3fb27SDimitry Andric   for (auto I = SC.rbegin(), E = SC.rend(); I != E; ++I)
113806c3fb27SDimitry Andric     (*I)->dump();
113906c3fb27SDimitry Andric   for (MachineInstr *MI : RC)
114006c3fb27SDimitry Andric     MI->dump();
114106c3fb27SDimitry Andric }
114206c3fb27SDimitry Andric 
114306c3fb27SDimitry Andric // Remove spill-reload like copy chains. For example
114406c3fb27SDimitry Andric // r0 = COPY r1
114506c3fb27SDimitry Andric // r1 = COPY r2
114606c3fb27SDimitry Andric // r2 = COPY r3
114706c3fb27SDimitry Andric // r3 = COPY r4
114806c3fb27SDimitry Andric // <def-use r4>
114906c3fb27SDimitry Andric // r4 = COPY r3
115006c3fb27SDimitry Andric // r3 = COPY r2
115106c3fb27SDimitry Andric // r2 = COPY r1
115206c3fb27SDimitry Andric // r1 = COPY r0
115306c3fb27SDimitry Andric // will be folded into
115406c3fb27SDimitry Andric // r0 = COPY r1
115506c3fb27SDimitry Andric // r1 = COPY r4
115606c3fb27SDimitry Andric // <def-use r4>
115706c3fb27SDimitry Andric // r4 = COPY r1
115806c3fb27SDimitry Andric // r1 = COPY r0
115906c3fb27SDimitry Andric // TODO: Currently we don't track usage of r0 outside the chain, so we
116006c3fb27SDimitry Andric // conservatively keep its value as it was before the rewrite.
116106c3fb27SDimitry Andric //
116206c3fb27SDimitry Andric // The algorithm is trying to keep
116306c3fb27SDimitry Andric // property#1: No Def of spill COPY in the chain is used or defined until the
116406c3fb27SDimitry Andric // paired reload COPY in the chain uses the Def.
116506c3fb27SDimitry Andric //
116606c3fb27SDimitry Andric // property#2: NO Source of COPY in the chain is used or defined until the next
116706c3fb27SDimitry Andric // COPY in the chain defines the Source, except the innermost spill-reload
116806c3fb27SDimitry Andric // pair.
116906c3fb27SDimitry Andric //
117006c3fb27SDimitry Andric // The algorithm is conducted by checking every COPY inside the MBB, assuming
117106c3fb27SDimitry Andric // the COPY is a reload COPY, then try to find paired spill COPY by searching
117206c3fb27SDimitry Andric // the COPY defines the Src of the reload COPY backward. If such pair is found,
117306c3fb27SDimitry Andric // it either belongs to an existing chain or a new chain depends on
117406c3fb27SDimitry Andric // last available COPY uses the Def of the reload COPY.
117506c3fb27SDimitry Andric // Implementation notes, we use CopyTracker::findLastDefCopy(Reg, ...) to find
117606c3fb27SDimitry Andric // out last COPY that defines Reg; we use CopyTracker::findLastUseCopy(Reg, ...)
117706c3fb27SDimitry Andric // to find out last COPY that uses Reg. When we are encountered with a Non-COPY
117806c3fb27SDimitry Andric // instruction, we check registers in the operands of this instruction. If this
117906c3fb27SDimitry Andric // Reg is defined by a COPY, we untrack this Reg via
118006c3fb27SDimitry Andric // CopyTracker::clobberRegister(Reg, ...).
118106c3fb27SDimitry Andric void MachineCopyPropagation::EliminateSpillageCopies(MachineBasicBlock &MBB) {
118206c3fb27SDimitry Andric   // ChainLeader maps MI inside a spill-reload chain to its innermost reload COPY.
118306c3fb27SDimitry Andric   // Thus we can track if a MI belongs to an existing spill-reload chain.
118406c3fb27SDimitry Andric   DenseMap<MachineInstr *, MachineInstr *> ChainLeader;
118506c3fb27SDimitry Andric   // SpillChain maps innermost reload COPY of a spill-reload chain to a sequence
118606c3fb27SDimitry Andric   // of COPYs that forms spills of a spill-reload chain.
118706c3fb27SDimitry Andric   // ReloadChain maps innermost reload COPY of a spill-reload chain to a
118806c3fb27SDimitry Andric   // sequence of COPYs that forms reloads of a spill-reload chain.
118906c3fb27SDimitry Andric   DenseMap<MachineInstr *, SmallVector<MachineInstr *>> SpillChain, ReloadChain;
119006c3fb27SDimitry Andric   // If a COPY's Source has use or def until next COPY defines the Source,
119106c3fb27SDimitry Andric   // we put the COPY in this set to keep property#2.
119206c3fb27SDimitry Andric   DenseSet<const MachineInstr *> CopySourceInvalid;
119306c3fb27SDimitry Andric 
119406c3fb27SDimitry Andric   auto TryFoldSpillageCopies =
119506c3fb27SDimitry Andric       [&, this](const SmallVectorImpl<MachineInstr *> &SC,
119606c3fb27SDimitry Andric                 const SmallVectorImpl<MachineInstr *> &RC) {
119706c3fb27SDimitry Andric         assert(SC.size() == RC.size() && "Spill-reload should be paired");
119806c3fb27SDimitry Andric 
119906c3fb27SDimitry Andric         // We need at least 3 pairs of copies for the transformation to apply,
120006c3fb27SDimitry Andric         // because the first outermost pair cannot be removed since we don't
120106c3fb27SDimitry Andric         // recolor outside of the chain and that we need at least one temporary
120206c3fb27SDimitry Andric         // spill slot to shorten the chain. If we only have a chain of two
120306c3fb27SDimitry Andric         // pairs, we already have the shortest sequence this code can handle:
120406c3fb27SDimitry Andric         // the outermost pair for the temporary spill slot, and the pair that
120506c3fb27SDimitry Andric         // use that temporary spill slot for the other end of the chain.
120606c3fb27SDimitry Andric         // TODO: We might be able to simplify to one spill-reload pair if collecting
120706c3fb27SDimitry Andric         // more infomation about the outermost COPY.
120806c3fb27SDimitry Andric         if (SC.size() <= 2)
120906c3fb27SDimitry Andric           return;
121006c3fb27SDimitry Andric 
121106c3fb27SDimitry Andric         // If violate property#2, we don't fold the chain.
12125f757f3fSDimitry Andric         for (const MachineInstr *Spill : drop_begin(SC))
121306c3fb27SDimitry Andric           if (CopySourceInvalid.count(Spill))
121406c3fb27SDimitry Andric             return;
121506c3fb27SDimitry Andric 
12165f757f3fSDimitry Andric         for (const MachineInstr *Reload : drop_end(RC))
121706c3fb27SDimitry Andric           if (CopySourceInvalid.count(Reload))
121806c3fb27SDimitry Andric             return;
121906c3fb27SDimitry Andric 
122006c3fb27SDimitry Andric         auto CheckCopyConstraint = [this](Register Def, Register Src) {
122106c3fb27SDimitry Andric           for (const TargetRegisterClass *RC : TRI->regclasses()) {
122206c3fb27SDimitry Andric             if (RC->contains(Def) && RC->contains(Src))
122306c3fb27SDimitry Andric               return true;
122406c3fb27SDimitry Andric           }
122506c3fb27SDimitry Andric           return false;
122606c3fb27SDimitry Andric         };
122706c3fb27SDimitry Andric 
122806c3fb27SDimitry Andric         auto UpdateReg = [](MachineInstr *MI, const MachineOperand *Old,
122906c3fb27SDimitry Andric                             const MachineOperand *New) {
123006c3fb27SDimitry Andric           for (MachineOperand &MO : MI->operands()) {
123106c3fb27SDimitry Andric             if (&MO == Old)
123206c3fb27SDimitry Andric               MO.setReg(New->getReg());
123306c3fb27SDimitry Andric           }
123406c3fb27SDimitry Andric         };
123506c3fb27SDimitry Andric 
123606c3fb27SDimitry Andric         std::optional<DestSourcePair> InnerMostSpillCopy =
123706c3fb27SDimitry Andric             isCopyInstr(*SC[0], *TII, UseCopyInstr);
123806c3fb27SDimitry Andric         std::optional<DestSourcePair> OuterMostSpillCopy =
123906c3fb27SDimitry Andric             isCopyInstr(*SC.back(), *TII, UseCopyInstr);
124006c3fb27SDimitry Andric         std::optional<DestSourcePair> InnerMostReloadCopy =
124106c3fb27SDimitry Andric             isCopyInstr(*RC[0], *TII, UseCopyInstr);
124206c3fb27SDimitry Andric         std::optional<DestSourcePair> OuterMostReloadCopy =
124306c3fb27SDimitry Andric             isCopyInstr(*RC.back(), *TII, UseCopyInstr);
124406c3fb27SDimitry Andric         if (!CheckCopyConstraint(OuterMostSpillCopy->Source->getReg(),
124506c3fb27SDimitry Andric                                  InnerMostSpillCopy->Source->getReg()) ||
124606c3fb27SDimitry Andric             !CheckCopyConstraint(InnerMostReloadCopy->Destination->getReg(),
124706c3fb27SDimitry Andric                                  OuterMostReloadCopy->Destination->getReg()))
124806c3fb27SDimitry Andric           return;
124906c3fb27SDimitry Andric 
125006c3fb27SDimitry Andric         SpillageChainsLength += SC.size() + RC.size();
125106c3fb27SDimitry Andric         NumSpillageChains += 1;
125206c3fb27SDimitry Andric         UpdateReg(SC[0], InnerMostSpillCopy->Destination,
125306c3fb27SDimitry Andric                   OuterMostSpillCopy->Source);
125406c3fb27SDimitry Andric         UpdateReg(RC[0], InnerMostReloadCopy->Source,
125506c3fb27SDimitry Andric                   OuterMostReloadCopy->Destination);
125606c3fb27SDimitry Andric 
125706c3fb27SDimitry Andric         for (size_t I = 1; I < SC.size() - 1; ++I) {
125806c3fb27SDimitry Andric           SC[I]->eraseFromParent();
125906c3fb27SDimitry Andric           RC[I]->eraseFromParent();
126006c3fb27SDimitry Andric           NumDeletes += 2;
126106c3fb27SDimitry Andric         }
126206c3fb27SDimitry Andric       };
126306c3fb27SDimitry Andric 
126406c3fb27SDimitry Andric   auto IsFoldableCopy = [this](const MachineInstr &MaybeCopy) {
126506c3fb27SDimitry Andric     if (MaybeCopy.getNumImplicitOperands() > 0)
126606c3fb27SDimitry Andric       return false;
126706c3fb27SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
126806c3fb27SDimitry Andric         isCopyInstr(MaybeCopy, *TII, UseCopyInstr);
126906c3fb27SDimitry Andric     if (!CopyOperands)
127006c3fb27SDimitry Andric       return false;
127106c3fb27SDimitry Andric     Register Src = CopyOperands->Source->getReg();
127206c3fb27SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
127306c3fb27SDimitry Andric     return Src && Def && !TRI->regsOverlap(Src, Def) &&
127406c3fb27SDimitry Andric            CopyOperands->Source->isRenamable() &&
127506c3fb27SDimitry Andric            CopyOperands->Destination->isRenamable();
127606c3fb27SDimitry Andric   };
127706c3fb27SDimitry Andric 
127806c3fb27SDimitry Andric   auto IsSpillReloadPair = [&, this](const MachineInstr &Spill,
127906c3fb27SDimitry Andric                                      const MachineInstr &Reload) {
128006c3fb27SDimitry Andric     if (!IsFoldableCopy(Spill) || !IsFoldableCopy(Reload))
128106c3fb27SDimitry Andric       return false;
128206c3fb27SDimitry Andric     std::optional<DestSourcePair> SpillCopy =
128306c3fb27SDimitry Andric         isCopyInstr(Spill, *TII, UseCopyInstr);
128406c3fb27SDimitry Andric     std::optional<DestSourcePair> ReloadCopy =
128506c3fb27SDimitry Andric         isCopyInstr(Reload, *TII, UseCopyInstr);
128606c3fb27SDimitry Andric     if (!SpillCopy || !ReloadCopy)
128706c3fb27SDimitry Andric       return false;
128806c3fb27SDimitry Andric     return SpillCopy->Source->getReg() == ReloadCopy->Destination->getReg() &&
128906c3fb27SDimitry Andric            SpillCopy->Destination->getReg() == ReloadCopy->Source->getReg();
129006c3fb27SDimitry Andric   };
129106c3fb27SDimitry Andric 
129206c3fb27SDimitry Andric   auto IsChainedCopy = [&, this](const MachineInstr &Prev,
129306c3fb27SDimitry Andric                                  const MachineInstr &Current) {
129406c3fb27SDimitry Andric     if (!IsFoldableCopy(Prev) || !IsFoldableCopy(Current))
129506c3fb27SDimitry Andric       return false;
129606c3fb27SDimitry Andric     std::optional<DestSourcePair> PrevCopy =
129706c3fb27SDimitry Andric         isCopyInstr(Prev, *TII, UseCopyInstr);
129806c3fb27SDimitry Andric     std::optional<DestSourcePair> CurrentCopy =
129906c3fb27SDimitry Andric         isCopyInstr(Current, *TII, UseCopyInstr);
130006c3fb27SDimitry Andric     if (!PrevCopy || !CurrentCopy)
130106c3fb27SDimitry Andric       return false;
130206c3fb27SDimitry Andric     return PrevCopy->Source->getReg() == CurrentCopy->Destination->getReg();
130306c3fb27SDimitry Andric   };
130406c3fb27SDimitry Andric 
130506c3fb27SDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
130606c3fb27SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
130706c3fb27SDimitry Andric         isCopyInstr(MI, *TII, UseCopyInstr);
130806c3fb27SDimitry Andric 
130906c3fb27SDimitry Andric     // Update track information via non-copy instruction.
131006c3fb27SDimitry Andric     SmallSet<Register, 8> RegsToClobber;
131106c3fb27SDimitry Andric     if (!CopyOperands) {
131206c3fb27SDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
131306c3fb27SDimitry Andric         if (!MO.isReg())
131406c3fb27SDimitry Andric           continue;
131506c3fb27SDimitry Andric         Register Reg = MO.getReg();
131606c3fb27SDimitry Andric         if (!Reg)
131706c3fb27SDimitry Andric           continue;
131806c3fb27SDimitry Andric         MachineInstr *LastUseCopy =
131906c3fb27SDimitry Andric             Tracker.findLastSeenUseInCopy(Reg.asMCReg(), *TRI);
132006c3fb27SDimitry Andric         if (LastUseCopy) {
132106c3fb27SDimitry Andric           LLVM_DEBUG(dbgs() << "MCP: Copy source of\n");
132206c3fb27SDimitry Andric           LLVM_DEBUG(LastUseCopy->dump());
132306c3fb27SDimitry Andric           LLVM_DEBUG(dbgs() << "might be invalidated by\n");
132406c3fb27SDimitry Andric           LLVM_DEBUG(MI.dump());
132506c3fb27SDimitry Andric           CopySourceInvalid.insert(LastUseCopy);
132606c3fb27SDimitry Andric         }
132706c3fb27SDimitry Andric         // Must be noted Tracker.clobberRegister(Reg, ...) removes tracking of
132806c3fb27SDimitry Andric         // Reg, i.e, COPY that defines Reg is removed from the mapping as well
132906c3fb27SDimitry Andric         // as marking COPYs that uses Reg unavailable.
133006c3fb27SDimitry Andric         // We don't invoke CopyTracker::clobberRegister(Reg, ...) if Reg is not
133106c3fb27SDimitry Andric         // defined by a previous COPY, since we don't want to make COPYs uses
133206c3fb27SDimitry Andric         // Reg unavailable.
133306c3fb27SDimitry Andric         if (Tracker.findLastSeenDefInCopy(MI, Reg.asMCReg(), *TRI, *TII,
133406c3fb27SDimitry Andric                                     UseCopyInstr))
133506c3fb27SDimitry Andric           // Thus we can keep the property#1.
133606c3fb27SDimitry Andric           RegsToClobber.insert(Reg);
133706c3fb27SDimitry Andric       }
133806c3fb27SDimitry Andric       for (Register Reg : RegsToClobber) {
133906c3fb27SDimitry Andric         Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
134006c3fb27SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Reg, TRI)
134106c3fb27SDimitry Andric                           << "\n");
134206c3fb27SDimitry Andric       }
134306c3fb27SDimitry Andric       continue;
134406c3fb27SDimitry Andric     }
134506c3fb27SDimitry Andric 
134606c3fb27SDimitry Andric     Register Src = CopyOperands->Source->getReg();
134706c3fb27SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
134806c3fb27SDimitry Andric     // Check if we can find a pair spill-reload copy.
134906c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: Searching paired spill for reload: ");
135006c3fb27SDimitry Andric     LLVM_DEBUG(MI.dump());
135106c3fb27SDimitry Andric     MachineInstr *MaybeSpill =
135206c3fb27SDimitry Andric         Tracker.findLastSeenDefInCopy(MI, Src.asMCReg(), *TRI, *TII, UseCopyInstr);
135306c3fb27SDimitry Andric     bool MaybeSpillIsChained = ChainLeader.count(MaybeSpill);
135406c3fb27SDimitry Andric     if (!MaybeSpillIsChained && MaybeSpill &&
135506c3fb27SDimitry Andric         IsSpillReloadPair(*MaybeSpill, MI)) {
135606c3fb27SDimitry Andric       // Check if we already have an existing chain. Now we have a
135706c3fb27SDimitry Andric       // spill-reload pair.
135806c3fb27SDimitry Andric       // L2: r2 = COPY r3
135906c3fb27SDimitry Andric       // L5: r3 = COPY r2
136006c3fb27SDimitry Andric       // Looking for a valid COPY before L5 which uses r3.
136106c3fb27SDimitry Andric       // This can be serverial cases.
136206c3fb27SDimitry Andric       // Case #1:
136306c3fb27SDimitry Andric       // No COPY is found, which can be r3 is def-use between (L2, L5), we
136406c3fb27SDimitry Andric       // create a new chain for L2 and L5.
136506c3fb27SDimitry Andric       // Case #2:
136606c3fb27SDimitry Andric       // L2: r2 = COPY r3
136706c3fb27SDimitry Andric       // L5: r3 = COPY r2
136806c3fb27SDimitry Andric       // Such COPY is found and is L2, we create a new chain for L2 and L5.
136906c3fb27SDimitry Andric       // Case #3:
137006c3fb27SDimitry Andric       // L2: r2 = COPY r3
137106c3fb27SDimitry Andric       // L3: r1 = COPY r3
137206c3fb27SDimitry Andric       // L5: r3 = COPY r2
137306c3fb27SDimitry Andric       // we create a new chain for L2 and L5.
137406c3fb27SDimitry Andric       // Case #4:
137506c3fb27SDimitry Andric       // L2: r2 = COPY r3
137606c3fb27SDimitry Andric       // L3: r1 = COPY r3
137706c3fb27SDimitry Andric       // L4: r3 = COPY r1
137806c3fb27SDimitry Andric       // L5: r3 = COPY r2
137906c3fb27SDimitry Andric       // Such COPY won't be found since L4 defines r3. we create a new chain
138006c3fb27SDimitry Andric       // for L2 and L5.
138106c3fb27SDimitry Andric       // Case #5:
138206c3fb27SDimitry Andric       // L2: r2 = COPY r3
138306c3fb27SDimitry Andric       // L3: r3 = COPY r1
138406c3fb27SDimitry Andric       // L4: r1 = COPY r3
138506c3fb27SDimitry Andric       // L5: r3 = COPY r2
138606c3fb27SDimitry Andric       // COPY is found and is L4 which belongs to an existing chain, we add
138706c3fb27SDimitry Andric       // L2 and L5 to this chain.
138806c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Found spill: ");
138906c3fb27SDimitry Andric       LLVM_DEBUG(MaybeSpill->dump());
139006c3fb27SDimitry Andric       MachineInstr *MaybePrevReload =
139106c3fb27SDimitry Andric           Tracker.findLastSeenUseInCopy(Def.asMCReg(), *TRI);
139206c3fb27SDimitry Andric       auto Leader = ChainLeader.find(MaybePrevReload);
139306c3fb27SDimitry Andric       MachineInstr *L = nullptr;
139406c3fb27SDimitry Andric       if (Leader == ChainLeader.end() ||
139506c3fb27SDimitry Andric           (MaybePrevReload && !IsChainedCopy(*MaybePrevReload, MI))) {
139606c3fb27SDimitry Andric         L = &MI;
139706c3fb27SDimitry Andric         assert(!SpillChain.count(L) &&
139806c3fb27SDimitry Andric                "SpillChain should not have contained newly found chain");
139906c3fb27SDimitry Andric       } else {
140006c3fb27SDimitry Andric         assert(MaybePrevReload &&
140106c3fb27SDimitry Andric                "Found a valid leader through nullptr should not happend");
140206c3fb27SDimitry Andric         L = Leader->second;
140306c3fb27SDimitry Andric         assert(SpillChain[L].size() > 0 &&
140406c3fb27SDimitry Andric                "Existing chain's length should be larger than zero");
140506c3fb27SDimitry Andric       }
140606c3fb27SDimitry Andric       assert(!ChainLeader.count(&MI) && !ChainLeader.count(MaybeSpill) &&
140706c3fb27SDimitry Andric              "Newly found paired spill-reload should not belong to any chain "
140806c3fb27SDimitry Andric              "at this point");
140906c3fb27SDimitry Andric       ChainLeader.insert({MaybeSpill, L});
141006c3fb27SDimitry Andric       ChainLeader.insert({&MI, L});
141106c3fb27SDimitry Andric       SpillChain[L].push_back(MaybeSpill);
141206c3fb27SDimitry Andric       ReloadChain[L].push_back(&MI);
141306c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Chain " << L << " now is:\n");
141406c3fb27SDimitry Andric       LLVM_DEBUG(printSpillReloadChain(SpillChain, ReloadChain, L));
141506c3fb27SDimitry Andric     } else if (MaybeSpill && !MaybeSpillIsChained) {
141606c3fb27SDimitry Andric       // MaybeSpill is unable to pair with MI. That's to say adding MI makes
141706c3fb27SDimitry Andric       // the chain invalid.
141806c3fb27SDimitry Andric       // The COPY defines Src is no longer considered as a candidate of a
141906c3fb27SDimitry Andric       // valid chain. Since we expect the Def of a spill copy isn't used by
142006c3fb27SDimitry Andric       // any COPY instruction until a reload copy. For example:
142106c3fb27SDimitry Andric       // L1: r1 = COPY r2
142206c3fb27SDimitry Andric       // L2: r3 = COPY r1
142306c3fb27SDimitry Andric       // If we later have
142406c3fb27SDimitry Andric       // L1: r1 = COPY r2
142506c3fb27SDimitry Andric       // L2: r3 = COPY r1
142606c3fb27SDimitry Andric       // L3: r2 = COPY r1
142706c3fb27SDimitry Andric       // L1 and L3 can't be a valid spill-reload pair.
142806c3fb27SDimitry Andric       // Thus we keep the property#1.
142906c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Not paired spill-reload:\n");
143006c3fb27SDimitry Andric       LLVM_DEBUG(MaybeSpill->dump());
143106c3fb27SDimitry Andric       LLVM_DEBUG(MI.dump());
143206c3fb27SDimitry Andric       Tracker.clobberRegister(Src.asMCReg(), *TRI, *TII, UseCopyInstr);
143306c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Src, TRI)
143406c3fb27SDimitry Andric                         << "\n");
143506c3fb27SDimitry Andric     }
143606c3fb27SDimitry Andric     Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
143706c3fb27SDimitry Andric   }
143806c3fb27SDimitry Andric 
143906c3fb27SDimitry Andric   for (auto I = SpillChain.begin(), E = SpillChain.end(); I != E; ++I) {
144006c3fb27SDimitry Andric     auto &SC = I->second;
144106c3fb27SDimitry Andric     assert(ReloadChain.count(I->first) &&
144206c3fb27SDimitry Andric            "Reload chain of the same leader should exist");
144306c3fb27SDimitry Andric     auto &RC = ReloadChain[I->first];
144406c3fb27SDimitry Andric     TryFoldSpillageCopies(SC, RC);
144506c3fb27SDimitry Andric   }
144606c3fb27SDimitry Andric 
144706c3fb27SDimitry Andric   MaybeDeadCopies.clear();
144806c3fb27SDimitry Andric   CopyDbgUsers.clear();
144906c3fb27SDimitry Andric   Tracker.clear();
145006c3fb27SDimitry Andric }
145106c3fb27SDimitry Andric 
14520b57cec5SDimitry Andric bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
14530b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()))
14540b57cec5SDimitry Andric     return false;
14550b57cec5SDimitry Andric 
145606c3fb27SDimitry Andric   bool isSpillageCopyElimEnabled = false;
145706c3fb27SDimitry Andric   switch (EnableSpillageCopyElimination) {
145806c3fb27SDimitry Andric   case cl::BOU_UNSET:
145906c3fb27SDimitry Andric     isSpillageCopyElimEnabled =
146006c3fb27SDimitry Andric         MF.getSubtarget().enableSpillageCopyElimination();
146106c3fb27SDimitry Andric     break;
146206c3fb27SDimitry Andric   case cl::BOU_TRUE:
146306c3fb27SDimitry Andric     isSpillageCopyElimEnabled = true;
146406c3fb27SDimitry Andric     break;
146506c3fb27SDimitry Andric   case cl::BOU_FALSE:
146606c3fb27SDimitry Andric     isSpillageCopyElimEnabled = false;
146706c3fb27SDimitry Andric     break;
146806c3fb27SDimitry Andric   }
146906c3fb27SDimitry Andric 
14700b57cec5SDimitry Andric   Changed = false;
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric   TRI = MF.getSubtarget().getRegisterInfo();
14730b57cec5SDimitry Andric   TII = MF.getSubtarget().getInstrInfo();
14740b57cec5SDimitry Andric   MRI = &MF.getRegInfo();
14750b57cec5SDimitry Andric 
1476480093f4SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
147706c3fb27SDimitry Andric     if (isSpillageCopyElimEnabled)
147806c3fb27SDimitry Andric       EliminateSpillageCopies(MBB);
1479480093f4SDimitry Andric     BackwardCopyPropagateBlock(MBB);
1480480093f4SDimitry Andric     ForwardCopyPropagateBlock(MBB);
1481480093f4SDimitry Andric   }
14820b57cec5SDimitry Andric 
14830b57cec5SDimitry Andric   return Changed;
14840b57cec5SDimitry Andric }
148581ad6265SDimitry Andric 
148681ad6265SDimitry Andric MachineFunctionPass *
148781ad6265SDimitry Andric llvm::createMachineCopyPropagationPass(bool UseCopyInstr = false) {
148881ad6265SDimitry Andric   return new MachineCopyPropagation(UseCopyInstr);
148981ad6265SDimitry Andric }
1490