xref: /llvm-project/llvm/lib/CodeGen/MachineCopyPropagation.cpp (revision 9115c477bb6e1b686f12941d150e992649646321)
1 //===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is an extremely simple MachineInstr-level copy propagation pass.
10 //
11 // This pass forwards the source of COPYs to the users of their destinations
12 // when doing so is legal.  For example:
13 //
14 //   %reg1 = COPY %reg0
15 //   ...
16 //   ... = OP %reg1
17 //
18 // If
19 //   - %reg0 has not been clobbered by the time of the use of %reg1
20 //   - the register class constraints are satisfied
21 //   - the COPY def is the only value that reaches OP
22 // then this pass replaces the above with:
23 //
24 //   %reg1 = COPY %reg0
25 //   ...
26 //   ... = OP %reg0
27 //
28 // This pass also removes some redundant COPYs.  For example:
29 //
30 //    %R1 = COPY %R0
31 //    ... // No clobber of %R1
32 //    %R0 = COPY %R1 <<< Removed
33 //
34 // or
35 //
36 //    %R1 = COPY %R0
37 //    ... // No clobber of %R0
38 //    %R1 = COPY %R0 <<< Removed
39 //
40 //===----------------------------------------------------------------------===//
41 
42 #include "llvm/ADT/DenseMap.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/SetVector.h"
45 #include "llvm/ADT/SmallVector.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/ADT/iterator_range.h"
48 #include "llvm/CodeGen/MachineBasicBlock.h"
49 #include "llvm/CodeGen/MachineFunction.h"
50 #include "llvm/CodeGen/MachineFunctionPass.h"
51 #include "llvm/CodeGen/MachineInstr.h"
52 #include "llvm/CodeGen/MachineOperand.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/TargetInstrInfo.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/TargetSubtargetInfo.h"
57 #include "llvm/MC/MCRegisterInfo.h"
58 #include "llvm/Pass.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/DebugCounter.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include <cassert>
63 #include <iterator>
64 
65 using namespace llvm;
66 
67 #define DEBUG_TYPE "machine-cp"
68 
69 STATISTIC(NumDeletes, "Number of dead copies deleted");
70 STATISTIC(NumCopyForwards, "Number of copy uses forwarded");
71 STATISTIC(NumCopyBackwardPropagated, "Number of copy defs backward propagated");
72 DEBUG_COUNTER(FwdCounter, "machine-cp-fwd",
73               "Controls which register COPYs are forwarded");
74 
75 namespace {
76 
77 class CopyTracker {
78   struct CopyInfo {
79     MachineInstr *MI;
80     SmallVector<unsigned, 4> DefRegs;
81     bool Avail;
82   };
83 
84   DenseMap<unsigned, CopyInfo> Copies;
85 
86 public:
87   /// Mark all of the given registers and their subregisters as unavailable for
88   /// copying.
89   void markRegsUnavailable(ArrayRef<unsigned> Regs,
90                            const TargetRegisterInfo &TRI) {
91     for (unsigned Reg : Regs) {
92       // Source of copy is no longer available for propagation.
93       for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) {
94         auto CI = Copies.find(*RUI);
95         if (CI != Copies.end())
96           CI->second.Avail = false;
97       }
98     }
99   }
100 
101   /// Clobber a single register, removing it from the tracker's copy maps.
102   void clobberRegister(unsigned Reg, const TargetRegisterInfo &TRI) {
103     for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) {
104       auto I = Copies.find(*RUI);
105       if (I != Copies.end()) {
106         // When we clobber the source of a copy, we need to clobber everything
107         // it defined.
108         markRegsUnavailable(I->second.DefRegs, TRI);
109         // When we clobber the destination of a copy, we need to clobber the
110         // whole register it defined.
111         if (MachineInstr *MI = I->second.MI)
112           markRegsUnavailable({MI->getOperand(0).getReg()}, TRI);
113         // Now we can erase the copy.
114         Copies.erase(I);
115       }
116     }
117   }
118 
119   /// Add this copy's registers into the tracker's copy maps.
120   void trackCopy(MachineInstr *MI, const TargetRegisterInfo &TRI) {
121     assert(MI->isCopy() && "Tracking non-copy?");
122 
123     Register Def = MI->getOperand(0).getReg();
124     Register Src = MI->getOperand(1).getReg();
125 
126     // Remember Def is defined by the copy.
127     for (MCRegUnitIterator RUI(Def, &TRI); RUI.isValid(); ++RUI)
128       Copies[*RUI] = {MI, {}, true};
129 
130     // Remember source that's copied to Def. Once it's clobbered, then
131     // it's no longer available for copy propagation.
132     for (MCRegUnitIterator RUI(Src, &TRI); RUI.isValid(); ++RUI) {
133       auto I = Copies.insert({*RUI, {nullptr, {}, false}});
134       auto &Copy = I.first->second;
135       if (!is_contained(Copy.DefRegs, Def))
136         Copy.DefRegs.push_back(Def);
137     }
138   }
139 
140   bool hasAnyCopies() {
141     return !Copies.empty();
142   }
143 
144   MachineInstr *findCopyForUnit(unsigned RegUnit, const TargetRegisterInfo &TRI,
145                          bool MustBeAvailable = false) {
146     auto CI = Copies.find(RegUnit);
147     if (CI == Copies.end())
148       return nullptr;
149     if (MustBeAvailable && !CI->second.Avail)
150       return nullptr;
151     return CI->second.MI;
152   }
153 
154   MachineInstr *findAvailCopy(MachineInstr &DestCopy, unsigned Reg,
155                               const TargetRegisterInfo &TRI) {
156     // We check the first RegUnit here, since we'll only be interested in the
157     // copy if it copies the entire register anyway.
158     MCRegUnitIterator RUI(Reg, &TRI);
159     MachineInstr *AvailCopy =
160         findCopyForUnit(*RUI, TRI, /*MustBeAvailable=*/true);
161     if (!AvailCopy ||
162         !TRI.isSubRegisterEq(AvailCopy->getOperand(0).getReg(), Reg))
163       return nullptr;
164 
165     // Check that the available copy isn't clobbered by any regmasks between
166     // itself and the destination.
167     Register AvailSrc = AvailCopy->getOperand(1).getReg();
168     Register AvailDef = AvailCopy->getOperand(0).getReg();
169     for (const MachineInstr &MI :
170          make_range(AvailCopy->getIterator(), DestCopy.getIterator()))
171       for (const MachineOperand &MO : MI.operands())
172         if (MO.isRegMask())
173           if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
174             return nullptr;
175 
176     return AvailCopy;
177   }
178 
179   void clear() {
180     Copies.clear();
181   }
182 };
183 
184 class MachineCopyPropagation : public MachineFunctionPass {
185   const TargetRegisterInfo *TRI;
186   const TargetInstrInfo *TII;
187   const MachineRegisterInfo *MRI;
188 
189 public:
190   static char ID; // Pass identification, replacement for typeid
191 
192   MachineCopyPropagation() : MachineFunctionPass(ID) {
193     initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
194   }
195 
196   void getAnalysisUsage(AnalysisUsage &AU) const override {
197     AU.setPreservesCFG();
198     MachineFunctionPass::getAnalysisUsage(AU);
199   }
200 
201   bool runOnMachineFunction(MachineFunction &MF) override;
202 
203   MachineFunctionProperties getRequiredProperties() const override {
204     return MachineFunctionProperties().set(
205         MachineFunctionProperties::Property::NoVRegs);
206   }
207 
208 private:
209   typedef enum { DebugUse = false, RegularUse = true } DebugType;
210 
211   void ClobberRegister(unsigned Reg);
212   void ReadRegister(unsigned Reg, MachineInstr &Reader,
213                     DebugType DT);
214   void CopyPropagateBlock(MachineBasicBlock &MBB);
215   bool eraseIfRedundant(MachineInstr &Copy);
216   bool eraseIfRedundant(MachineInstr &Copy, unsigned Src, unsigned Def);
217   void forwardUses(MachineInstr &MI);
218   bool isForwardableRegClassCopy(const MachineInstr &Copy,
219                                  const MachineInstr &UseI, unsigned UseIdx);
220   bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use);
221   bool isSafeBackwardCopyPropagation(MachineInstr &Copy, MachineInstr &SrcMI);
222 
223   /// Candidates for deletion.
224   SmallSetVector<MachineInstr *, 8> MaybeDeadCopies;
225 
226   /// Multimap tracking debug users in current BB
227   DenseMap<MachineInstr*, SmallVector<MachineInstr*, 2>> CopyDbgUsers;
228 
229   CopyTracker Tracker;
230 
231   bool Changed;
232 };
233 
234 } // end anonymous namespace
235 
236 char MachineCopyPropagation::ID = 0;
237 
238 char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
239 
240 INITIALIZE_PASS(MachineCopyPropagation, DEBUG_TYPE,
241                 "Machine Copy Propagation Pass", false, false)
242 
243 void MachineCopyPropagation::ReadRegister(unsigned Reg, MachineInstr &Reader,
244                                           DebugType DT) {
245   // If 'Reg' is defined by a copy, the copy is no longer a candidate
246   // for elimination. If a copy is "read" by a debug user, record the user
247   // for propagation.
248   for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI) {
249     if (MachineInstr *Copy = Tracker.findCopyForUnit(*RUI, *TRI)) {
250       if (DT == RegularUse) {
251         LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy->dump());
252         MaybeDeadCopies.remove(Copy);
253       } else {
254         CopyDbgUsers[Copy].push_back(&Reader);
255       }
256     }
257   }
258 }
259 
260 /// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
261 /// This fact may have been obscured by sub register usage or may not be true at
262 /// all even though Src and Def are subregisters of the registers used in
263 /// PreviousCopy. e.g.
264 /// isNopCopy("ecx = COPY eax", AX, CX) == true
265 /// isNopCopy("ecx = COPY eax", AH, CL) == false
266 static bool isNopCopy(const MachineInstr &PreviousCopy, unsigned Src,
267                       unsigned Def, const TargetRegisterInfo *TRI) {
268   Register PreviousSrc = PreviousCopy.getOperand(1).getReg();
269   Register PreviousDef = PreviousCopy.getOperand(0).getReg();
270   if (Src == PreviousSrc) {
271     assert(Def == PreviousDef);
272     return true;
273   }
274   if (!TRI->isSubRegister(PreviousSrc, Src))
275     return false;
276   unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
277   return SubIdx == TRI->getSubRegIndex(PreviousDef, Def);
278 }
279 
280 bool MachineCopyPropagation::isSafeBackwardCopyPropagation(
281     MachineInstr &Copy, MachineInstr &SrcMI) {
282   MachineOperand &SrcOp = SrcMI.getOperand(0);
283   if (!(SrcOp.isReg() && SrcOp.isDef() &&
284         SrcOp.getReg() == Copy.getOperand(1).getReg() && SrcOp.isRenamable() &&
285         !SrcOp.isTied() && !SrcOp.isImplicit() &&
286         !MRI->isReserved(SrcOp.getReg())))
287     return false;
288   if (const TargetRegisterClass *URC = SrcMI.getRegClassConstraint(0, TII, TRI))
289     return URC->contains(Copy.getOperand(0).getReg());
290   return false;
291 }
292 
293 /// In a terminal BB, remove instruction \p Copy if \p Copy's src and dst are
294 /// not used or defined between \p Copy and definition point of \p Copy's src.
295 /// \p Copy's dst will be backward propagated to where \p Copy's src is defined.
296 bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy) {
297   // Only take terminal BBs into account.
298   if (!Copy.getParent()->succ_empty())
299     return false;
300   if (!Copy.getOperand(1).isRenamable() || !Copy.getOperand(1).isKill())
301     return false;
302   unsigned Def = Copy.getOperand(0).getReg();
303   unsigned Src = Copy.getOperand(1).getReg();
304   if (MRI->isReserved(Src) || MRI->isReserved(Def))
305     return false;
306   MachineBasicBlock::reverse_iterator E = Copy.getParent()->rend(), It = Copy;
307   It++;
308   MachineInstr *SrcMI = nullptr;
309   for (; It != E; ++It) {
310     if (It->readsRegister(Src, TRI) || It->readsRegister(Def, TRI))
311       return false;
312     if (It->modifiesRegister(Def, TRI))
313       return false;
314     if (It->modifiesRegister(Src, TRI)) {
315       SrcMI = &*It;
316       break;
317     }
318   }
319   if (!SrcMI)
320     return false;
321   if (!isSafeBackwardCopyPropagation(Copy, *SrcMI))
322     return false;
323   SrcMI->getOperand(0).setReg(Def);
324   SrcMI->getOperand(0).setIsRenamable(Copy.getOperand(0).isRenamable());
325   Copy.eraseFromParent();
326   ++NumCopyBackwardPropagated;
327   ++NumDeletes;
328   return true;
329 }
330 
331 /// Remove instruction \p Copy if there exists a previous copy that copies the
332 /// register \p Src to the register \p Def; This may happen indirectly by
333 /// copying the super registers.
334 bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy, unsigned Src,
335                                               unsigned Def) {
336   // Avoid eliminating a copy from/to a reserved registers as we cannot predict
337   // the value (Example: The sparc zero register is writable but stays zero).
338   if (MRI->isReserved(Src) || MRI->isReserved(Def))
339     return false;
340 
341   // Search for an existing copy.
342   MachineInstr *PrevCopy = Tracker.findAvailCopy(Copy, Def, *TRI);
343   if (!PrevCopy)
344     return false;
345 
346   // Check that the existing copy uses the correct sub registers.
347   if (PrevCopy->getOperand(0).isDead())
348     return false;
349   if (!isNopCopy(*PrevCopy, Src, Def, TRI))
350     return false;
351 
352   LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
353 
354   // Copy was redundantly redefining either Src or Def. Remove earlier kill
355   // flags between Copy and PrevCopy because the value will be reused now.
356   assert(Copy.isCopy());
357   Register CopyDef = Copy.getOperand(0).getReg();
358   assert(CopyDef == Src || CopyDef == Def);
359   for (MachineInstr &MI :
360        make_range(PrevCopy->getIterator(), Copy.getIterator()))
361     MI.clearRegisterKills(CopyDef, TRI);
362 
363   Copy.eraseFromParent();
364   Changed = true;
365   ++NumDeletes;
366   return true;
367 }
368 
369 /// Decide whether we should forward the source of \param Copy to its use in
370 /// \param UseI based on the physical register class constraints of the opcode
371 /// and avoiding introducing more cross-class COPYs.
372 bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
373                                                        const MachineInstr &UseI,
374                                                        unsigned UseIdx) {
375 
376   Register CopySrcReg = Copy.getOperand(1).getReg();
377 
378   // If the new register meets the opcode register constraints, then allow
379   // forwarding.
380   if (const TargetRegisterClass *URC =
381           UseI.getRegClassConstraint(UseIdx, TII, TRI))
382     return URC->contains(CopySrcReg);
383 
384   if (!UseI.isCopy())
385     return false;
386 
387   /// COPYs don't have register class constraints, so if the user instruction
388   /// is a COPY, we just try to avoid introducing additional cross-class
389   /// COPYs.  For example:
390   ///
391   ///   RegClassA = COPY RegClassB  // Copy parameter
392   ///   ...
393   ///   RegClassB = COPY RegClassA  // UseI parameter
394   ///
395   /// which after forwarding becomes
396   ///
397   ///   RegClassA = COPY RegClassB
398   ///   ...
399   ///   RegClassB = COPY RegClassB
400   ///
401   /// so we have reduced the number of cross-class COPYs and potentially
402   /// introduced a nop COPY that can be removed.
403   const TargetRegisterClass *UseDstRC =
404       TRI->getMinimalPhysRegClass(UseI.getOperand(0).getReg());
405 
406   const TargetRegisterClass *SuperRC = UseDstRC;
407   for (TargetRegisterClass::sc_iterator SuperRCI = UseDstRC->getSuperClasses();
408        SuperRC; SuperRC = *SuperRCI++)
409     if (SuperRC->contains(CopySrcReg))
410       return true;
411 
412   return false;
413 }
414 
415 /// Check that \p MI does not have implicit uses that overlap with it's \p Use
416 /// operand (the register being replaced), since these can sometimes be
417 /// implicitly tied to other operands.  For example, on AMDGPU:
418 ///
419 /// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
420 ///
421 /// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
422 /// way of knowing we need to update the latter when updating the former.
423 bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
424                                                 const MachineOperand &Use) {
425   for (const MachineOperand &MIUse : MI.uses())
426     if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
427         MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
428       return true;
429 
430   return false;
431 }
432 
433 /// Look for available copies whose destination register is used by \p MI and
434 /// replace the use in \p MI with the copy's source register.
435 void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
436   if (!Tracker.hasAnyCopies())
437     return;
438 
439   // Look for non-tied explicit vreg uses that have an active COPY
440   // instruction that defines the physical register allocated to them.
441   // Replace the vreg with the source of the active COPY.
442   for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
443        ++OpIdx) {
444     MachineOperand &MOUse = MI.getOperand(OpIdx);
445     // Don't forward into undef use operands since doing so can cause problems
446     // with the machine verifier, since it doesn't treat undef reads as reads,
447     // so we can end up with a live range that ends on an undef read, leading to
448     // an error that the live range doesn't end on a read of the live range
449     // register.
450     if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
451         MOUse.isImplicit())
452       continue;
453 
454     if (!MOUse.getReg())
455       continue;
456 
457     // Check that the register is marked 'renamable' so we know it is safe to
458     // rename it without violating any constraints that aren't expressed in the
459     // IR (e.g. ABI or opcode requirements).
460     if (!MOUse.isRenamable())
461       continue;
462 
463     MachineInstr *Copy = Tracker.findAvailCopy(MI, MOUse.getReg(), *TRI);
464     if (!Copy)
465       continue;
466 
467     Register CopyDstReg = Copy->getOperand(0).getReg();
468     const MachineOperand &CopySrc = Copy->getOperand(1);
469     Register CopySrcReg = CopySrc.getReg();
470 
471     // FIXME: Don't handle partial uses of wider COPYs yet.
472     if (MOUse.getReg() != CopyDstReg) {
473       LLVM_DEBUG(
474           dbgs() << "MCP: FIXME! Not forwarding COPY to sub-register use:\n  "
475                  << MI);
476       continue;
477     }
478 
479     // Don't forward COPYs of reserved regs unless they are constant.
480     if (MRI->isReserved(CopySrcReg) && !MRI->isConstantPhysReg(CopySrcReg))
481       continue;
482 
483     if (!isForwardableRegClassCopy(*Copy, MI, OpIdx))
484       continue;
485 
486     if (hasImplicitOverlap(MI, MOUse))
487       continue;
488 
489     if (!DebugCounter::shouldExecute(FwdCounter)) {
490       LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n  "
491                         << MI);
492       continue;
493     }
494 
495     LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
496                       << "\n     with " << printReg(CopySrcReg, TRI)
497                       << "\n     in " << MI << "     from " << *Copy);
498 
499     MOUse.setReg(CopySrcReg);
500     if (!CopySrc.isRenamable())
501       MOUse.setIsRenamable(false);
502 
503     LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
504 
505     // Clear kill markers that may have been invalidated.
506     for (MachineInstr &KMI :
507          make_range(Copy->getIterator(), std::next(MI.getIterator())))
508       KMI.clearRegisterKills(CopySrcReg, TRI);
509 
510     ++NumCopyForwards;
511     Changed = true;
512   }
513 }
514 
515 void MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
516   LLVM_DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
517 
518   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
519     MachineInstr *MI = &*I;
520     ++I;
521 
522     // Analyze copies (which don't overlap themselves).
523     if (MI->isCopy() && !TRI->regsOverlap(MI->getOperand(0).getReg(),
524                                           MI->getOperand(1).getReg())) {
525       Register Def = MI->getOperand(0).getReg();
526       Register Src = MI->getOperand(1).getReg();
527 
528       assert(!Register::isVirtualRegister(Def) &&
529              !Register::isVirtualRegister(Src) &&
530              "MachineCopyPropagation should be run after register allocation!");
531 
532       // In a terminal BB,
533       //  $reg0 = OP ...
534       //  ... <<< No uses of $reg0 and $reg1, no defs of $reg0 and $reg1
535       //  $reg1 = COPY $reg0 <<< $reg0 is killed
536       // =>
537       //  $reg1 = OP ...
538       //  ...
539       //  <RET>
540       if (eraseIfRedundant(*MI))
541         continue;
542 
543       // The two copies cancel out and the source of the first copy
544       // hasn't been overridden, eliminate the second one. e.g.
545       //  %ecx = COPY %eax
546       //  ... nothing clobbered eax.
547       //  %eax = COPY %ecx
548       // =>
549       //  %ecx = COPY %eax
550       //
551       // or
552       //
553       //  %ecx = COPY %eax
554       //  ... nothing clobbered eax.
555       //  %ecx = COPY %eax
556       // =>
557       //  %ecx = COPY %eax
558       if (eraseIfRedundant(*MI, Def, Src) || eraseIfRedundant(*MI, Src, Def))
559         continue;
560 
561       forwardUses(*MI);
562 
563       // Src may have been changed by forwardUses()
564       Src = MI->getOperand(1).getReg();
565 
566       // If Src is defined by a previous copy, the previous copy cannot be
567       // eliminated.
568       ReadRegister(Src, *MI, RegularUse);
569       for (const MachineOperand &MO : MI->implicit_operands()) {
570         if (!MO.isReg() || !MO.readsReg())
571           continue;
572         Register Reg = MO.getReg();
573         if (!Reg)
574           continue;
575         ReadRegister(Reg, *MI, RegularUse);
576       }
577 
578       LLVM_DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
579 
580       // Copy is now a candidate for deletion.
581       if (!MRI->isReserved(Def))
582         MaybeDeadCopies.insert(MI);
583 
584       // If 'Def' is previously source of another copy, then this earlier copy's
585       // source is no longer available. e.g.
586       // %xmm9 = copy %xmm2
587       // ...
588       // %xmm2 = copy %xmm0
589       // ...
590       // %xmm2 = copy %xmm9
591       Tracker.clobberRegister(Def, *TRI);
592       for (const MachineOperand &MO : MI->implicit_operands()) {
593         if (!MO.isReg() || !MO.isDef())
594           continue;
595         Register Reg = MO.getReg();
596         if (!Reg)
597           continue;
598         Tracker.clobberRegister(Reg, *TRI);
599       }
600 
601       Tracker.trackCopy(MI, *TRI);
602 
603       continue;
604     }
605 
606     // Clobber any earlyclobber regs first.
607     for (const MachineOperand &MO : MI->operands())
608       if (MO.isReg() && MO.isEarlyClobber()) {
609         Register Reg = MO.getReg();
610         // If we have a tied earlyclobber, that means it is also read by this
611         // instruction, so we need to make sure we don't remove it as dead
612         // later.
613         if (MO.isTied())
614           ReadRegister(Reg, *MI, RegularUse);
615         Tracker.clobberRegister(Reg, *TRI);
616       }
617 
618     forwardUses(*MI);
619 
620     // Not a copy.
621     SmallVector<unsigned, 2> Defs;
622     const MachineOperand *RegMask = nullptr;
623     for (const MachineOperand &MO : MI->operands()) {
624       if (MO.isRegMask())
625         RegMask = &MO;
626       if (!MO.isReg())
627         continue;
628       Register Reg = MO.getReg();
629       if (!Reg)
630         continue;
631 
632       assert(!Register::isVirtualRegister(Reg) &&
633              "MachineCopyPropagation should be run after register allocation!");
634 
635       if (MO.isDef() && !MO.isEarlyClobber()) {
636         Defs.push_back(Reg);
637         continue;
638       } else if (MO.readsReg())
639         ReadRegister(Reg, *MI, MO.isDebug() ? DebugUse : RegularUse);
640     }
641 
642     // The instruction has a register mask operand which means that it clobbers
643     // a large set of registers.  Treat clobbered registers the same way as
644     // defined registers.
645     if (RegMask) {
646       // Erase any MaybeDeadCopies whose destination register is clobbered.
647       for (SmallSetVector<MachineInstr *, 8>::iterator DI =
648                MaybeDeadCopies.begin();
649            DI != MaybeDeadCopies.end();) {
650         MachineInstr *MaybeDead = *DI;
651         Register Reg = MaybeDead->getOperand(0).getReg();
652         assert(!MRI->isReserved(Reg));
653 
654         if (!RegMask->clobbersPhysReg(Reg)) {
655           ++DI;
656           continue;
657         }
658 
659         LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
660                    MaybeDead->dump());
661 
662         // Make sure we invalidate any entries in the copy maps before erasing
663         // the instruction.
664         Tracker.clobberRegister(Reg, *TRI);
665 
666         // erase() will return the next valid iterator pointing to the next
667         // element after the erased one.
668         DI = MaybeDeadCopies.erase(DI);
669         MaybeDead->eraseFromParent();
670         Changed = true;
671         ++NumDeletes;
672       }
673     }
674 
675     // Any previous copy definition or reading the Defs is no longer available.
676     for (unsigned Reg : Defs)
677       Tracker.clobberRegister(Reg, *TRI);
678   }
679 
680   // If MBB doesn't have successors, delete the copies whose defs are not used.
681   // If MBB does have successors, then conservative assume the defs are live-out
682   // since we don't want to trust live-in lists.
683   if (MBB.succ_empty()) {
684     for (MachineInstr *MaybeDead : MaybeDeadCopies) {
685       LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
686                  MaybeDead->dump());
687       assert(!MRI->isReserved(MaybeDead->getOperand(0).getReg()));
688 
689       // Update matching debug values, if any.
690       assert(MaybeDead->isCopy());
691       unsigned SrcReg = MaybeDead->getOperand(1).getReg();
692       MRI->updateDbgUsersToReg(SrcReg, CopyDbgUsers[MaybeDead]);
693 
694       MaybeDead->eraseFromParent();
695       Changed = true;
696       ++NumDeletes;
697     }
698   }
699 
700   MaybeDeadCopies.clear();
701   CopyDbgUsers.clear();
702   Tracker.clear();
703 }
704 
705 bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
706   if (skipFunction(MF.getFunction()))
707     return false;
708 
709   Changed = false;
710 
711   TRI = MF.getSubtarget().getRegisterInfo();
712   TII = MF.getSubtarget().getInstrInfo();
713   MRI = &MF.getRegInfo();
714 
715   for (MachineBasicBlock &MBB : MF)
716     CopyPropagateBlock(MBB);
717 
718   return Changed;
719 }
720