xref: /llvm-project/llvm/lib/CodeGen/MachineCopyPropagation.cpp (revision c5b668deb8848bca64e71efab5a3477857548e0f)
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_iterator I = std::next(CopyMI->getIterator()),
94        E = MBB->end(), E2 = MI->getIterator(); I != E && I != E2; ++I) {
95     if (I->hasUnmodeledSideEffects() || I->isCall() ||
96         I->isTerminator())
97       return false;
98   }
99   return true;
100 }
101 
102 /// isNopCopy - Return true if the specified copy is really a nop. That is
103 /// if the source of the copy is the same of the definition of the copy that
104 /// supplied the source. If the source of the copy is a sub-register than it
105 /// must check the sub-indices match. e.g.
106 /// ecx = mov eax
107 /// al  = mov cl
108 /// But not
109 /// ecx = mov eax
110 /// al  = mov ch
111 static bool isNopCopy(const MachineInstr *CopyMI, unsigned Def, unsigned Src,
112                       const TargetRegisterInfo *TRI) {
113   unsigned SrcSrc = CopyMI->getOperand(1).getReg();
114   if (Def == SrcSrc)
115     return true;
116   if (TRI->isSubRegister(SrcSrc, Def)) {
117     unsigned SrcDef = CopyMI->getOperand(0).getReg();
118     unsigned SubIdx = TRI->getSubRegIndex(SrcSrc, Def);
119     if (!SubIdx)
120       return false;
121     return SubIdx == TRI->getSubRegIndex(SrcDef, Src);
122   }
123 
124   return false;
125 }
126 
127 void MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
128   DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
129 
130   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
131     MachineInstr *MI = &*I;
132     ++I;
133 
134     if (MI->isCopy()) {
135       unsigned Def = MI->getOperand(0).getReg();
136       unsigned Src = MI->getOperand(1).getReg();
137 
138       assert(!TargetRegisterInfo::isVirtualRegister(Def) &&
139              !TargetRegisterInfo::isVirtualRegister(Src) &&
140              "MachineCopyPropagation should be run after register allocation!");
141 
142       DenseMap<unsigned, MachineInstr*>::iterator CI = AvailCopyMap.find(Src);
143       if (CI != AvailCopyMap.end()) {
144         MachineInstr *CopyMI = CI->second;
145         if (!MRI->isReserved(Def) &&
146             (!MRI->isReserved(Src) || NoInterveningSideEffect(CopyMI, MI)) &&
147             isNopCopy(CopyMI, Def, Src, TRI)) {
148           // The two copies cancel out and the source of the first copy
149           // hasn't been overridden, eliminate the second one. e.g.
150           //  %ECX<def> = COPY %EAX<kill>
151           //  ... nothing clobbered EAX.
152           //  %EAX<def> = COPY %ECX
153           // =>
154           //  %ECX<def> = COPY %EAX
155           //
156           // Also avoid eliminating a copy from reserved registers unless the
157           // definition is proven not clobbered. e.g.
158           // %RSP<def> = COPY %RAX
159           // CALL
160           // %RAX<def> = COPY %RSP
161 
162           DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; MI->dump());
163 
164           // Clear any kills of Def between CopyMI and MI. This extends the
165           // live range.
166           for (MachineInstr &MMI
167                : make_range(CopyMI->getIterator(), MI->getIterator()))
168             MMI.clearRegisterKills(Def, TRI);
169 
170           MI->eraseFromParent();
171           Changed = true;
172           ++NumDeletes;
173           continue;
174         }
175       }
176 
177       // If Src is defined by a previous copy, the previous copy cannot be
178       // eliminated.
179       for (MCRegAliasIterator AI(Src, TRI, true); AI.isValid(); ++AI) {
180         Reg2MIMap::iterator CI = CopyMap.find(*AI);
181         if (CI != CopyMap.end()) {
182           DEBUG(dbgs() << "MCP: Copy is no longer dead: "; CI->second->dump());
183           MaybeDeadCopies.remove(CI->second);
184         }
185       }
186 
187       DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
188 
189       // Copy is now a candidate for deletion.
190       if (!MRI->isReserved(Def))
191         MaybeDeadCopies.insert(MI);
192 
193       // If 'Def' is previously source of another copy, then this earlier copy's
194       // source is no longer available. e.g.
195       // %xmm9<def> = copy %xmm2
196       // ...
197       // %xmm2<def> = copy %xmm0
198       // ...
199       // %xmm2<def> = copy %xmm9
200       SourceNoLongerAvailable(Def);
201 
202       // Remember Def is defined by the copy.
203       // ... Make sure to clear the def maps of aliases first.
204       for (MCRegAliasIterator AI(Def, TRI, false); AI.isValid(); ++AI) {
205         CopyMap.erase(*AI);
206         AvailCopyMap.erase(*AI);
207       }
208       for (MCSubRegIterator SR(Def, TRI, /*IncludeSelf=*/true); SR.isValid();
209            ++SR) {
210         CopyMap[*SR] = MI;
211         AvailCopyMap[*SR] = MI;
212       }
213 
214       // Remember source that's copied to Def. Once it's clobbered, then
215       // it's no longer available for copy propagation.
216       SmallVectorImpl<unsigned> &DestList = SrcMap[Src];
217       if (std::find(DestList.begin(), DestList.end(), Def) == DestList.end())
218         DestList.push_back(Def);
219 
220       continue;
221     }
222 
223     // Not a copy.
224     SmallVector<unsigned, 2> Defs;
225     const MachineOperand *RegMask = nullptr;
226     for (const MachineOperand &MO : MI->operands()) {
227       if (MO.isRegMask())
228         RegMask = &MO;
229       if (!MO.isReg())
230         continue;
231       unsigned Reg = MO.getReg();
232       if (!Reg)
233         continue;
234 
235       assert(!TargetRegisterInfo::isVirtualRegister(Reg) &&
236              "MachineCopyPropagation should be run after register allocation!");
237 
238       if (MO.isDef()) {
239         Defs.push_back(Reg);
240         continue;
241       }
242 
243       // If 'Reg' is defined by a copy, the copy is no longer a candidate
244       // for elimination.
245       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
246         Reg2MIMap::iterator CI = CopyMap.find(*AI);
247         if (CI != CopyMap.end()) {
248           DEBUG(dbgs() << "MCP: Copy is used - not dead: "; CI->second->dump());
249           MaybeDeadCopies.remove(CI->second);
250         }
251       }
252       // Treat undef use like defs for copy propagation but not for
253       // dead copy. We would need to do a liveness check to be sure the copy
254       // is dead for undef uses.
255       // The backends are allowed to do whatever they want with undef value
256       // and we cannot be sure this register will not be rewritten to break
257       // some false dependencies for the hardware for instance.
258       if (MO.isUndef())
259         Defs.push_back(Reg);
260     }
261 
262     // The instruction has a register mask operand which means that it clobbers
263     // a large set of registers.  It is possible to use the register mask to
264     // prune the available copies, but treat it like a basic block boundary for
265     // now.
266     if (RegMask) {
267       // Erase any MaybeDeadCopies whose destination register is clobbered.
268       for (MachineInstr *MaybeDead : MaybeDeadCopies) {
269         unsigned Reg = MaybeDead->getOperand(0).getReg();
270         assert(!MRI->isReserved(Reg));
271         if (!RegMask->clobbersPhysReg(Reg))
272           continue;
273         DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
274               MaybeDead->dump());
275         MaybeDead->eraseFromParent();
276         Changed = true;
277         ++NumDeletes;
278       }
279 
280       // Clear all data structures as if we were beginning a new basic block.
281       MaybeDeadCopies.clear();
282       AvailCopyMap.clear();
283       CopyMap.clear();
284       SrcMap.clear();
285       continue;
286     }
287 
288     for (unsigned Reg : Defs) {
289       // No longer defined by a copy.
290       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
291         CopyMap.erase(*AI);
292         AvailCopyMap.erase(*AI);
293       }
294 
295       // If 'Reg' is previously source of a copy, it is no longer available for
296       // copy propagation.
297       SourceNoLongerAvailable(Reg);
298     }
299   }
300 
301   // If MBB doesn't have successors, delete the copies whose defs are not used.
302   // If MBB does have successors, then conservative assume the defs are live-out
303   // since we don't want to trust live-in lists.
304   if (MBB.succ_empty()) {
305     for (MachineInstr *MaybeDead : MaybeDeadCopies) {
306       assert(!MRI->isReserved(MaybeDead->getOperand(0).getReg()));
307       MaybeDead->eraseFromParent();
308       Changed = true;
309       ++NumDeletes;
310     }
311   }
312 
313   MaybeDeadCopies.clear();
314   AvailCopyMap.clear();
315   CopyMap.clear();
316   SrcMap.clear();
317 }
318 
319 bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
320   if (skipOptnoneFunction(*MF.getFunction()))
321     return false;
322 
323   Changed = false;
324 
325   TRI = MF.getSubtarget().getRegisterInfo();
326   TII = MF.getSubtarget().getInstrInfo();
327   MRI = &MF.getRegInfo();
328 
329   for (MachineBasicBlock &MBB : MF)
330     CopyPropagateBlock(MBB);
331 
332   return Changed;
333 }
334