xref: /llvm-project/llvm/lib/CodeGen/MachineCopyPropagation.cpp (revision dc0848c0293d798fecd4d02273cf98e84dc95866)
1 //===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is an extremely simple MachineInstr-level copy propagation pass.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/Passes.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetRegisterInfo.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "codegen-cp"
31 
32 STATISTIC(NumDeletes, "Number of dead copies deleted");
33 
34 namespace {
35   class MachineCopyPropagation : public MachineFunctionPass {
36     const TargetRegisterInfo *TRI;
37     const TargetInstrInfo *TII;
38     const MachineRegisterInfo *MRI;
39 
40   public:
41     static char ID; // Pass identification, replacement for typeid
42     MachineCopyPropagation() : MachineFunctionPass(ID) {
43       initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
44     }
45 
46     bool runOnMachineFunction(MachineFunction &MF) override;
47 
48   private:
49     typedef SmallVector<unsigned, 4> DestList;
50     typedef DenseMap<unsigned, DestList> SourceMap;
51     typedef DenseMap<unsigned, MachineInstr*> Reg2MIMap;
52 
53     void SourceNoLongerAvailable(unsigned Reg);
54     void CopyPropagateBlock(MachineBasicBlock &MBB);
55 
56     /// Candidates for deletion.
57     SmallSetVector<MachineInstr*, 8> MaybeDeadCopies;
58     /// Def -> available copies map.
59     Reg2MIMap AvailCopyMap;
60     /// Def -> copies map.
61     Reg2MIMap CopyMap;
62     /// Src -> Def map
63     SourceMap SrcMap;
64     bool Changed;
65   };
66 }
67 char MachineCopyPropagation::ID = 0;
68 char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
69 
70 INITIALIZE_PASS(MachineCopyPropagation, "machine-cp",
71                 "Machine Copy Propagation Pass", false, false)
72 
73 void MachineCopyPropagation::SourceNoLongerAvailable(unsigned Reg) {
74   for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
75     SourceMap::iterator SI = SrcMap.find(*AI);
76     if (SI != SrcMap.end()) {
77       const DestList& Defs = SI->second;
78       for (unsigned MappedDef : Defs) {
79         // Source of copy is no longer available for propagation.
80         for (MCSubRegIterator SR(MappedDef, TRI, true); SR.isValid(); ++SR)
81           AvailCopyMap.erase(*SR);
82       }
83     }
84   }
85 }
86 
87 static bool NoInterveningSideEffect(const MachineInstr *CopyMI,
88                                     const MachineInstr *MI) {
89   const MachineBasicBlock *MBB = CopyMI->getParent();
90   if (MI->getParent() != MBB)
91     return false;
92 
93   for (MachineBasicBlock::const_instr_iterator
94            I = std::next(CopyMI->getInstrIterator()),
95            E = MBB->instr_end(), E2 = MI->getInstrIterator();
96        I != E && I != E2; ++I) {
97     if (I->hasUnmodeledSideEffects() || I->isCall() ||
98         I->isTerminator())
99       return false;
100   }
101   return true;
102 }
103 
104 /// isNopCopy - Return true if the specified copy is really a nop. That is
105 /// if the source of the copy is the same of the definition of the copy that
106 /// supplied the source. If the source of the copy is a sub-register than it
107 /// must check the sub-indices match. e.g.
108 /// ecx = mov eax
109 /// al  = mov cl
110 /// But not
111 /// ecx = mov eax
112 /// al  = mov ch
113 static bool isNopCopy(const MachineInstr *CopyMI, unsigned Def, unsigned Src,
114                       const TargetRegisterInfo *TRI) {
115   unsigned SrcSrc = CopyMI->getOperand(1).getReg();
116   if (Def == SrcSrc)
117     return true;
118   if (TRI->isSubRegister(SrcSrc, Def)) {
119     unsigned SrcDef = CopyMI->getOperand(0).getReg();
120     unsigned SubIdx = TRI->getSubRegIndex(SrcSrc, Def);
121     if (!SubIdx)
122       return false;
123     return SubIdx == TRI->getSubRegIndex(SrcDef, Src);
124   }
125 
126   return false;
127 }
128 
129 void MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
130   DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
131 
132   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
133     MachineInstr *MI = &*I;
134     ++I;
135 
136     if (MI->isCopy()) {
137       unsigned Def = MI->getOperand(0).getReg();
138       unsigned Src = MI->getOperand(1).getReg();
139 
140       assert(!TargetRegisterInfo::isVirtualRegister(Def) &&
141              !TargetRegisterInfo::isVirtualRegister(Src) &&
142              "MachineCopyPropagation should be run after register allocation!");
143 
144       DenseMap<unsigned, MachineInstr*>::iterator CI = AvailCopyMap.find(Src);
145       if (CI != AvailCopyMap.end()) {
146         MachineInstr *CopyMI = CI->second;
147         if (!MRI->isReserved(Def) &&
148             (!MRI->isReserved(Src) || NoInterveningSideEffect(CopyMI, MI)) &&
149             isNopCopy(CopyMI, Def, Src, TRI)) {
150           // The two copies cancel out and the source of the first copy
151           // hasn't been overridden, eliminate the second one. e.g.
152           //  %ECX<def> = COPY %EAX<kill>
153           //  ... nothing clobbered EAX.
154           //  %EAX<def> = COPY %ECX
155           // =>
156           //  %ECX<def> = COPY %EAX
157           //
158           // Also avoid eliminating a copy from reserved registers unless the
159           // definition is proven not clobbered. e.g.
160           // %RSP<def> = COPY %RAX
161           // CALL
162           // %RAX<def> = COPY %RSP
163 
164           DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; MI->dump());
165 
166           // Clear any kills of Def between CopyMI and MI. This extends the
167           // live range.
168           for (MachineInstr &MMI :
169                make_range(CopyMI->getInstrIterator(), MI->getInstrIterator()))
170             MMI.clearRegisterKills(Def, TRI);
171 
172           MI->eraseFromParent();
173           Changed = true;
174           ++NumDeletes;
175           continue;
176         }
177       }
178 
179       // If Src is defined by a previous copy, the previous copy cannot be
180       // eliminated.
181       for (MCRegAliasIterator AI(Src, TRI, true); AI.isValid(); ++AI) {
182         Reg2MIMap::iterator CI = CopyMap.find(*AI);
183         if (CI != CopyMap.end()) {
184           DEBUG(dbgs() << "MCP: Copy is no longer dead: "; CI->second->dump());
185           MaybeDeadCopies.remove(CI->second);
186         }
187       }
188 
189       DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
190 
191       // Copy is now a candidate for deletion.
192       if (!MRI->isReserved(Def))
193         MaybeDeadCopies.insert(MI);
194 
195       // If 'Def' is previously source of another copy, then this earlier copy's
196       // source is no longer available. e.g.
197       // %xmm9<def> = copy %xmm2
198       // ...
199       // %xmm2<def> = copy %xmm0
200       // ...
201       // %xmm2<def> = copy %xmm9
202       SourceNoLongerAvailable(Def);
203 
204       // Remember Def is defined by the copy.
205       // ... Make sure to clear the def maps of aliases first.
206       for (MCRegAliasIterator AI(Def, TRI, false); AI.isValid(); ++AI) {
207         CopyMap.erase(*AI);
208         AvailCopyMap.erase(*AI);
209       }
210       for (MCSubRegIterator SR(Def, TRI, /*IncludeSelf=*/true); SR.isValid();
211            ++SR) {
212         CopyMap[*SR] = MI;
213         AvailCopyMap[*SR] = MI;
214       }
215 
216       // Remember source that's copied to Def. Once it's clobbered, then
217       // it's no longer available for copy propagation.
218       SmallVectorImpl<unsigned> &DestList = SrcMap[Src];
219       if (std::find(DestList.begin(), DestList.end(), Def) == DestList.end())
220         DestList.push_back(Def);
221 
222       continue;
223     }
224 
225     // Not a copy.
226     SmallVector<unsigned, 2> Defs;
227     const MachineOperand *RegMask = nullptr;
228     for (const MachineOperand &MO : MI->operands()) {
229       if (MO.isRegMask())
230         RegMask = &MO;
231       if (!MO.isReg())
232         continue;
233       unsigned Reg = MO.getReg();
234       if (!Reg)
235         continue;
236 
237       assert(!TargetRegisterInfo::isVirtualRegister(Reg) &&
238              "MachineCopyPropagation should be run after register allocation!");
239 
240       if (MO.isDef()) {
241         Defs.push_back(Reg);
242         continue;
243       }
244 
245       // If 'Reg' is defined by a copy, the copy is no longer a candidate
246       // for elimination.
247       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
248         Reg2MIMap::iterator CI = CopyMap.find(*AI);
249         if (CI != CopyMap.end()) {
250           DEBUG(dbgs() << "MCP: Copy is used - not dead: "; CI->second->dump());
251           MaybeDeadCopies.remove(CI->second);
252         }
253       }
254       // Treat undef use like defs for copy propagation but not for
255       // dead copy. We would need to do a liveness check to be sure the copy
256       // is dead for undef uses.
257       // The backends are allowed to do whatever they want with undef value
258       // and we cannot be sure this register will not be rewritten to break
259       // some false dependencies for the hardware for instance.
260       if (MO.isUndef())
261         Defs.push_back(Reg);
262     }
263 
264     // The instruction has a register mask operand which means that it clobbers
265     // a large set of registers.  It is possible to use the register mask to
266     // prune the available copies, but treat it like a basic block boundary for
267     // now.
268     if (RegMask) {
269       // Erase any MaybeDeadCopies whose destination register is clobbered.
270       for (MachineInstr *MaybeDead : MaybeDeadCopies) {
271         unsigned Reg = MaybeDead->getOperand(0).getReg();
272         assert(!MRI->isReserved(Reg));
273         if (!RegMask->clobbersPhysReg(Reg))
274           continue;
275         DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
276               MaybeDead->dump());
277         MaybeDead->eraseFromParent();
278         Changed = true;
279         ++NumDeletes;
280       }
281 
282       // Clear all data structures as if we were beginning a new basic block.
283       MaybeDeadCopies.clear();
284       AvailCopyMap.clear();
285       CopyMap.clear();
286       SrcMap.clear();
287       continue;
288     }
289 
290     for (unsigned Reg : Defs) {
291       // No longer defined by a copy.
292       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
293         CopyMap.erase(*AI);
294         AvailCopyMap.erase(*AI);
295       }
296 
297       // If 'Reg' is previously source of a copy, it is no longer available for
298       // copy propagation.
299       SourceNoLongerAvailable(Reg);
300     }
301   }
302 
303   // If MBB doesn't have successors, delete the copies whose defs are not used.
304   // If MBB does have successors, then conservative assume the defs are live-out
305   // since we don't want to trust live-in lists.
306   if (MBB.succ_empty()) {
307     for (MachineInstr *MaybeDead : MaybeDeadCopies) {
308       assert(!MRI->isReserved(MaybeDead->getOperand(0).getReg()));
309       MaybeDead->eraseFromParent();
310       Changed = true;
311       ++NumDeletes;
312     }
313   }
314 
315   MaybeDeadCopies.clear();
316   AvailCopyMap.clear();
317   CopyMap.clear();
318   SrcMap.clear();
319 }
320 
321 bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
322   if (skipOptnoneFunction(*MF.getFunction()))
323     return false;
324 
325   Changed = false;
326 
327   TRI = MF.getSubtarget().getRegisterInfo();
328   TII = MF.getSubtarget().getInstrInfo();
329   MRI = &MF.getRegInfo();
330 
331   for (MachineBasicBlock &MBB : MF)
332     CopyPropagateBlock(MBB);
333 
334   return Changed;
335 }
336