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