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