xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/MachineCopyPropagation.cpp (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
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"
680b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
690b57cec5SDimitry Andric #include "llvm/Pass.h"
700b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
710b57cec5SDimitry Andric #include "llvm/Support/DebugCounter.h"
720b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
730b57cec5SDimitry Andric #include <cassert>
740b57cec5SDimitry Andric #include <iterator>
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric using namespace llvm;
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric #define DEBUG_TYPE "machine-cp"
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric STATISTIC(NumDeletes, "Number of dead copies deleted");
810b57cec5SDimitry Andric STATISTIC(NumCopyForwards, "Number of copy uses forwarded");
82480093f4SDimitry Andric STATISTIC(NumCopyBackwardPropagated, "Number of copy defs backward propagated");
8306c3fb27SDimitry Andric STATISTIC(SpillageChainsLength, "Length of spillage chains");
8406c3fb27SDimitry Andric STATISTIC(NumSpillageChains, "Number of spillage chains");
850b57cec5SDimitry Andric DEBUG_COUNTER(FwdCounter, "machine-cp-fwd",
860b57cec5SDimitry Andric               "Controls which register COPYs are forwarded");
870b57cec5SDimitry Andric 
8881ad6265SDimitry Andric static cl::opt<bool> MCPUseCopyInstr("mcp-use-is-copy-instr", cl::init(false),
8981ad6265SDimitry Andric                                      cl::Hidden);
9006c3fb27SDimitry Andric static cl::opt<cl::boolOrDefault>
9106c3fb27SDimitry Andric     EnableSpillageCopyElimination("enable-spill-copy-elim", cl::Hidden);
9281ad6265SDimitry Andric 
930b57cec5SDimitry Andric namespace {
940b57cec5SDimitry Andric 
95bdd1243dSDimitry Andric static std::optional<DestSourcePair> isCopyInstr(const MachineInstr &MI,
9681ad6265SDimitry Andric                                                  const TargetInstrInfo &TII,
9781ad6265SDimitry Andric                                                  bool UseCopyInstr) {
9881ad6265SDimitry Andric   if (UseCopyInstr)
9981ad6265SDimitry Andric     return TII.isCopyInstr(MI);
10081ad6265SDimitry Andric 
10181ad6265SDimitry Andric   if (MI.isCopy())
102bdd1243dSDimitry Andric     return std::optional<DestSourcePair>(
10381ad6265SDimitry Andric         DestSourcePair{MI.getOperand(0), MI.getOperand(1)});
10481ad6265SDimitry Andric 
105bdd1243dSDimitry Andric   return std::nullopt;
10681ad6265SDimitry Andric }
10781ad6265SDimitry Andric 
1080b57cec5SDimitry Andric class CopyTracker {
1090b57cec5SDimitry Andric   struct CopyInfo {
11006c3fb27SDimitry Andric     MachineInstr *MI, *LastSeenUseInCopy;
111e8d8bef9SDimitry Andric     SmallVector<MCRegister, 4> DefRegs;
1120b57cec5SDimitry Andric     bool Avail;
1130b57cec5SDimitry Andric   };
1140b57cec5SDimitry Andric 
115e8d8bef9SDimitry Andric   DenseMap<MCRegister, CopyInfo> Copies;
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric public:
1180b57cec5SDimitry Andric   /// Mark all of the given registers and their subregisters as unavailable for
1190b57cec5SDimitry Andric   /// copying.
120e8d8bef9SDimitry Andric   void markRegsUnavailable(ArrayRef<MCRegister> Regs,
1210b57cec5SDimitry Andric                            const TargetRegisterInfo &TRI) {
122e8d8bef9SDimitry Andric     for (MCRegister Reg : Regs) {
1230b57cec5SDimitry Andric       // Source of copy is no longer available for propagation.
12406c3fb27SDimitry Andric       for (MCRegUnit Unit : TRI.regunits(Reg)) {
12506c3fb27SDimitry Andric         auto CI = Copies.find(Unit);
1260b57cec5SDimitry Andric         if (CI != Copies.end())
1270b57cec5SDimitry Andric           CI->second.Avail = false;
1280b57cec5SDimitry Andric       }
1290b57cec5SDimitry Andric     }
1300b57cec5SDimitry Andric   }
1310b57cec5SDimitry Andric 
132480093f4SDimitry Andric   /// Remove register from copy maps.
13381ad6265SDimitry Andric   void invalidateRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
13481ad6265SDimitry Andric                           const TargetInstrInfo &TII, bool UseCopyInstr) {
135480093f4SDimitry Andric     // Since Reg might be a subreg of some registers, only invalidate Reg is not
136480093f4SDimitry Andric     // enough. We have to find the COPY defines Reg or registers defined by Reg
137*5f757f3fSDimitry Andric     // and invalidate all of them. Similarly, we must invalidate all of the
138*5f757f3fSDimitry Andric     // the subregisters used in the source of the COPY.
139*5f757f3fSDimitry Andric     SmallSet<MCRegUnit, 8> RegUnitsToInvalidate;
140*5f757f3fSDimitry Andric     auto InvalidateCopy = [&](MachineInstr *MI) {
141bdd1243dSDimitry Andric       std::optional<DestSourcePair> CopyOperands =
14281ad6265SDimitry Andric           isCopyInstr(*MI, TII, UseCopyInstr);
14381ad6265SDimitry Andric       assert(CopyOperands && "Expect copy");
14481ad6265SDimitry Andric 
145*5f757f3fSDimitry Andric       auto Dest = TRI.regunits(CopyOperands->Destination->getReg().asMCReg());
146*5f757f3fSDimitry Andric       auto Src = TRI.regunits(CopyOperands->Source->getReg().asMCReg());
147*5f757f3fSDimitry Andric       RegUnitsToInvalidate.insert(Dest.begin(), Dest.end());
148*5f757f3fSDimitry Andric       RegUnitsToInvalidate.insert(Src.begin(), Src.end());
149*5f757f3fSDimitry Andric     };
150*5f757f3fSDimitry Andric 
151*5f757f3fSDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Reg)) {
152*5f757f3fSDimitry Andric       auto I = Copies.find(Unit);
153*5f757f3fSDimitry Andric       if (I != Copies.end()) {
154*5f757f3fSDimitry Andric         if (MachineInstr *MI = I->second.MI)
155*5f757f3fSDimitry Andric           InvalidateCopy(MI);
156*5f757f3fSDimitry Andric         if (MachineInstr *MI = I->second.LastSeenUseInCopy)
157*5f757f3fSDimitry Andric           InvalidateCopy(MI);
158480093f4SDimitry Andric       }
159480093f4SDimitry Andric     }
160*5f757f3fSDimitry Andric     for (MCRegUnit Unit : RegUnitsToInvalidate)
16106c3fb27SDimitry Andric       Copies.erase(Unit);
162480093f4SDimitry Andric   }
163480093f4SDimitry Andric 
1640b57cec5SDimitry Andric   /// Clobber a single register, removing it from the tracker's copy maps.
16581ad6265SDimitry Andric   void clobberRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
16681ad6265SDimitry Andric                        const TargetInstrInfo &TII, bool UseCopyInstr) {
16706c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Reg)) {
16806c3fb27SDimitry Andric       auto I = Copies.find(Unit);
1690b57cec5SDimitry Andric       if (I != Copies.end()) {
1700b57cec5SDimitry Andric         // When we clobber the source of a copy, we need to clobber everything
1710b57cec5SDimitry Andric         // it defined.
1720b57cec5SDimitry Andric         markRegsUnavailable(I->second.DefRegs, TRI);
1730b57cec5SDimitry Andric         // When we clobber the destination of a copy, we need to clobber the
1740b57cec5SDimitry Andric         // whole register it defined.
17581ad6265SDimitry Andric         if (MachineInstr *MI = I->second.MI) {
176bdd1243dSDimitry Andric           std::optional<DestSourcePair> CopyOperands =
17781ad6265SDimitry Andric               isCopyInstr(*MI, TII, UseCopyInstr);
17881ad6265SDimitry Andric           markRegsUnavailable({CopyOperands->Destination->getReg().asMCReg()},
17981ad6265SDimitry Andric                               TRI);
18081ad6265SDimitry Andric         }
1810b57cec5SDimitry Andric         // Now we can erase the copy.
1820b57cec5SDimitry Andric         Copies.erase(I);
1830b57cec5SDimitry Andric       }
1840b57cec5SDimitry Andric     }
1850b57cec5SDimitry Andric   }
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   /// Add this copy's registers into the tracker's copy maps.
18881ad6265SDimitry Andric   void trackCopy(MachineInstr *MI, const TargetRegisterInfo &TRI,
18981ad6265SDimitry Andric                  const TargetInstrInfo &TII, bool UseCopyInstr) {
190bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
191bdd1243dSDimitry Andric         isCopyInstr(*MI, TII, UseCopyInstr);
19281ad6265SDimitry Andric     assert(CopyOperands && "Tracking non-copy?");
1930b57cec5SDimitry Andric 
19481ad6265SDimitry Andric     MCRegister Src = CopyOperands->Source->getReg().asMCReg();
19581ad6265SDimitry Andric     MCRegister Def = CopyOperands->Destination->getReg().asMCReg();
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric     // Remember Def is defined by the copy.
19806c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Def))
19906c3fb27SDimitry Andric       Copies[Unit] = {MI, nullptr, {}, true};
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric     // Remember source that's copied to Def. Once it's clobbered, then
2020b57cec5SDimitry Andric     // it's no longer available for copy propagation.
20306c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Src)) {
20406c3fb27SDimitry Andric       auto I = Copies.insert({Unit, {nullptr, nullptr, {}, false}});
2050b57cec5SDimitry Andric       auto &Copy = I.first->second;
2060b57cec5SDimitry Andric       if (!is_contained(Copy.DefRegs, Def))
2070b57cec5SDimitry Andric         Copy.DefRegs.push_back(Def);
20806c3fb27SDimitry Andric       Copy.LastSeenUseInCopy = MI;
2090b57cec5SDimitry Andric     }
2100b57cec5SDimitry Andric   }
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric   bool hasAnyCopies() {
2130b57cec5SDimitry Andric     return !Copies.empty();
2140b57cec5SDimitry Andric   }
2150b57cec5SDimitry Andric 
216e8d8bef9SDimitry Andric   MachineInstr *findCopyForUnit(MCRegister RegUnit,
217e8d8bef9SDimitry Andric                                 const TargetRegisterInfo &TRI,
2180b57cec5SDimitry Andric                                 bool MustBeAvailable = false) {
2190b57cec5SDimitry Andric     auto CI = Copies.find(RegUnit);
2200b57cec5SDimitry Andric     if (CI == Copies.end())
2210b57cec5SDimitry Andric       return nullptr;
2220b57cec5SDimitry Andric     if (MustBeAvailable && !CI->second.Avail)
2230b57cec5SDimitry Andric       return nullptr;
2240b57cec5SDimitry Andric     return CI->second.MI;
2250b57cec5SDimitry Andric   }
2260b57cec5SDimitry Andric 
227e8d8bef9SDimitry Andric   MachineInstr *findCopyDefViaUnit(MCRegister RegUnit,
228480093f4SDimitry Andric                                    const TargetRegisterInfo &TRI) {
229480093f4SDimitry Andric     auto CI = Copies.find(RegUnit);
230480093f4SDimitry Andric     if (CI == Copies.end())
231480093f4SDimitry Andric       return nullptr;
232480093f4SDimitry Andric     if (CI->second.DefRegs.size() != 1)
233480093f4SDimitry Andric       return nullptr;
23406c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(CI->second.DefRegs[0]).begin();
23506c3fb27SDimitry Andric     return findCopyForUnit(RU, TRI, true);
236480093f4SDimitry Andric   }
237480093f4SDimitry Andric 
238e8d8bef9SDimitry Andric   MachineInstr *findAvailBackwardCopy(MachineInstr &I, MCRegister Reg,
23981ad6265SDimitry Andric                                       const TargetRegisterInfo &TRI,
24081ad6265SDimitry Andric                                       const TargetInstrInfo &TII,
24181ad6265SDimitry Andric                                       bool UseCopyInstr) {
24206c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
24306c3fb27SDimitry Andric     MachineInstr *AvailCopy = findCopyDefViaUnit(RU, TRI);
24481ad6265SDimitry Andric 
24581ad6265SDimitry Andric     if (!AvailCopy)
246480093f4SDimitry Andric       return nullptr;
247480093f4SDimitry Andric 
248bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
24981ad6265SDimitry Andric         isCopyInstr(*AvailCopy, TII, UseCopyInstr);
25081ad6265SDimitry Andric     Register AvailSrc = CopyOperands->Source->getReg();
25181ad6265SDimitry Andric     Register AvailDef = CopyOperands->Destination->getReg();
25281ad6265SDimitry Andric     if (!TRI.isSubRegisterEq(AvailSrc, Reg))
25381ad6265SDimitry Andric       return nullptr;
25481ad6265SDimitry Andric 
255480093f4SDimitry Andric     for (const MachineInstr &MI :
256480093f4SDimitry Andric          make_range(AvailCopy->getReverseIterator(), I.getReverseIterator()))
257480093f4SDimitry Andric       for (const MachineOperand &MO : MI.operands())
258480093f4SDimitry Andric         if (MO.isRegMask())
259480093f4SDimitry Andric           // FIXME: Shall we simultaneously invalidate AvailSrc or AvailDef?
260480093f4SDimitry Andric           if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
261480093f4SDimitry Andric             return nullptr;
262480093f4SDimitry Andric 
263480093f4SDimitry Andric     return AvailCopy;
264480093f4SDimitry Andric   }
265480093f4SDimitry Andric 
266e8d8bef9SDimitry Andric   MachineInstr *findAvailCopy(MachineInstr &DestCopy, MCRegister Reg,
26781ad6265SDimitry Andric                               const TargetRegisterInfo &TRI,
26881ad6265SDimitry Andric                               const TargetInstrInfo &TII, bool UseCopyInstr) {
2690b57cec5SDimitry Andric     // We check the first RegUnit here, since we'll only be interested in the
2700b57cec5SDimitry Andric     // copy if it copies the entire register anyway.
27106c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
2720b57cec5SDimitry Andric     MachineInstr *AvailCopy =
27306c3fb27SDimitry Andric         findCopyForUnit(RU, TRI, /*MustBeAvailable=*/true);
27481ad6265SDimitry Andric 
27581ad6265SDimitry Andric     if (!AvailCopy)
27681ad6265SDimitry Andric       return nullptr;
27781ad6265SDimitry Andric 
278bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
27981ad6265SDimitry Andric         isCopyInstr(*AvailCopy, TII, UseCopyInstr);
28081ad6265SDimitry Andric     Register AvailSrc = CopyOperands->Source->getReg();
28181ad6265SDimitry Andric     Register AvailDef = CopyOperands->Destination->getReg();
28281ad6265SDimitry Andric     if (!TRI.isSubRegisterEq(AvailDef, Reg))
2830b57cec5SDimitry Andric       return nullptr;
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric     // Check that the available copy isn't clobbered by any regmasks between
2860b57cec5SDimitry Andric     // itself and the destination.
2870b57cec5SDimitry Andric     for (const MachineInstr &MI :
2880b57cec5SDimitry Andric          make_range(AvailCopy->getIterator(), DestCopy.getIterator()))
2890b57cec5SDimitry Andric       for (const MachineOperand &MO : MI.operands())
2900b57cec5SDimitry Andric         if (MO.isRegMask())
2910b57cec5SDimitry Andric           if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
2920b57cec5SDimitry Andric             return nullptr;
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric     return AvailCopy;
2950b57cec5SDimitry Andric   }
2960b57cec5SDimitry Andric 
29706c3fb27SDimitry Andric   // Find last COPY that defines Reg before Current MachineInstr.
29806c3fb27SDimitry Andric   MachineInstr *findLastSeenDefInCopy(const MachineInstr &Current,
29906c3fb27SDimitry Andric                                       MCRegister Reg,
30006c3fb27SDimitry Andric                                       const TargetRegisterInfo &TRI,
30106c3fb27SDimitry Andric                                       const TargetInstrInfo &TII,
30206c3fb27SDimitry Andric                                       bool UseCopyInstr) {
30306c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
30406c3fb27SDimitry Andric     auto CI = Copies.find(RU);
30506c3fb27SDimitry Andric     if (CI == Copies.end() || !CI->second.Avail)
30606c3fb27SDimitry Andric       return nullptr;
30706c3fb27SDimitry Andric 
30806c3fb27SDimitry Andric     MachineInstr *DefCopy = CI->second.MI;
30906c3fb27SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
31006c3fb27SDimitry Andric         isCopyInstr(*DefCopy, TII, UseCopyInstr);
31106c3fb27SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
31206c3fb27SDimitry Andric     if (!TRI.isSubRegisterEq(Def, Reg))
31306c3fb27SDimitry Andric       return nullptr;
31406c3fb27SDimitry Andric 
31506c3fb27SDimitry Andric     for (const MachineInstr &MI :
31606c3fb27SDimitry Andric          make_range(static_cast<const MachineInstr *>(DefCopy)->getIterator(),
31706c3fb27SDimitry Andric                     Current.getIterator()))
31806c3fb27SDimitry Andric       for (const MachineOperand &MO : MI.operands())
31906c3fb27SDimitry Andric         if (MO.isRegMask())
32006c3fb27SDimitry Andric           if (MO.clobbersPhysReg(Def)) {
32106c3fb27SDimitry Andric             LLVM_DEBUG(dbgs() << "MCP: Removed tracking of "
32206c3fb27SDimitry Andric                               << printReg(Def, &TRI) << "\n");
32306c3fb27SDimitry Andric             return nullptr;
32406c3fb27SDimitry Andric           }
32506c3fb27SDimitry Andric 
32606c3fb27SDimitry Andric     return DefCopy;
32706c3fb27SDimitry Andric   }
32806c3fb27SDimitry Andric 
32906c3fb27SDimitry Andric   // Find last COPY that uses Reg.
33006c3fb27SDimitry Andric   MachineInstr *findLastSeenUseInCopy(MCRegister Reg,
33106c3fb27SDimitry Andric                                       const TargetRegisterInfo &TRI) {
33206c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
33306c3fb27SDimitry Andric     auto CI = Copies.find(RU);
33406c3fb27SDimitry Andric     if (CI == Copies.end())
33506c3fb27SDimitry Andric       return nullptr;
33606c3fb27SDimitry Andric     return CI->second.LastSeenUseInCopy;
33706c3fb27SDimitry Andric   }
33806c3fb27SDimitry Andric 
3390b57cec5SDimitry Andric   void clear() {
3400b57cec5SDimitry Andric     Copies.clear();
3410b57cec5SDimitry Andric   }
3420b57cec5SDimitry Andric };
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric class MachineCopyPropagation : public MachineFunctionPass {
34506c3fb27SDimitry Andric   const TargetRegisterInfo *TRI = nullptr;
34606c3fb27SDimitry Andric   const TargetInstrInfo *TII = nullptr;
34706c3fb27SDimitry Andric   const MachineRegisterInfo *MRI = nullptr;
3480b57cec5SDimitry Andric 
34981ad6265SDimitry Andric   // Return true if this is a copy instruction and false otherwise.
35081ad6265SDimitry Andric   bool UseCopyInstr;
35181ad6265SDimitry Andric 
3520b57cec5SDimitry Andric public:
3530b57cec5SDimitry Andric   static char ID; // Pass identification, replacement for typeid
3540b57cec5SDimitry Andric 
35581ad6265SDimitry Andric   MachineCopyPropagation(bool CopyInstr = false)
35681ad6265SDimitry Andric       : MachineFunctionPass(ID), UseCopyInstr(CopyInstr || MCPUseCopyInstr) {
3570b57cec5SDimitry Andric     initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
3580b57cec5SDimitry Andric   }
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
3610b57cec5SDimitry Andric     AU.setPreservesCFG();
3620b57cec5SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
3630b57cec5SDimitry Andric   }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric   MachineFunctionProperties getRequiredProperties() const override {
3680b57cec5SDimitry Andric     return MachineFunctionProperties().set(
3690b57cec5SDimitry Andric         MachineFunctionProperties::Property::NoVRegs);
3700b57cec5SDimitry Andric   }
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric private:
3738bcb0991SDimitry Andric   typedef enum { DebugUse = false, RegularUse = true } DebugType;
3748bcb0991SDimitry Andric 
375e8d8bef9SDimitry Andric   void ReadRegister(MCRegister Reg, MachineInstr &Reader, DebugType DT);
376480093f4SDimitry Andric   void ForwardCopyPropagateBlock(MachineBasicBlock &MBB);
377480093f4SDimitry Andric   void BackwardCopyPropagateBlock(MachineBasicBlock &MBB);
37806c3fb27SDimitry Andric   void EliminateSpillageCopies(MachineBasicBlock &MBB);
379e8d8bef9SDimitry Andric   bool eraseIfRedundant(MachineInstr &Copy, MCRegister Src, MCRegister Def);
3800b57cec5SDimitry Andric   void forwardUses(MachineInstr &MI);
381480093f4SDimitry Andric   void propagateDefs(MachineInstr &MI);
3820b57cec5SDimitry Andric   bool isForwardableRegClassCopy(const MachineInstr &Copy,
3830b57cec5SDimitry Andric                                  const MachineInstr &UseI, unsigned UseIdx);
384480093f4SDimitry Andric   bool isBackwardPropagatableRegClassCopy(const MachineInstr &Copy,
385480093f4SDimitry Andric                                           const MachineInstr &UseI,
386480093f4SDimitry Andric                                           unsigned UseIdx);
3870b57cec5SDimitry Andric   bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use);
388e8d8bef9SDimitry Andric   bool hasOverlappingMultipleDef(const MachineInstr &MI,
389e8d8bef9SDimitry Andric                                  const MachineOperand &MODef, Register Def);
3900b57cec5SDimitry Andric 
3910b57cec5SDimitry Andric   /// Candidates for deletion.
3920b57cec5SDimitry Andric   SmallSetVector<MachineInstr *, 8> MaybeDeadCopies;
3930b57cec5SDimitry Andric 
3948bcb0991SDimitry Andric   /// Multimap tracking debug users in current BB
395fe6060f1SDimitry Andric   DenseMap<MachineInstr *, SmallSet<MachineInstr *, 2>> CopyDbgUsers;
3968bcb0991SDimitry Andric 
3970b57cec5SDimitry Andric   CopyTracker Tracker;
3980b57cec5SDimitry Andric 
39906c3fb27SDimitry Andric   bool Changed = false;
4000b57cec5SDimitry Andric };
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric } // end anonymous namespace
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric char MachineCopyPropagation::ID = 0;
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric INITIALIZE_PASS(MachineCopyPropagation, DEBUG_TYPE,
4090b57cec5SDimitry Andric                 "Machine Copy Propagation Pass", false, false)
4100b57cec5SDimitry Andric 
411e8d8bef9SDimitry Andric void MachineCopyPropagation::ReadRegister(MCRegister Reg, MachineInstr &Reader,
4128bcb0991SDimitry Andric                                           DebugType DT) {
4130b57cec5SDimitry Andric   // If 'Reg' is defined by a copy, the copy is no longer a candidate
4148bcb0991SDimitry Andric   // for elimination. If a copy is "read" by a debug user, record the user
4158bcb0991SDimitry Andric   // for propagation.
41606c3fb27SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(Reg)) {
41706c3fb27SDimitry Andric     if (MachineInstr *Copy = Tracker.findCopyForUnit(Unit, *TRI)) {
4188bcb0991SDimitry Andric       if (DT == RegularUse) {
4190b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy->dump());
4200b57cec5SDimitry Andric         MaybeDeadCopies.remove(Copy);
4218bcb0991SDimitry Andric       } else {
422fe6060f1SDimitry Andric         CopyDbgUsers[Copy].insert(&Reader);
4238bcb0991SDimitry Andric       }
4240b57cec5SDimitry Andric     }
4250b57cec5SDimitry Andric   }
4260b57cec5SDimitry Andric }
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric /// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
4290b57cec5SDimitry Andric /// This fact may have been obscured by sub register usage or may not be true at
4300b57cec5SDimitry Andric /// all even though Src and Def are subregisters of the registers used in
4310b57cec5SDimitry Andric /// PreviousCopy. e.g.
4320b57cec5SDimitry Andric /// isNopCopy("ecx = COPY eax", AX, CX) == true
4330b57cec5SDimitry Andric /// isNopCopy("ecx = COPY eax", AH, CL) == false
434e8d8bef9SDimitry Andric static bool isNopCopy(const MachineInstr &PreviousCopy, MCRegister Src,
43581ad6265SDimitry Andric                       MCRegister Def, const TargetRegisterInfo *TRI,
43681ad6265SDimitry Andric                       const TargetInstrInfo *TII, bool UseCopyInstr) {
43781ad6265SDimitry Andric 
438bdd1243dSDimitry Andric   std::optional<DestSourcePair> CopyOperands =
43981ad6265SDimitry Andric       isCopyInstr(PreviousCopy, *TII, UseCopyInstr);
44081ad6265SDimitry Andric   MCRegister PreviousSrc = CopyOperands->Source->getReg().asMCReg();
44181ad6265SDimitry Andric   MCRegister PreviousDef = CopyOperands->Destination->getReg().asMCReg();
44216d6b3b3SDimitry Andric   if (Src == PreviousSrc && Def == PreviousDef)
4430b57cec5SDimitry Andric     return true;
4440b57cec5SDimitry Andric   if (!TRI->isSubRegister(PreviousSrc, Src))
4450b57cec5SDimitry Andric     return false;
4460b57cec5SDimitry Andric   unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
4470b57cec5SDimitry Andric   return SubIdx == TRI->getSubRegIndex(PreviousDef, Def);
4480b57cec5SDimitry Andric }
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric /// Remove instruction \p Copy if there exists a previous copy that copies the
4510b57cec5SDimitry Andric /// register \p Src to the register \p Def; This may happen indirectly by
4520b57cec5SDimitry Andric /// copying the super registers.
453e8d8bef9SDimitry Andric bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy,
454e8d8bef9SDimitry Andric                                               MCRegister Src, MCRegister Def) {
4550b57cec5SDimitry Andric   // Avoid eliminating a copy from/to a reserved registers as we cannot predict
4560b57cec5SDimitry Andric   // the value (Example: The sparc zero register is writable but stays zero).
4570b57cec5SDimitry Andric   if (MRI->isReserved(Src) || MRI->isReserved(Def))
4580b57cec5SDimitry Andric     return false;
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   // Search for an existing copy.
46181ad6265SDimitry Andric   MachineInstr *PrevCopy =
46281ad6265SDimitry Andric       Tracker.findAvailCopy(Copy, Def, *TRI, *TII, UseCopyInstr);
4630b57cec5SDimitry Andric   if (!PrevCopy)
4640b57cec5SDimitry Andric     return false;
4650b57cec5SDimitry Andric 
46681ad6265SDimitry Andric   auto PrevCopyOperands = isCopyInstr(*PrevCopy, *TII, UseCopyInstr);
4670b57cec5SDimitry Andric   // Check that the existing copy uses the correct sub registers.
46881ad6265SDimitry Andric   if (PrevCopyOperands->Destination->isDead())
4690b57cec5SDimitry Andric     return false;
47081ad6265SDimitry Andric   if (!isNopCopy(*PrevCopy, Src, Def, TRI, TII, UseCopyInstr))
4710b57cec5SDimitry Andric     return false;
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric   // Copy was redundantly redefining either Src or Def. Remove earlier kill
4760b57cec5SDimitry Andric   // flags between Copy and PrevCopy because the value will be reused now.
477bdd1243dSDimitry Andric   std::optional<DestSourcePair> CopyOperands =
478bdd1243dSDimitry Andric       isCopyInstr(Copy, *TII, UseCopyInstr);
47981ad6265SDimitry Andric   assert(CopyOperands);
48081ad6265SDimitry Andric 
48181ad6265SDimitry Andric   Register CopyDef = CopyOperands->Destination->getReg();
4820b57cec5SDimitry Andric   assert(CopyDef == Src || CopyDef == Def);
4830b57cec5SDimitry Andric   for (MachineInstr &MI :
4840b57cec5SDimitry Andric        make_range(PrevCopy->getIterator(), Copy.getIterator()))
4850b57cec5SDimitry Andric     MI.clearRegisterKills(CopyDef, TRI);
4860b57cec5SDimitry Andric 
48706c3fb27SDimitry Andric   // Clear undef flag from remaining copy if needed.
48806c3fb27SDimitry Andric   if (!CopyOperands->Source->isUndef()) {
48906c3fb27SDimitry Andric     PrevCopy->getOperand(PrevCopyOperands->Source->getOperandNo())
49006c3fb27SDimitry Andric         .setIsUndef(false);
49106c3fb27SDimitry Andric   }
49206c3fb27SDimitry Andric 
4930b57cec5SDimitry Andric   Copy.eraseFromParent();
4940b57cec5SDimitry Andric   Changed = true;
4950b57cec5SDimitry Andric   ++NumDeletes;
4960b57cec5SDimitry Andric   return true;
4970b57cec5SDimitry Andric }
4980b57cec5SDimitry Andric 
499480093f4SDimitry Andric bool MachineCopyPropagation::isBackwardPropagatableRegClassCopy(
500480093f4SDimitry Andric     const MachineInstr &Copy, const MachineInstr &UseI, unsigned UseIdx) {
501bdd1243dSDimitry Andric   std::optional<DestSourcePair> CopyOperands =
502bdd1243dSDimitry Andric       isCopyInstr(Copy, *TII, UseCopyInstr);
50381ad6265SDimitry Andric   Register Def = CopyOperands->Destination->getReg();
504480093f4SDimitry Andric 
505480093f4SDimitry Andric   if (const TargetRegisterClass *URC =
506480093f4SDimitry Andric           UseI.getRegClassConstraint(UseIdx, TII, TRI))
507480093f4SDimitry Andric     return URC->contains(Def);
508480093f4SDimitry Andric 
509480093f4SDimitry Andric   // We don't process further if UseI is a COPY, since forward copy propagation
510480093f4SDimitry Andric   // should handle that.
511480093f4SDimitry Andric   return false;
512480093f4SDimitry Andric }
513480093f4SDimitry Andric 
5140b57cec5SDimitry Andric /// Decide whether we should forward the source of \param Copy to its use in
5150b57cec5SDimitry Andric /// \param UseI based on the physical register class constraints of the opcode
5160b57cec5SDimitry Andric /// and avoiding introducing more cross-class COPYs.
5170b57cec5SDimitry Andric bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
5180b57cec5SDimitry Andric                                                        const MachineInstr &UseI,
5190b57cec5SDimitry Andric                                                        unsigned UseIdx) {
520bdd1243dSDimitry Andric   std::optional<DestSourcePair> CopyOperands =
521bdd1243dSDimitry Andric       isCopyInstr(Copy, *TII, UseCopyInstr);
52281ad6265SDimitry Andric   Register CopySrcReg = CopyOperands->Source->getReg();
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   // If the new register meets the opcode register constraints, then allow
5250b57cec5SDimitry Andric   // forwarding.
5260b57cec5SDimitry Andric   if (const TargetRegisterClass *URC =
5270b57cec5SDimitry Andric           UseI.getRegClassConstraint(UseIdx, TII, TRI))
5280b57cec5SDimitry Andric     return URC->contains(CopySrcReg);
5290b57cec5SDimitry Andric 
53081ad6265SDimitry Andric   auto UseICopyOperands = isCopyInstr(UseI, *TII, UseCopyInstr);
53181ad6265SDimitry Andric   if (!UseICopyOperands)
5320b57cec5SDimitry Andric     return false;
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   /// COPYs don't have register class constraints, so if the user instruction
5350b57cec5SDimitry Andric   /// is a COPY, we just try to avoid introducing additional cross-class
5360b57cec5SDimitry Andric   /// COPYs.  For example:
5370b57cec5SDimitry Andric   ///
5380b57cec5SDimitry Andric   ///   RegClassA = COPY RegClassB  // Copy parameter
5390b57cec5SDimitry Andric   ///   ...
5400b57cec5SDimitry Andric   ///   RegClassB = COPY RegClassA  // UseI parameter
5410b57cec5SDimitry Andric   ///
5420b57cec5SDimitry Andric   /// which after forwarding becomes
5430b57cec5SDimitry Andric   ///
5440b57cec5SDimitry Andric   ///   RegClassA = COPY RegClassB
5450b57cec5SDimitry Andric   ///   ...
5460b57cec5SDimitry Andric   ///   RegClassB = COPY RegClassB
5470b57cec5SDimitry Andric   ///
5480b57cec5SDimitry Andric   /// so we have reduced the number of cross-class COPYs and potentially
5490b57cec5SDimitry Andric   /// introduced a nop COPY that can be removed.
5500b57cec5SDimitry Andric 
55181ad6265SDimitry Andric   // Allow forwarding if src and dst belong to any common class, so long as they
55281ad6265SDimitry Andric   // don't belong to any (possibly smaller) common class that requires copies to
55381ad6265SDimitry Andric   // go via a different class.
55481ad6265SDimitry Andric   Register UseDstReg = UseICopyOperands->Destination->getReg();
55581ad6265SDimitry Andric   bool Found = false;
55681ad6265SDimitry Andric   bool IsCrossClass = false;
55781ad6265SDimitry Andric   for (const TargetRegisterClass *RC : TRI->regclasses()) {
55881ad6265SDimitry Andric     if (RC->contains(CopySrcReg) && RC->contains(UseDstReg)) {
55981ad6265SDimitry Andric       Found = true;
56081ad6265SDimitry Andric       if (TRI->getCrossCopyRegClass(RC) != RC) {
56181ad6265SDimitry Andric         IsCrossClass = true;
56281ad6265SDimitry Andric         break;
56381ad6265SDimitry Andric       }
56481ad6265SDimitry Andric     }
56581ad6265SDimitry Andric   }
56681ad6265SDimitry Andric   if (!Found)
56781ad6265SDimitry Andric     return false;
56881ad6265SDimitry Andric   if (!IsCrossClass)
56981ad6265SDimitry Andric     return true;
57081ad6265SDimitry Andric   // The forwarded copy would be cross-class. Only do this if the original copy
57181ad6265SDimitry Andric   // was also cross-class.
57281ad6265SDimitry Andric   Register CopyDstReg = CopyOperands->Destination->getReg();
57381ad6265SDimitry Andric   for (const TargetRegisterClass *RC : TRI->regclasses()) {
57481ad6265SDimitry Andric     if (RC->contains(CopySrcReg) && RC->contains(CopyDstReg) &&
57581ad6265SDimitry Andric         TRI->getCrossCopyRegClass(RC) != RC)
57681ad6265SDimitry Andric       return true;
57781ad6265SDimitry Andric   }
5780b57cec5SDimitry Andric   return false;
5790b57cec5SDimitry Andric }
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric /// Check that \p MI does not have implicit uses that overlap with it's \p Use
5820b57cec5SDimitry Andric /// operand (the register being replaced), since these can sometimes be
5830b57cec5SDimitry Andric /// implicitly tied to other operands.  For example, on AMDGPU:
5840b57cec5SDimitry Andric ///
5850b57cec5SDimitry Andric /// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
5860b57cec5SDimitry Andric ///
5870b57cec5SDimitry Andric /// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
5880b57cec5SDimitry Andric /// way of knowing we need to update the latter when updating the former.
5890b57cec5SDimitry Andric bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
5900b57cec5SDimitry Andric                                                 const MachineOperand &Use) {
5910b57cec5SDimitry Andric   for (const MachineOperand &MIUse : MI.uses())
5920b57cec5SDimitry Andric     if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
5930b57cec5SDimitry Andric         MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
5940b57cec5SDimitry Andric       return true;
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric   return false;
5970b57cec5SDimitry Andric }
5980b57cec5SDimitry Andric 
599e8d8bef9SDimitry Andric /// For an MI that has multiple definitions, check whether \p MI has
600e8d8bef9SDimitry Andric /// a definition that overlaps with another of its definitions.
601e8d8bef9SDimitry Andric /// For example, on ARM: umull   r9, r9, lr, r0
602e8d8bef9SDimitry Andric /// The umull instruction is unpredictable unless RdHi and RdLo are different.
603e8d8bef9SDimitry Andric bool MachineCopyPropagation::hasOverlappingMultipleDef(
604e8d8bef9SDimitry Andric     const MachineInstr &MI, const MachineOperand &MODef, Register Def) {
605e8d8bef9SDimitry Andric   for (const MachineOperand &MIDef : MI.defs()) {
606e8d8bef9SDimitry Andric     if ((&MIDef != &MODef) && MIDef.isReg() &&
607e8d8bef9SDimitry Andric         TRI->regsOverlap(Def, MIDef.getReg()))
608e8d8bef9SDimitry Andric       return true;
609e8d8bef9SDimitry Andric   }
610e8d8bef9SDimitry Andric 
611e8d8bef9SDimitry Andric   return false;
612e8d8bef9SDimitry Andric }
613e8d8bef9SDimitry Andric 
6140b57cec5SDimitry Andric /// Look for available copies whose destination register is used by \p MI and
6150b57cec5SDimitry Andric /// replace the use in \p MI with the copy's source register.
6160b57cec5SDimitry Andric void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
6170b57cec5SDimitry Andric   if (!Tracker.hasAnyCopies())
6180b57cec5SDimitry Andric     return;
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric   // Look for non-tied explicit vreg uses that have an active COPY
6210b57cec5SDimitry Andric   // instruction that defines the physical register allocated to them.
6220b57cec5SDimitry Andric   // Replace the vreg with the source of the active COPY.
6230b57cec5SDimitry Andric   for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
6240b57cec5SDimitry Andric        ++OpIdx) {
6250b57cec5SDimitry Andric     MachineOperand &MOUse = MI.getOperand(OpIdx);
6260b57cec5SDimitry Andric     // Don't forward into undef use operands since doing so can cause problems
6270b57cec5SDimitry Andric     // with the machine verifier, since it doesn't treat undef reads as reads,
6280b57cec5SDimitry Andric     // so we can end up with a live range that ends on an undef read, leading to
6290b57cec5SDimitry Andric     // an error that the live range doesn't end on a read of the live range
6300b57cec5SDimitry Andric     // register.
6310b57cec5SDimitry Andric     if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
6320b57cec5SDimitry Andric         MOUse.isImplicit())
6330b57cec5SDimitry Andric       continue;
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric     if (!MOUse.getReg())
6360b57cec5SDimitry Andric       continue;
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric     // Check that the register is marked 'renamable' so we know it is safe to
6390b57cec5SDimitry Andric     // rename it without violating any constraints that aren't expressed in the
6400b57cec5SDimitry Andric     // IR (e.g. ABI or opcode requirements).
6410b57cec5SDimitry Andric     if (!MOUse.isRenamable())
6420b57cec5SDimitry Andric       continue;
6430b57cec5SDimitry Andric 
64481ad6265SDimitry Andric     MachineInstr *Copy = Tracker.findAvailCopy(MI, MOUse.getReg().asMCReg(),
64581ad6265SDimitry Andric                                                *TRI, *TII, UseCopyInstr);
6460b57cec5SDimitry Andric     if (!Copy)
6470b57cec5SDimitry Andric       continue;
6480b57cec5SDimitry Andric 
649bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
65081ad6265SDimitry Andric         isCopyInstr(*Copy, *TII, UseCopyInstr);
65181ad6265SDimitry Andric     Register CopyDstReg = CopyOperands->Destination->getReg();
65281ad6265SDimitry Andric     const MachineOperand &CopySrc = *CopyOperands->Source;
6538bcb0991SDimitry Andric     Register CopySrcReg = CopySrc.getReg();
6540b57cec5SDimitry Andric 
65506c3fb27SDimitry Andric     Register ForwardedReg = CopySrcReg;
65606c3fb27SDimitry Andric     // MI might use a sub-register of the Copy destination, in which case the
65706c3fb27SDimitry Andric     // forwarded register is the matching sub-register of the Copy source.
6580b57cec5SDimitry Andric     if (MOUse.getReg() != CopyDstReg) {
65906c3fb27SDimitry Andric       unsigned SubRegIdx = TRI->getSubRegIndex(CopyDstReg, MOUse.getReg());
66006c3fb27SDimitry Andric       assert(SubRegIdx &&
66106c3fb27SDimitry Andric              "MI source is not a sub-register of Copy destination");
66206c3fb27SDimitry Andric       ForwardedReg = TRI->getSubReg(CopySrcReg, SubRegIdx);
66306c3fb27SDimitry Andric       if (!ForwardedReg) {
66406c3fb27SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Copy source does not have sub-register "
66506c3fb27SDimitry Andric                           << TRI->getSubRegIndexName(SubRegIdx) << '\n');
6660b57cec5SDimitry Andric         continue;
6670b57cec5SDimitry Andric       }
66806c3fb27SDimitry Andric     }
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric     // Don't forward COPYs of reserved regs unless they are constant.
6710b57cec5SDimitry Andric     if (MRI->isReserved(CopySrcReg) && !MRI->isConstantPhysReg(CopySrcReg))
6720b57cec5SDimitry Andric       continue;
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric     if (!isForwardableRegClassCopy(*Copy, MI, OpIdx))
6750b57cec5SDimitry Andric       continue;
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric     if (hasImplicitOverlap(MI, MOUse))
6780b57cec5SDimitry Andric       continue;
6790b57cec5SDimitry Andric 
680480093f4SDimitry Andric     // Check that the instruction is not a copy that partially overwrites the
681480093f4SDimitry Andric     // original copy source that we are about to use. The tracker mechanism
682480093f4SDimitry Andric     // cannot cope with that.
68381ad6265SDimitry Andric     if (isCopyInstr(MI, *TII, UseCopyInstr) &&
68481ad6265SDimitry Andric         MI.modifiesRegister(CopySrcReg, TRI) &&
685480093f4SDimitry Andric         !MI.definesRegister(CopySrcReg)) {
686480093f4SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Copy source overlap with dest in " << MI);
687480093f4SDimitry Andric       continue;
688480093f4SDimitry Andric     }
689480093f4SDimitry Andric 
6900b57cec5SDimitry Andric     if (!DebugCounter::shouldExecute(FwdCounter)) {
6910b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n  "
6920b57cec5SDimitry Andric                         << MI);
6930b57cec5SDimitry Andric       continue;
6940b57cec5SDimitry Andric     }
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
69706c3fb27SDimitry Andric                       << "\n     with " << printReg(ForwardedReg, TRI)
6980b57cec5SDimitry Andric                       << "\n     in " << MI << "     from " << *Copy);
6990b57cec5SDimitry Andric 
70006c3fb27SDimitry Andric     MOUse.setReg(ForwardedReg);
70106c3fb27SDimitry Andric 
7020b57cec5SDimitry Andric     if (!CopySrc.isRenamable())
7030b57cec5SDimitry Andric       MOUse.setIsRenamable(false);
704349cc55cSDimitry Andric     MOUse.setIsUndef(CopySrc.isUndef());
7050b57cec5SDimitry Andric 
7060b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric     // Clear kill markers that may have been invalidated.
7090b57cec5SDimitry Andric     for (MachineInstr &KMI :
7100b57cec5SDimitry Andric          make_range(Copy->getIterator(), std::next(MI.getIterator())))
7110b57cec5SDimitry Andric       KMI.clearRegisterKills(CopySrcReg, TRI);
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric     ++NumCopyForwards;
7140b57cec5SDimitry Andric     Changed = true;
7150b57cec5SDimitry Andric   }
7160b57cec5SDimitry Andric }
7170b57cec5SDimitry Andric 
718480093f4SDimitry Andric void MachineCopyPropagation::ForwardCopyPropagateBlock(MachineBasicBlock &MBB) {
719480093f4SDimitry Andric   LLVM_DEBUG(dbgs() << "MCP: ForwardCopyPropagateBlock " << MBB.getName()
720480093f4SDimitry Andric                     << "\n");
7210b57cec5SDimitry Andric 
722349cc55cSDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
7230b57cec5SDimitry Andric     // Analyze copies (which don't overlap themselves).
724bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
725bdd1243dSDimitry Andric         isCopyInstr(MI, *TII, UseCopyInstr);
72681ad6265SDimitry Andric     if (CopyOperands) {
72781ad6265SDimitry Andric 
72881ad6265SDimitry Andric       Register RegSrc = CopyOperands->Source->getReg();
72981ad6265SDimitry Andric       Register RegDef = CopyOperands->Destination->getReg();
73081ad6265SDimitry Andric 
73181ad6265SDimitry Andric       if (!TRI->regsOverlap(RegDef, RegSrc)) {
73281ad6265SDimitry Andric         assert(RegDef.isPhysical() && RegSrc.isPhysical() &&
7330b57cec5SDimitry Andric               "MachineCopyPropagation should be run after register allocation!");
7340b57cec5SDimitry Andric 
73581ad6265SDimitry Andric         MCRegister Def = RegDef.asMCReg();
73681ad6265SDimitry Andric         MCRegister Src = RegSrc.asMCReg();
737e8d8bef9SDimitry Andric 
7380b57cec5SDimitry Andric         // The two copies cancel out and the source of the first copy
7390b57cec5SDimitry Andric         // hasn't been overridden, eliminate the second one. e.g.
7400b57cec5SDimitry Andric         //  %ecx = COPY %eax
7410b57cec5SDimitry Andric         //  ... nothing clobbered eax.
7420b57cec5SDimitry Andric         //  %eax = COPY %ecx
7430b57cec5SDimitry Andric         // =>
7440b57cec5SDimitry Andric         //  %ecx = COPY %eax
7450b57cec5SDimitry Andric         //
7460b57cec5SDimitry Andric         // or
7470b57cec5SDimitry Andric         //
7480b57cec5SDimitry Andric         //  %ecx = COPY %eax
7490b57cec5SDimitry Andric         //  ... nothing clobbered eax.
7500b57cec5SDimitry Andric         //  %ecx = COPY %eax
7510b57cec5SDimitry Andric         // =>
7520b57cec5SDimitry Andric         //  %ecx = COPY %eax
753349cc55cSDimitry Andric         if (eraseIfRedundant(MI, Def, Src) || eraseIfRedundant(MI, Src, Def))
7540b57cec5SDimitry Andric           continue;
7550b57cec5SDimitry Andric 
756349cc55cSDimitry Andric         forwardUses(MI);
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric         // Src may have been changed by forwardUses()
75981ad6265SDimitry Andric         CopyOperands = isCopyInstr(MI, *TII, UseCopyInstr);
76081ad6265SDimitry Andric         Src = CopyOperands->Source->getReg().asMCReg();
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric         // If Src is defined by a previous copy, the previous copy cannot be
7630b57cec5SDimitry Andric         // eliminated.
764349cc55cSDimitry Andric         ReadRegister(Src, MI, RegularUse);
765349cc55cSDimitry Andric         for (const MachineOperand &MO : MI.implicit_operands()) {
7660b57cec5SDimitry Andric           if (!MO.isReg() || !MO.readsReg())
7670b57cec5SDimitry Andric             continue;
768e8d8bef9SDimitry Andric           MCRegister Reg = MO.getReg().asMCReg();
7690b57cec5SDimitry Andric           if (!Reg)
7700b57cec5SDimitry Andric             continue;
771349cc55cSDimitry Andric           ReadRegister(Reg, MI, RegularUse);
7720b57cec5SDimitry Andric         }
7730b57cec5SDimitry Andric 
774349cc55cSDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI.dump());
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric         // Copy is now a candidate for deletion.
7770b57cec5SDimitry Andric         if (!MRI->isReserved(Def))
778349cc55cSDimitry Andric           MaybeDeadCopies.insert(&MI);
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric         // If 'Def' is previously source of another copy, then this earlier copy's
7810b57cec5SDimitry Andric         // source is no longer available. e.g.
7820b57cec5SDimitry Andric         // %xmm9 = copy %xmm2
7830b57cec5SDimitry Andric         // ...
7840b57cec5SDimitry Andric         // %xmm2 = copy %xmm0
7850b57cec5SDimitry Andric         // ...
7860b57cec5SDimitry Andric         // %xmm2 = copy %xmm9
78781ad6265SDimitry Andric         Tracker.clobberRegister(Def, *TRI, *TII, UseCopyInstr);
788349cc55cSDimitry Andric         for (const MachineOperand &MO : MI.implicit_operands()) {
7890b57cec5SDimitry Andric           if (!MO.isReg() || !MO.isDef())
7900b57cec5SDimitry Andric             continue;
791e8d8bef9SDimitry Andric           MCRegister Reg = MO.getReg().asMCReg();
7920b57cec5SDimitry Andric           if (!Reg)
7930b57cec5SDimitry Andric             continue;
79481ad6265SDimitry Andric           Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
7950b57cec5SDimitry Andric         }
7960b57cec5SDimitry Andric 
79781ad6265SDimitry Andric         Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric         continue;
8000b57cec5SDimitry Andric       }
80181ad6265SDimitry Andric     }
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric     // Clobber any earlyclobber regs first.
804349cc55cSDimitry Andric     for (const MachineOperand &MO : MI.operands())
8050b57cec5SDimitry Andric       if (MO.isReg() && MO.isEarlyClobber()) {
806e8d8bef9SDimitry Andric         MCRegister Reg = MO.getReg().asMCReg();
8070b57cec5SDimitry Andric         // If we have a tied earlyclobber, that means it is also read by this
8080b57cec5SDimitry Andric         // instruction, so we need to make sure we don't remove it as dead
8090b57cec5SDimitry Andric         // later.
8100b57cec5SDimitry Andric         if (MO.isTied())
811349cc55cSDimitry Andric           ReadRegister(Reg, MI, RegularUse);
81281ad6265SDimitry Andric         Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
8130b57cec5SDimitry Andric       }
8140b57cec5SDimitry Andric 
815349cc55cSDimitry Andric     forwardUses(MI);
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric     // Not a copy.
818e8d8bef9SDimitry Andric     SmallVector<Register, 2> Defs;
8190b57cec5SDimitry Andric     const MachineOperand *RegMask = nullptr;
820349cc55cSDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
8210b57cec5SDimitry Andric       if (MO.isRegMask())
8220b57cec5SDimitry Andric         RegMask = &MO;
8230b57cec5SDimitry Andric       if (!MO.isReg())
8240b57cec5SDimitry Andric         continue;
8258bcb0991SDimitry Andric       Register Reg = MO.getReg();
8260b57cec5SDimitry Andric       if (!Reg)
8270b57cec5SDimitry Andric         continue;
8280b57cec5SDimitry Andric 
829e8d8bef9SDimitry Andric       assert(!Reg.isVirtual() &&
8300b57cec5SDimitry Andric              "MachineCopyPropagation should be run after register allocation!");
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric       if (MO.isDef() && !MO.isEarlyClobber()) {
833e8d8bef9SDimitry Andric         Defs.push_back(Reg.asMCReg());
8340b57cec5SDimitry Andric         continue;
8358bcb0991SDimitry Andric       } else if (MO.readsReg())
836349cc55cSDimitry Andric         ReadRegister(Reg.asMCReg(), MI, MO.isDebug() ? DebugUse : RegularUse);
8370b57cec5SDimitry Andric     }
8380b57cec5SDimitry Andric 
8390b57cec5SDimitry Andric     // The instruction has a register mask operand which means that it clobbers
8400b57cec5SDimitry Andric     // a large set of registers.  Treat clobbered registers the same way as
8410b57cec5SDimitry Andric     // defined registers.
8420b57cec5SDimitry Andric     if (RegMask) {
8430b57cec5SDimitry Andric       // Erase any MaybeDeadCopies whose destination register is clobbered.
8440b57cec5SDimitry Andric       for (SmallSetVector<MachineInstr *, 8>::iterator DI =
8450b57cec5SDimitry Andric                MaybeDeadCopies.begin();
8460b57cec5SDimitry Andric            DI != MaybeDeadCopies.end();) {
8470b57cec5SDimitry Andric         MachineInstr *MaybeDead = *DI;
848bdd1243dSDimitry Andric         std::optional<DestSourcePair> CopyOperands =
84981ad6265SDimitry Andric             isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
85081ad6265SDimitry Andric         MCRegister Reg = CopyOperands->Destination->getReg().asMCReg();
8510b57cec5SDimitry Andric         assert(!MRI->isReserved(Reg));
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric         if (!RegMask->clobbersPhysReg(Reg)) {
8540b57cec5SDimitry Andric           ++DI;
8550b57cec5SDimitry Andric           continue;
8560b57cec5SDimitry Andric         }
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
8590b57cec5SDimitry Andric                    MaybeDead->dump());
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric         // Make sure we invalidate any entries in the copy maps before erasing
8620b57cec5SDimitry Andric         // the instruction.
86381ad6265SDimitry Andric         Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric         // erase() will return the next valid iterator pointing to the next
8660b57cec5SDimitry Andric         // element after the erased one.
8670b57cec5SDimitry Andric         DI = MaybeDeadCopies.erase(DI);
8680b57cec5SDimitry Andric         MaybeDead->eraseFromParent();
8690b57cec5SDimitry Andric         Changed = true;
8700b57cec5SDimitry Andric         ++NumDeletes;
8710b57cec5SDimitry Andric       }
8720b57cec5SDimitry Andric     }
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric     // Any previous copy definition or reading the Defs is no longer available.
875e8d8bef9SDimitry Andric     for (MCRegister Reg : Defs)
87681ad6265SDimitry Andric       Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
8770b57cec5SDimitry Andric   }
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric   // If MBB doesn't have successors, delete the copies whose defs are not used.
8800b57cec5SDimitry Andric   // If MBB does have successors, then conservative assume the defs are live-out
8810b57cec5SDimitry Andric   // since we don't want to trust live-in lists.
8820b57cec5SDimitry Andric   if (MBB.succ_empty()) {
8830b57cec5SDimitry Andric     for (MachineInstr *MaybeDead : MaybeDeadCopies) {
8840b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
8850b57cec5SDimitry Andric                  MaybeDead->dump());
88681ad6265SDimitry Andric 
887bdd1243dSDimitry Andric       std::optional<DestSourcePair> CopyOperands =
88881ad6265SDimitry Andric           isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
88981ad6265SDimitry Andric       assert(CopyOperands);
89081ad6265SDimitry Andric 
89181ad6265SDimitry Andric       Register SrcReg = CopyOperands->Source->getReg();
89281ad6265SDimitry Andric       Register DestReg = CopyOperands->Destination->getReg();
89381ad6265SDimitry Andric       assert(!MRI->isReserved(DestReg));
8940b57cec5SDimitry Andric 
8958bcb0991SDimitry Andric       // Update matching debug values, if any.
896fe6060f1SDimitry Andric       SmallVector<MachineInstr *> MaybeDeadDbgUsers(
897fe6060f1SDimitry Andric           CopyDbgUsers[MaybeDead].begin(), CopyDbgUsers[MaybeDead].end());
898fe6060f1SDimitry Andric       MRI->updateDbgUsersToReg(DestReg.asMCReg(), SrcReg.asMCReg(),
899fe6060f1SDimitry Andric                                MaybeDeadDbgUsers);
9000b57cec5SDimitry Andric 
9010b57cec5SDimitry Andric       MaybeDead->eraseFromParent();
9020b57cec5SDimitry Andric       Changed = true;
9030b57cec5SDimitry Andric       ++NumDeletes;
9040b57cec5SDimitry Andric     }
9050b57cec5SDimitry Andric   }
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric   MaybeDeadCopies.clear();
9088bcb0991SDimitry Andric   CopyDbgUsers.clear();
9090b57cec5SDimitry Andric   Tracker.clear();
9100b57cec5SDimitry Andric }
9110b57cec5SDimitry Andric 
91206c3fb27SDimitry Andric static bool isBackwardPropagatableCopy(const DestSourcePair &CopyOperands,
91381ad6265SDimitry Andric                                        const MachineRegisterInfo &MRI,
91406c3fb27SDimitry Andric                                        const TargetInstrInfo &TII) {
91506c3fb27SDimitry Andric   Register Def = CopyOperands.Destination->getReg();
91606c3fb27SDimitry Andric   Register Src = CopyOperands.Source->getReg();
917480093f4SDimitry Andric 
918480093f4SDimitry Andric   if (!Def || !Src)
919480093f4SDimitry Andric     return false;
920480093f4SDimitry Andric 
921480093f4SDimitry Andric   if (MRI.isReserved(Def) || MRI.isReserved(Src))
922480093f4SDimitry Andric     return false;
923480093f4SDimitry Andric 
92406c3fb27SDimitry Andric   return CopyOperands.Source->isRenamable() && CopyOperands.Source->isKill();
925480093f4SDimitry Andric }
926480093f4SDimitry Andric 
927480093f4SDimitry Andric void MachineCopyPropagation::propagateDefs(MachineInstr &MI) {
928480093f4SDimitry Andric   if (!Tracker.hasAnyCopies())
929480093f4SDimitry Andric     return;
930480093f4SDimitry Andric 
931480093f4SDimitry Andric   for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx != OpEnd;
932480093f4SDimitry Andric        ++OpIdx) {
933480093f4SDimitry Andric     MachineOperand &MODef = MI.getOperand(OpIdx);
934480093f4SDimitry Andric 
935480093f4SDimitry Andric     if (!MODef.isReg() || MODef.isUse())
936480093f4SDimitry Andric       continue;
937480093f4SDimitry Andric 
938480093f4SDimitry Andric     // Ignore non-trivial cases.
939480093f4SDimitry Andric     if (MODef.isTied() || MODef.isUndef() || MODef.isImplicit())
940480093f4SDimitry Andric       continue;
941480093f4SDimitry Andric 
942480093f4SDimitry Andric     if (!MODef.getReg())
943480093f4SDimitry Andric       continue;
944480093f4SDimitry Andric 
945480093f4SDimitry Andric     // We only handle if the register comes from a vreg.
946480093f4SDimitry Andric     if (!MODef.isRenamable())
947480093f4SDimitry Andric       continue;
948480093f4SDimitry Andric 
94981ad6265SDimitry Andric     MachineInstr *Copy = Tracker.findAvailBackwardCopy(
95081ad6265SDimitry Andric         MI, MODef.getReg().asMCReg(), *TRI, *TII, UseCopyInstr);
951480093f4SDimitry Andric     if (!Copy)
952480093f4SDimitry Andric       continue;
953480093f4SDimitry Andric 
954bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
95581ad6265SDimitry Andric         isCopyInstr(*Copy, *TII, UseCopyInstr);
95681ad6265SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
95781ad6265SDimitry Andric     Register Src = CopyOperands->Source->getReg();
958480093f4SDimitry Andric 
959480093f4SDimitry Andric     if (MODef.getReg() != Src)
960480093f4SDimitry Andric       continue;
961480093f4SDimitry Andric 
962480093f4SDimitry Andric     if (!isBackwardPropagatableRegClassCopy(*Copy, MI, OpIdx))
963480093f4SDimitry Andric       continue;
964480093f4SDimitry Andric 
965480093f4SDimitry Andric     if (hasImplicitOverlap(MI, MODef))
966480093f4SDimitry Andric       continue;
967480093f4SDimitry Andric 
968e8d8bef9SDimitry Andric     if (hasOverlappingMultipleDef(MI, MODef, Def))
969e8d8bef9SDimitry Andric       continue;
970e8d8bef9SDimitry Andric 
971480093f4SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MODef.getReg(), TRI)
972480093f4SDimitry Andric                       << "\n     with " << printReg(Def, TRI) << "\n     in "
973480093f4SDimitry Andric                       << MI << "     from " << *Copy);
974480093f4SDimitry Andric 
975480093f4SDimitry Andric     MODef.setReg(Def);
97681ad6265SDimitry Andric     MODef.setIsRenamable(CopyOperands->Destination->isRenamable());
977480093f4SDimitry Andric 
978480093f4SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
979480093f4SDimitry Andric     MaybeDeadCopies.insert(Copy);
980480093f4SDimitry Andric     Changed = true;
981480093f4SDimitry Andric     ++NumCopyBackwardPropagated;
982480093f4SDimitry Andric   }
983480093f4SDimitry Andric }
984480093f4SDimitry Andric 
985480093f4SDimitry Andric void MachineCopyPropagation::BackwardCopyPropagateBlock(
986480093f4SDimitry Andric     MachineBasicBlock &MBB) {
987480093f4SDimitry Andric   LLVM_DEBUG(dbgs() << "MCP: BackwardCopyPropagateBlock " << MBB.getName()
988480093f4SDimitry Andric                     << "\n");
989480093f4SDimitry Andric 
9900eae32dcSDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(MBB))) {
991480093f4SDimitry Andric     // Ignore non-trivial COPYs.
992bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
993bdd1243dSDimitry Andric         isCopyInstr(MI, *TII, UseCopyInstr);
99481ad6265SDimitry Andric     if (CopyOperands && MI.getNumOperands() == 2) {
99581ad6265SDimitry Andric       Register DefReg = CopyOperands->Destination->getReg();
99681ad6265SDimitry Andric       Register SrcReg = CopyOperands->Source->getReg();
997480093f4SDimitry Andric 
99881ad6265SDimitry Andric       if (!TRI->regsOverlap(DefReg, SrcReg)) {
999480093f4SDimitry Andric         // Unlike forward cp, we don't invoke propagateDefs here,
1000480093f4SDimitry Andric         // just let forward cp do COPY-to-COPY propagation.
100106c3fb27SDimitry Andric         if (isBackwardPropagatableCopy(*CopyOperands, *MRI, *TII)) {
100206c3fb27SDimitry Andric           Tracker.invalidateRegister(SrcReg.asMCReg(), *TRI, *TII,
100306c3fb27SDimitry Andric                                      UseCopyInstr);
100406c3fb27SDimitry Andric           Tracker.invalidateRegister(DefReg.asMCReg(), *TRI, *TII,
100506c3fb27SDimitry Andric                                      UseCopyInstr);
100681ad6265SDimitry Andric           Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
1007480093f4SDimitry Andric           continue;
1008480093f4SDimitry Andric         }
1009480093f4SDimitry Andric       }
101081ad6265SDimitry Andric     }
1011480093f4SDimitry Andric 
1012480093f4SDimitry Andric     // Invalidate any earlyclobber regs first.
10130eae32dcSDimitry Andric     for (const MachineOperand &MO : MI.operands())
1014480093f4SDimitry Andric       if (MO.isReg() && MO.isEarlyClobber()) {
1015e8d8bef9SDimitry Andric         MCRegister Reg = MO.getReg().asMCReg();
1016480093f4SDimitry Andric         if (!Reg)
1017480093f4SDimitry Andric           continue;
101881ad6265SDimitry Andric         Tracker.invalidateRegister(Reg, *TRI, *TII, UseCopyInstr);
1019480093f4SDimitry Andric       }
1020480093f4SDimitry Andric 
10210eae32dcSDimitry Andric     propagateDefs(MI);
10220eae32dcSDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
1023480093f4SDimitry Andric       if (!MO.isReg())
1024480093f4SDimitry Andric         continue;
1025480093f4SDimitry Andric 
1026480093f4SDimitry Andric       if (!MO.getReg())
1027480093f4SDimitry Andric         continue;
1028480093f4SDimitry Andric 
1029480093f4SDimitry Andric       if (MO.isDef())
103081ad6265SDimitry Andric         Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
103181ad6265SDimitry Andric                                    UseCopyInstr);
1032480093f4SDimitry Andric 
1033fe6060f1SDimitry Andric       if (MO.readsReg()) {
1034fe6060f1SDimitry Andric         if (MO.isDebug()) {
1035fe6060f1SDimitry Andric           //  Check if the register in the debug instruction is utilized
1036fe6060f1SDimitry Andric           // in a copy instruction, so we can update the debug info if the
1037fe6060f1SDimitry Andric           // register is changed.
103806c3fb27SDimitry Andric           for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
103906c3fb27SDimitry Andric             if (auto *Copy = Tracker.findCopyDefViaUnit(Unit, *TRI)) {
10400eae32dcSDimitry Andric               CopyDbgUsers[Copy].insert(&MI);
1041fe6060f1SDimitry Andric             }
1042fe6060f1SDimitry Andric           }
1043fe6060f1SDimitry Andric         } else {
104481ad6265SDimitry Andric           Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
104581ad6265SDimitry Andric                                      UseCopyInstr);
1046480093f4SDimitry Andric         }
1047480093f4SDimitry Andric       }
1048fe6060f1SDimitry Andric     }
1049fe6060f1SDimitry Andric   }
1050480093f4SDimitry Andric 
1051480093f4SDimitry Andric   for (auto *Copy : MaybeDeadCopies) {
1052bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
105381ad6265SDimitry Andric         isCopyInstr(*Copy, *TII, UseCopyInstr);
105481ad6265SDimitry Andric     Register Src = CopyOperands->Source->getReg();
105581ad6265SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
1056fe6060f1SDimitry Andric     SmallVector<MachineInstr *> MaybeDeadDbgUsers(CopyDbgUsers[Copy].begin(),
1057fe6060f1SDimitry Andric                                                   CopyDbgUsers[Copy].end());
1058fe6060f1SDimitry Andric 
1059fe6060f1SDimitry Andric     MRI->updateDbgUsersToReg(Src.asMCReg(), Def.asMCReg(), MaybeDeadDbgUsers);
1060480093f4SDimitry Andric     Copy->eraseFromParent();
1061480093f4SDimitry Andric     ++NumDeletes;
1062480093f4SDimitry Andric   }
1063480093f4SDimitry Andric 
1064480093f4SDimitry Andric   MaybeDeadCopies.clear();
1065480093f4SDimitry Andric   CopyDbgUsers.clear();
1066480093f4SDimitry Andric   Tracker.clear();
1067480093f4SDimitry Andric }
1068480093f4SDimitry Andric 
106906c3fb27SDimitry Andric static void LLVM_ATTRIBUTE_UNUSED printSpillReloadChain(
107006c3fb27SDimitry Andric     DenseMap<MachineInstr *, SmallVector<MachineInstr *>> &SpillChain,
107106c3fb27SDimitry Andric     DenseMap<MachineInstr *, SmallVector<MachineInstr *>> &ReloadChain,
107206c3fb27SDimitry Andric     MachineInstr *Leader) {
107306c3fb27SDimitry Andric   auto &SC = SpillChain[Leader];
107406c3fb27SDimitry Andric   auto &RC = ReloadChain[Leader];
107506c3fb27SDimitry Andric   for (auto I = SC.rbegin(), E = SC.rend(); I != E; ++I)
107606c3fb27SDimitry Andric     (*I)->dump();
107706c3fb27SDimitry Andric   for (MachineInstr *MI : RC)
107806c3fb27SDimitry Andric     MI->dump();
107906c3fb27SDimitry Andric }
108006c3fb27SDimitry Andric 
108106c3fb27SDimitry Andric // Remove spill-reload like copy chains. For example
108206c3fb27SDimitry Andric // r0 = COPY r1
108306c3fb27SDimitry Andric // r1 = COPY r2
108406c3fb27SDimitry Andric // r2 = COPY r3
108506c3fb27SDimitry Andric // r3 = COPY r4
108606c3fb27SDimitry Andric // <def-use r4>
108706c3fb27SDimitry Andric // r4 = COPY r3
108806c3fb27SDimitry Andric // r3 = COPY r2
108906c3fb27SDimitry Andric // r2 = COPY r1
109006c3fb27SDimitry Andric // r1 = COPY r0
109106c3fb27SDimitry Andric // will be folded into
109206c3fb27SDimitry Andric // r0 = COPY r1
109306c3fb27SDimitry Andric // r1 = COPY r4
109406c3fb27SDimitry Andric // <def-use r4>
109506c3fb27SDimitry Andric // r4 = COPY r1
109606c3fb27SDimitry Andric // r1 = COPY r0
109706c3fb27SDimitry Andric // TODO: Currently we don't track usage of r0 outside the chain, so we
109806c3fb27SDimitry Andric // conservatively keep its value as it was before the rewrite.
109906c3fb27SDimitry Andric //
110006c3fb27SDimitry Andric // The algorithm is trying to keep
110106c3fb27SDimitry Andric // property#1: No Def of spill COPY in the chain is used or defined until the
110206c3fb27SDimitry Andric // paired reload COPY in the chain uses the Def.
110306c3fb27SDimitry Andric //
110406c3fb27SDimitry Andric // property#2: NO Source of COPY in the chain is used or defined until the next
110506c3fb27SDimitry Andric // COPY in the chain defines the Source, except the innermost spill-reload
110606c3fb27SDimitry Andric // pair.
110706c3fb27SDimitry Andric //
110806c3fb27SDimitry Andric // The algorithm is conducted by checking every COPY inside the MBB, assuming
110906c3fb27SDimitry Andric // the COPY is a reload COPY, then try to find paired spill COPY by searching
111006c3fb27SDimitry Andric // the COPY defines the Src of the reload COPY backward. If such pair is found,
111106c3fb27SDimitry Andric // it either belongs to an existing chain or a new chain depends on
111206c3fb27SDimitry Andric // last available COPY uses the Def of the reload COPY.
111306c3fb27SDimitry Andric // Implementation notes, we use CopyTracker::findLastDefCopy(Reg, ...) to find
111406c3fb27SDimitry Andric // out last COPY that defines Reg; we use CopyTracker::findLastUseCopy(Reg, ...)
111506c3fb27SDimitry Andric // to find out last COPY that uses Reg. When we are encountered with a Non-COPY
111606c3fb27SDimitry Andric // instruction, we check registers in the operands of this instruction. If this
111706c3fb27SDimitry Andric // Reg is defined by a COPY, we untrack this Reg via
111806c3fb27SDimitry Andric // CopyTracker::clobberRegister(Reg, ...).
111906c3fb27SDimitry Andric void MachineCopyPropagation::EliminateSpillageCopies(MachineBasicBlock &MBB) {
112006c3fb27SDimitry Andric   // ChainLeader maps MI inside a spill-reload chain to its innermost reload COPY.
112106c3fb27SDimitry Andric   // Thus we can track if a MI belongs to an existing spill-reload chain.
112206c3fb27SDimitry Andric   DenseMap<MachineInstr *, MachineInstr *> ChainLeader;
112306c3fb27SDimitry Andric   // SpillChain maps innermost reload COPY of a spill-reload chain to a sequence
112406c3fb27SDimitry Andric   // of COPYs that forms spills of a spill-reload chain.
112506c3fb27SDimitry Andric   // ReloadChain maps innermost reload COPY of a spill-reload chain to a
112606c3fb27SDimitry Andric   // sequence of COPYs that forms reloads of a spill-reload chain.
112706c3fb27SDimitry Andric   DenseMap<MachineInstr *, SmallVector<MachineInstr *>> SpillChain, ReloadChain;
112806c3fb27SDimitry Andric   // If a COPY's Source has use or def until next COPY defines the Source,
112906c3fb27SDimitry Andric   // we put the COPY in this set to keep property#2.
113006c3fb27SDimitry Andric   DenseSet<const MachineInstr *> CopySourceInvalid;
113106c3fb27SDimitry Andric 
113206c3fb27SDimitry Andric   auto TryFoldSpillageCopies =
113306c3fb27SDimitry Andric       [&, this](const SmallVectorImpl<MachineInstr *> &SC,
113406c3fb27SDimitry Andric                 const SmallVectorImpl<MachineInstr *> &RC) {
113506c3fb27SDimitry Andric         assert(SC.size() == RC.size() && "Spill-reload should be paired");
113606c3fb27SDimitry Andric 
113706c3fb27SDimitry Andric         // We need at least 3 pairs of copies for the transformation to apply,
113806c3fb27SDimitry Andric         // because the first outermost pair cannot be removed since we don't
113906c3fb27SDimitry Andric         // recolor outside of the chain and that we need at least one temporary
114006c3fb27SDimitry Andric         // spill slot to shorten the chain. If we only have a chain of two
114106c3fb27SDimitry Andric         // pairs, we already have the shortest sequence this code can handle:
114206c3fb27SDimitry Andric         // the outermost pair for the temporary spill slot, and the pair that
114306c3fb27SDimitry Andric         // use that temporary spill slot for the other end of the chain.
114406c3fb27SDimitry Andric         // TODO: We might be able to simplify to one spill-reload pair if collecting
114506c3fb27SDimitry Andric         // more infomation about the outermost COPY.
114606c3fb27SDimitry Andric         if (SC.size() <= 2)
114706c3fb27SDimitry Andric           return;
114806c3fb27SDimitry Andric 
114906c3fb27SDimitry Andric         // If violate property#2, we don't fold the chain.
1150*5f757f3fSDimitry Andric         for (const MachineInstr *Spill : drop_begin(SC))
115106c3fb27SDimitry Andric           if (CopySourceInvalid.count(Spill))
115206c3fb27SDimitry Andric             return;
115306c3fb27SDimitry Andric 
1154*5f757f3fSDimitry Andric         for (const MachineInstr *Reload : drop_end(RC))
115506c3fb27SDimitry Andric           if (CopySourceInvalid.count(Reload))
115606c3fb27SDimitry Andric             return;
115706c3fb27SDimitry Andric 
115806c3fb27SDimitry Andric         auto CheckCopyConstraint = [this](Register Def, Register Src) {
115906c3fb27SDimitry Andric           for (const TargetRegisterClass *RC : TRI->regclasses()) {
116006c3fb27SDimitry Andric             if (RC->contains(Def) && RC->contains(Src))
116106c3fb27SDimitry Andric               return true;
116206c3fb27SDimitry Andric           }
116306c3fb27SDimitry Andric           return false;
116406c3fb27SDimitry Andric         };
116506c3fb27SDimitry Andric 
116606c3fb27SDimitry Andric         auto UpdateReg = [](MachineInstr *MI, const MachineOperand *Old,
116706c3fb27SDimitry Andric                             const MachineOperand *New) {
116806c3fb27SDimitry Andric           for (MachineOperand &MO : MI->operands()) {
116906c3fb27SDimitry Andric             if (&MO == Old)
117006c3fb27SDimitry Andric               MO.setReg(New->getReg());
117106c3fb27SDimitry Andric           }
117206c3fb27SDimitry Andric         };
117306c3fb27SDimitry Andric 
117406c3fb27SDimitry Andric         std::optional<DestSourcePair> InnerMostSpillCopy =
117506c3fb27SDimitry Andric             isCopyInstr(*SC[0], *TII, UseCopyInstr);
117606c3fb27SDimitry Andric         std::optional<DestSourcePair> OuterMostSpillCopy =
117706c3fb27SDimitry Andric             isCopyInstr(*SC.back(), *TII, UseCopyInstr);
117806c3fb27SDimitry Andric         std::optional<DestSourcePair> InnerMostReloadCopy =
117906c3fb27SDimitry Andric             isCopyInstr(*RC[0], *TII, UseCopyInstr);
118006c3fb27SDimitry Andric         std::optional<DestSourcePair> OuterMostReloadCopy =
118106c3fb27SDimitry Andric             isCopyInstr(*RC.back(), *TII, UseCopyInstr);
118206c3fb27SDimitry Andric         if (!CheckCopyConstraint(OuterMostSpillCopy->Source->getReg(),
118306c3fb27SDimitry Andric                                  InnerMostSpillCopy->Source->getReg()) ||
118406c3fb27SDimitry Andric             !CheckCopyConstraint(InnerMostReloadCopy->Destination->getReg(),
118506c3fb27SDimitry Andric                                  OuterMostReloadCopy->Destination->getReg()))
118606c3fb27SDimitry Andric           return;
118706c3fb27SDimitry Andric 
118806c3fb27SDimitry Andric         SpillageChainsLength += SC.size() + RC.size();
118906c3fb27SDimitry Andric         NumSpillageChains += 1;
119006c3fb27SDimitry Andric         UpdateReg(SC[0], InnerMostSpillCopy->Destination,
119106c3fb27SDimitry Andric                   OuterMostSpillCopy->Source);
119206c3fb27SDimitry Andric         UpdateReg(RC[0], InnerMostReloadCopy->Source,
119306c3fb27SDimitry Andric                   OuterMostReloadCopy->Destination);
119406c3fb27SDimitry Andric 
119506c3fb27SDimitry Andric         for (size_t I = 1; I < SC.size() - 1; ++I) {
119606c3fb27SDimitry Andric           SC[I]->eraseFromParent();
119706c3fb27SDimitry Andric           RC[I]->eraseFromParent();
119806c3fb27SDimitry Andric           NumDeletes += 2;
119906c3fb27SDimitry Andric         }
120006c3fb27SDimitry Andric       };
120106c3fb27SDimitry Andric 
120206c3fb27SDimitry Andric   auto IsFoldableCopy = [this](const MachineInstr &MaybeCopy) {
120306c3fb27SDimitry Andric     if (MaybeCopy.getNumImplicitOperands() > 0)
120406c3fb27SDimitry Andric       return false;
120506c3fb27SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
120606c3fb27SDimitry Andric         isCopyInstr(MaybeCopy, *TII, UseCopyInstr);
120706c3fb27SDimitry Andric     if (!CopyOperands)
120806c3fb27SDimitry Andric       return false;
120906c3fb27SDimitry Andric     Register Src = CopyOperands->Source->getReg();
121006c3fb27SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
121106c3fb27SDimitry Andric     return Src && Def && !TRI->regsOverlap(Src, Def) &&
121206c3fb27SDimitry Andric            CopyOperands->Source->isRenamable() &&
121306c3fb27SDimitry Andric            CopyOperands->Destination->isRenamable();
121406c3fb27SDimitry Andric   };
121506c3fb27SDimitry Andric 
121606c3fb27SDimitry Andric   auto IsSpillReloadPair = [&, this](const MachineInstr &Spill,
121706c3fb27SDimitry Andric                                      const MachineInstr &Reload) {
121806c3fb27SDimitry Andric     if (!IsFoldableCopy(Spill) || !IsFoldableCopy(Reload))
121906c3fb27SDimitry Andric       return false;
122006c3fb27SDimitry Andric     std::optional<DestSourcePair> SpillCopy =
122106c3fb27SDimitry Andric         isCopyInstr(Spill, *TII, UseCopyInstr);
122206c3fb27SDimitry Andric     std::optional<DestSourcePair> ReloadCopy =
122306c3fb27SDimitry Andric         isCopyInstr(Reload, *TII, UseCopyInstr);
122406c3fb27SDimitry Andric     if (!SpillCopy || !ReloadCopy)
122506c3fb27SDimitry Andric       return false;
122606c3fb27SDimitry Andric     return SpillCopy->Source->getReg() == ReloadCopy->Destination->getReg() &&
122706c3fb27SDimitry Andric            SpillCopy->Destination->getReg() == ReloadCopy->Source->getReg();
122806c3fb27SDimitry Andric   };
122906c3fb27SDimitry Andric 
123006c3fb27SDimitry Andric   auto IsChainedCopy = [&, this](const MachineInstr &Prev,
123106c3fb27SDimitry Andric                                  const MachineInstr &Current) {
123206c3fb27SDimitry Andric     if (!IsFoldableCopy(Prev) || !IsFoldableCopy(Current))
123306c3fb27SDimitry Andric       return false;
123406c3fb27SDimitry Andric     std::optional<DestSourcePair> PrevCopy =
123506c3fb27SDimitry Andric         isCopyInstr(Prev, *TII, UseCopyInstr);
123606c3fb27SDimitry Andric     std::optional<DestSourcePair> CurrentCopy =
123706c3fb27SDimitry Andric         isCopyInstr(Current, *TII, UseCopyInstr);
123806c3fb27SDimitry Andric     if (!PrevCopy || !CurrentCopy)
123906c3fb27SDimitry Andric       return false;
124006c3fb27SDimitry Andric     return PrevCopy->Source->getReg() == CurrentCopy->Destination->getReg();
124106c3fb27SDimitry Andric   };
124206c3fb27SDimitry Andric 
124306c3fb27SDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
124406c3fb27SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
124506c3fb27SDimitry Andric         isCopyInstr(MI, *TII, UseCopyInstr);
124606c3fb27SDimitry Andric 
124706c3fb27SDimitry Andric     // Update track information via non-copy instruction.
124806c3fb27SDimitry Andric     SmallSet<Register, 8> RegsToClobber;
124906c3fb27SDimitry Andric     if (!CopyOperands) {
125006c3fb27SDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
125106c3fb27SDimitry Andric         if (!MO.isReg())
125206c3fb27SDimitry Andric           continue;
125306c3fb27SDimitry Andric         Register Reg = MO.getReg();
125406c3fb27SDimitry Andric         if (!Reg)
125506c3fb27SDimitry Andric           continue;
125606c3fb27SDimitry Andric         MachineInstr *LastUseCopy =
125706c3fb27SDimitry Andric             Tracker.findLastSeenUseInCopy(Reg.asMCReg(), *TRI);
125806c3fb27SDimitry Andric         if (LastUseCopy) {
125906c3fb27SDimitry Andric           LLVM_DEBUG(dbgs() << "MCP: Copy source of\n");
126006c3fb27SDimitry Andric           LLVM_DEBUG(LastUseCopy->dump());
126106c3fb27SDimitry Andric           LLVM_DEBUG(dbgs() << "might be invalidated by\n");
126206c3fb27SDimitry Andric           LLVM_DEBUG(MI.dump());
126306c3fb27SDimitry Andric           CopySourceInvalid.insert(LastUseCopy);
126406c3fb27SDimitry Andric         }
126506c3fb27SDimitry Andric         // Must be noted Tracker.clobberRegister(Reg, ...) removes tracking of
126606c3fb27SDimitry Andric         // Reg, i.e, COPY that defines Reg is removed from the mapping as well
126706c3fb27SDimitry Andric         // as marking COPYs that uses Reg unavailable.
126806c3fb27SDimitry Andric         // We don't invoke CopyTracker::clobberRegister(Reg, ...) if Reg is not
126906c3fb27SDimitry Andric         // defined by a previous COPY, since we don't want to make COPYs uses
127006c3fb27SDimitry Andric         // Reg unavailable.
127106c3fb27SDimitry Andric         if (Tracker.findLastSeenDefInCopy(MI, Reg.asMCReg(), *TRI, *TII,
127206c3fb27SDimitry Andric                                     UseCopyInstr))
127306c3fb27SDimitry Andric           // Thus we can keep the property#1.
127406c3fb27SDimitry Andric           RegsToClobber.insert(Reg);
127506c3fb27SDimitry Andric       }
127606c3fb27SDimitry Andric       for (Register Reg : RegsToClobber) {
127706c3fb27SDimitry Andric         Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
127806c3fb27SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Reg, TRI)
127906c3fb27SDimitry Andric                           << "\n");
128006c3fb27SDimitry Andric       }
128106c3fb27SDimitry Andric       continue;
128206c3fb27SDimitry Andric     }
128306c3fb27SDimitry Andric 
128406c3fb27SDimitry Andric     Register Src = CopyOperands->Source->getReg();
128506c3fb27SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
128606c3fb27SDimitry Andric     // Check if we can find a pair spill-reload copy.
128706c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: Searching paired spill for reload: ");
128806c3fb27SDimitry Andric     LLVM_DEBUG(MI.dump());
128906c3fb27SDimitry Andric     MachineInstr *MaybeSpill =
129006c3fb27SDimitry Andric         Tracker.findLastSeenDefInCopy(MI, Src.asMCReg(), *TRI, *TII, UseCopyInstr);
129106c3fb27SDimitry Andric     bool MaybeSpillIsChained = ChainLeader.count(MaybeSpill);
129206c3fb27SDimitry Andric     if (!MaybeSpillIsChained && MaybeSpill &&
129306c3fb27SDimitry Andric         IsSpillReloadPair(*MaybeSpill, MI)) {
129406c3fb27SDimitry Andric       // Check if we already have an existing chain. Now we have a
129506c3fb27SDimitry Andric       // spill-reload pair.
129606c3fb27SDimitry Andric       // L2: r2 = COPY r3
129706c3fb27SDimitry Andric       // L5: r3 = COPY r2
129806c3fb27SDimitry Andric       // Looking for a valid COPY before L5 which uses r3.
129906c3fb27SDimitry Andric       // This can be serverial cases.
130006c3fb27SDimitry Andric       // Case #1:
130106c3fb27SDimitry Andric       // No COPY is found, which can be r3 is def-use between (L2, L5), we
130206c3fb27SDimitry Andric       // create a new chain for L2 and L5.
130306c3fb27SDimitry Andric       // Case #2:
130406c3fb27SDimitry Andric       // L2: r2 = COPY r3
130506c3fb27SDimitry Andric       // L5: r3 = COPY r2
130606c3fb27SDimitry Andric       // Such COPY is found and is L2, we create a new chain for L2 and L5.
130706c3fb27SDimitry Andric       // Case #3:
130806c3fb27SDimitry Andric       // L2: r2 = COPY r3
130906c3fb27SDimitry Andric       // L3: r1 = COPY r3
131006c3fb27SDimitry Andric       // L5: r3 = COPY r2
131106c3fb27SDimitry Andric       // we create a new chain for L2 and L5.
131206c3fb27SDimitry Andric       // Case #4:
131306c3fb27SDimitry Andric       // L2: r2 = COPY r3
131406c3fb27SDimitry Andric       // L3: r1 = COPY r3
131506c3fb27SDimitry Andric       // L4: r3 = COPY r1
131606c3fb27SDimitry Andric       // L5: r3 = COPY r2
131706c3fb27SDimitry Andric       // Such COPY won't be found since L4 defines r3. we create a new chain
131806c3fb27SDimitry Andric       // for L2 and L5.
131906c3fb27SDimitry Andric       // Case #5:
132006c3fb27SDimitry Andric       // L2: r2 = COPY r3
132106c3fb27SDimitry Andric       // L3: r3 = COPY r1
132206c3fb27SDimitry Andric       // L4: r1 = COPY r3
132306c3fb27SDimitry Andric       // L5: r3 = COPY r2
132406c3fb27SDimitry Andric       // COPY is found and is L4 which belongs to an existing chain, we add
132506c3fb27SDimitry Andric       // L2 and L5 to this chain.
132606c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Found spill: ");
132706c3fb27SDimitry Andric       LLVM_DEBUG(MaybeSpill->dump());
132806c3fb27SDimitry Andric       MachineInstr *MaybePrevReload =
132906c3fb27SDimitry Andric           Tracker.findLastSeenUseInCopy(Def.asMCReg(), *TRI);
133006c3fb27SDimitry Andric       auto Leader = ChainLeader.find(MaybePrevReload);
133106c3fb27SDimitry Andric       MachineInstr *L = nullptr;
133206c3fb27SDimitry Andric       if (Leader == ChainLeader.end() ||
133306c3fb27SDimitry Andric           (MaybePrevReload && !IsChainedCopy(*MaybePrevReload, MI))) {
133406c3fb27SDimitry Andric         L = &MI;
133506c3fb27SDimitry Andric         assert(!SpillChain.count(L) &&
133606c3fb27SDimitry Andric                "SpillChain should not have contained newly found chain");
133706c3fb27SDimitry Andric       } else {
133806c3fb27SDimitry Andric         assert(MaybePrevReload &&
133906c3fb27SDimitry Andric                "Found a valid leader through nullptr should not happend");
134006c3fb27SDimitry Andric         L = Leader->second;
134106c3fb27SDimitry Andric         assert(SpillChain[L].size() > 0 &&
134206c3fb27SDimitry Andric                "Existing chain's length should be larger than zero");
134306c3fb27SDimitry Andric       }
134406c3fb27SDimitry Andric       assert(!ChainLeader.count(&MI) && !ChainLeader.count(MaybeSpill) &&
134506c3fb27SDimitry Andric              "Newly found paired spill-reload should not belong to any chain "
134606c3fb27SDimitry Andric              "at this point");
134706c3fb27SDimitry Andric       ChainLeader.insert({MaybeSpill, L});
134806c3fb27SDimitry Andric       ChainLeader.insert({&MI, L});
134906c3fb27SDimitry Andric       SpillChain[L].push_back(MaybeSpill);
135006c3fb27SDimitry Andric       ReloadChain[L].push_back(&MI);
135106c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Chain " << L << " now is:\n");
135206c3fb27SDimitry Andric       LLVM_DEBUG(printSpillReloadChain(SpillChain, ReloadChain, L));
135306c3fb27SDimitry Andric     } else if (MaybeSpill && !MaybeSpillIsChained) {
135406c3fb27SDimitry Andric       // MaybeSpill is unable to pair with MI. That's to say adding MI makes
135506c3fb27SDimitry Andric       // the chain invalid.
135606c3fb27SDimitry Andric       // The COPY defines Src is no longer considered as a candidate of a
135706c3fb27SDimitry Andric       // valid chain. Since we expect the Def of a spill copy isn't used by
135806c3fb27SDimitry Andric       // any COPY instruction until a reload copy. For example:
135906c3fb27SDimitry Andric       // L1: r1 = COPY r2
136006c3fb27SDimitry Andric       // L2: r3 = COPY r1
136106c3fb27SDimitry Andric       // If we later have
136206c3fb27SDimitry Andric       // L1: r1 = COPY r2
136306c3fb27SDimitry Andric       // L2: r3 = COPY r1
136406c3fb27SDimitry Andric       // L3: r2 = COPY r1
136506c3fb27SDimitry Andric       // L1 and L3 can't be a valid spill-reload pair.
136606c3fb27SDimitry Andric       // Thus we keep the property#1.
136706c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Not paired spill-reload:\n");
136806c3fb27SDimitry Andric       LLVM_DEBUG(MaybeSpill->dump());
136906c3fb27SDimitry Andric       LLVM_DEBUG(MI.dump());
137006c3fb27SDimitry Andric       Tracker.clobberRegister(Src.asMCReg(), *TRI, *TII, UseCopyInstr);
137106c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Src, TRI)
137206c3fb27SDimitry Andric                         << "\n");
137306c3fb27SDimitry Andric     }
137406c3fb27SDimitry Andric     Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
137506c3fb27SDimitry Andric   }
137606c3fb27SDimitry Andric 
137706c3fb27SDimitry Andric   for (auto I = SpillChain.begin(), E = SpillChain.end(); I != E; ++I) {
137806c3fb27SDimitry Andric     auto &SC = I->second;
137906c3fb27SDimitry Andric     assert(ReloadChain.count(I->first) &&
138006c3fb27SDimitry Andric            "Reload chain of the same leader should exist");
138106c3fb27SDimitry Andric     auto &RC = ReloadChain[I->first];
138206c3fb27SDimitry Andric     TryFoldSpillageCopies(SC, RC);
138306c3fb27SDimitry Andric   }
138406c3fb27SDimitry Andric 
138506c3fb27SDimitry Andric   MaybeDeadCopies.clear();
138606c3fb27SDimitry Andric   CopyDbgUsers.clear();
138706c3fb27SDimitry Andric   Tracker.clear();
138806c3fb27SDimitry Andric }
138906c3fb27SDimitry Andric 
13900b57cec5SDimitry Andric bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
13910b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()))
13920b57cec5SDimitry Andric     return false;
13930b57cec5SDimitry Andric 
139406c3fb27SDimitry Andric   bool isSpillageCopyElimEnabled = false;
139506c3fb27SDimitry Andric   switch (EnableSpillageCopyElimination) {
139606c3fb27SDimitry Andric   case cl::BOU_UNSET:
139706c3fb27SDimitry Andric     isSpillageCopyElimEnabled =
139806c3fb27SDimitry Andric         MF.getSubtarget().enableSpillageCopyElimination();
139906c3fb27SDimitry Andric     break;
140006c3fb27SDimitry Andric   case cl::BOU_TRUE:
140106c3fb27SDimitry Andric     isSpillageCopyElimEnabled = true;
140206c3fb27SDimitry Andric     break;
140306c3fb27SDimitry Andric   case cl::BOU_FALSE:
140406c3fb27SDimitry Andric     isSpillageCopyElimEnabled = false;
140506c3fb27SDimitry Andric     break;
140606c3fb27SDimitry Andric   }
140706c3fb27SDimitry Andric 
14080b57cec5SDimitry Andric   Changed = false;
14090b57cec5SDimitry Andric 
14100b57cec5SDimitry Andric   TRI = MF.getSubtarget().getRegisterInfo();
14110b57cec5SDimitry Andric   TII = MF.getSubtarget().getInstrInfo();
14120b57cec5SDimitry Andric   MRI = &MF.getRegInfo();
14130b57cec5SDimitry Andric 
1414480093f4SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
141506c3fb27SDimitry Andric     if (isSpillageCopyElimEnabled)
141606c3fb27SDimitry Andric       EliminateSpillageCopies(MBB);
1417480093f4SDimitry Andric     BackwardCopyPropagateBlock(MBB);
1418480093f4SDimitry Andric     ForwardCopyPropagateBlock(MBB);
1419480093f4SDimitry Andric   }
14200b57cec5SDimitry Andric 
14210b57cec5SDimitry Andric   return Changed;
14220b57cec5SDimitry Andric }
142381ad6265SDimitry Andric 
142481ad6265SDimitry Andric MachineFunctionPass *
142581ad6265SDimitry Andric llvm::createMachineCopyPropagationPass(bool UseCopyInstr = false) {
142681ad6265SDimitry Andric   return new MachineCopyPropagation(UseCopyInstr);
142781ad6265SDimitry Andric }
1428