blob: 3bf8147a06c39243c3f8ff1a4c193d4289c01efc [file] [log] [blame]
Evan Cheng00b1a3c2012-01-07 03:02:36 +00001//===- 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//
Geoff Berryfabedba2017-10-03 16:59:13 +000010// This is an extremely simple MachineInstr-level copy propagation pass.
Evan Cheng00b1a3c2012-01-07 03:02:36 +000011//
Geoff Berrya2b90112018-02-27 16:59:10 +000012// This pass forwards the source of COPYs to the users of their destinations
13// when doing so is legal. For example:
14//
15// %reg1 = COPY %reg0
16// ...
17// ... = OP %reg1
18//
19// If
20// - %reg0 has not been clobbered by the time of the use of %reg1
21// - the register class constraints are satisfied
22// - the COPY def is the only value that reaches OP
23// then this pass replaces the above with:
24//
25// %reg1 = COPY %reg0
26// ...
27// ... = OP %reg0
28//
29// This pass also removes some redundant COPYs. For example:
30//
31// %R1 = COPY %R0
32// ... // No clobber of %R1
33// %R0 = COPY %R1 <<< Removed
34//
35// or
36//
37// %R1 = COPY %R0
38// ... // No clobber of %R0
39// %R1 = COPY %R0 <<< Removed
40//
Evan Cheng00b1a3c2012-01-07 03:02:36 +000041//===----------------------------------------------------------------------===//
42
Evan Cheng00b1a3c2012-01-07 03:02:36 +000043#include "llvm/ADT/DenseMap.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000044#include "llvm/ADT/STLExtras.h"
Evan Cheng00b1a3c2012-01-07 03:02:36 +000045#include "llvm/ADT/SetVector.h"
46#include "llvm/ADT/SmallVector.h"
47#include "llvm/ADT/Statistic.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000048#include "llvm/ADT/iterator_range.h"
49#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include "llvm/CodeGen/MachineFunction.h"
51#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000052#include "llvm/CodeGen/MachineInstr.h"
53#include "llvm/CodeGen/MachineOperand.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000054#include "llvm/CodeGen/MachineRegisterInfo.h"
Geoff Berrya2b90112018-02-27 16:59:10 +000055#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000056#include "llvm/CodeGen/TargetRegisterInfo.h"
57#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000058#include "llvm/MC/MCRegisterInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000059#include "llvm/Pass.h"
60#include "llvm/Support/Debug.h"
Geoff Berrya2b90112018-02-27 16:59:10 +000061#include "llvm/Support/DebugCounter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000062#include "llvm/Support/raw_ostream.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000063#include <cassert>
64#include <iterator>
65
Evan Cheng00b1a3c2012-01-07 03:02:36 +000066using namespace llvm;
67
Matthias Braun1527baa2017-05-25 21:26:32 +000068#define DEBUG_TYPE "machine-cp"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000069
Evan Cheng00b1a3c2012-01-07 03:02:36 +000070STATISTIC(NumDeletes, "Number of dead copies deleted");
Geoff Berrya2b90112018-02-27 16:59:10 +000071STATISTIC(NumCopyForwards, "Number of copy uses forwarded");
72DEBUG_COUNTER(FwdCounter, "machine-cp-fwd",
73 "Controls which register COPYs are forwarded");
Evan Cheng00b1a3c2012-01-07 03:02:36 +000074
75namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +000076
77using RegList = SmallVector<unsigned, 4>;
78using SourceMap = DenseMap<unsigned, RegList>;
79using Reg2MIMap = DenseMap<unsigned, MachineInstr *>;
Matthias Braune39ff702016-02-26 03:18:50 +000080
Geoff Berryfabedba2017-10-03 16:59:13 +000081 class MachineCopyPropagation : public MachineFunctionPass {
Evan Cheng00b1a3c2012-01-07 03:02:36 +000082 const TargetRegisterInfo *TRI;
Jakob Stoklund Olesenbb1e9832012-11-30 23:53:00 +000083 const TargetInstrInfo *TII;
Geoff Berryfabedba2017-10-03 16:59:13 +000084 const MachineRegisterInfo *MRI;
Andrew Trick9e761992012-02-08 21:22:43 +000085
Evan Cheng00b1a3c2012-01-07 03:02:36 +000086 public:
87 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +000088
Geoff Berryfabedba2017-10-03 16:59:13 +000089 MachineCopyPropagation() : MachineFunctionPass(ID) {
Matthias Braun273575d2016-02-20 03:56:36 +000090 initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
Evan Cheng00b1a3c2012-01-07 03:02:36 +000091 }
92
Matt Arsenault8f4d43a2016-06-02 00:04:26 +000093 void getAnalysisUsage(AnalysisUsage &AU) const override {
94 AU.setPreservesCFG();
95 MachineFunctionPass::getAnalysisUsage(AU);
96 }
97
Craig Topper4584cd52014-03-07 09:26:03 +000098 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Cheng00b1a3c2012-01-07 03:02:36 +000099
Derek Schuffad154c82016-03-28 17:05:30 +0000100 MachineFunctionProperties getRequiredProperties() const override {
101 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000102 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000103 }
104
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000105 private:
Matthias Braune39ff702016-02-26 03:18:50 +0000106 void ClobberRegister(unsigned Reg);
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000107 void ReadRegister(unsigned Reg);
Matthias Braunbd18d752016-02-20 03:56:39 +0000108 void CopyPropagateBlock(MachineBasicBlock &MBB);
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000109 bool eraseIfRedundant(MachineInstr &Copy, unsigned Src, unsigned Def);
Geoff Berrya2b90112018-02-27 16:59:10 +0000110 void forwardUses(MachineInstr &MI);
111 bool isForwardableRegClassCopy(const MachineInstr &Copy,
112 const MachineInstr &UseI, unsigned UseIdx);
113 bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use);
Matthias Braunbd18d752016-02-20 03:56:39 +0000114
115 /// Candidates for deletion.
116 SmallSetVector<MachineInstr*, 8> MaybeDeadCopies;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000117
Matthias Braunbd18d752016-02-20 03:56:39 +0000118 /// Def -> available copies map.
Matthias Braunc65e9042016-02-20 03:56:41 +0000119 Reg2MIMap AvailCopyMap;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000120
Matthias Braunbd18d752016-02-20 03:56:39 +0000121 /// Def -> copies map.
Matthias Braunc65e9042016-02-20 03:56:41 +0000122 Reg2MIMap CopyMap;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000123
Matthias Braunbd18d752016-02-20 03:56:39 +0000124 /// Src -> Def map
125 SourceMap SrcMap;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000126
Matthias Braunbd18d752016-02-20 03:56:39 +0000127 bool Changed;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000128 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000129
130} // end anonymous namespace
131
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000132char MachineCopyPropagation::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000133
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000134char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000135
Matthias Braun1527baa2017-05-25 21:26:32 +0000136INITIALIZE_PASS(MachineCopyPropagation, DEBUG_TYPE,
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000137 "Machine Copy Propagation Pass", false, false)
138
Matthias Braune39ff702016-02-26 03:18:50 +0000139/// Remove any entry in \p Map where the register is a subregister or equal to
140/// a register contained in \p Regs.
141static void removeRegsFromMap(Reg2MIMap &Map, const RegList &Regs,
142 const TargetRegisterInfo &TRI) {
143 for (unsigned Reg : Regs) {
144 // Source of copy is no longer available for propagation.
145 for (MCSubRegIterator SR(Reg, &TRI, true); SR.isValid(); ++SR)
146 Map.erase(*SR);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000147 }
148}
149
Matthias Braune39ff702016-02-26 03:18:50 +0000150/// Remove any entry in \p Map that is marked clobbered in \p RegMask.
151/// The map will typically have a lot fewer entries than the regmask clobbers,
152/// so this is more efficient than iterating the clobbered registers and calling
153/// ClobberRegister() on them.
154static void removeClobberedRegsFromMap(Reg2MIMap &Map,
155 const MachineOperand &RegMask) {
156 for (Reg2MIMap::iterator I = Map.begin(), E = Map.end(), Next; I != E;
157 I = Next) {
158 Next = std::next(I);
159 unsigned Reg = I->first;
160 if (RegMask.clobbersPhysReg(Reg))
161 Map.erase(I);
Evan Cheng520730f2012-01-08 19:52:28 +0000162 }
Matthias Braune39ff702016-02-26 03:18:50 +0000163}
164
165void MachineCopyPropagation::ClobberRegister(unsigned Reg) {
166 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
167 CopyMap.erase(*AI);
168 AvailCopyMap.erase(*AI);
169
170 SourceMap::iterator SI = SrcMap.find(*AI);
171 if (SI != SrcMap.end()) {
172 removeRegsFromMap(AvailCopyMap, SI->second, *TRI);
173 SrcMap.erase(SI);
174 }
175 }
Evan Cheng520730f2012-01-08 19:52:28 +0000176}
177
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000178void MachineCopyPropagation::ReadRegister(unsigned Reg) {
179 // If 'Reg' is defined by a copy, the copy is no longer a candidate
180 // for elimination.
181 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
182 Reg2MIMap::iterator CI = CopyMap.find(*AI);
183 if (CI != CopyMap.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000184 LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: ";
185 CI->second->dump());
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000186 MaybeDeadCopies.remove(CI->second);
187 }
188 }
189}
190
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000191/// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
192/// This fact may have been obscured by sub register usage or may not be true at
193/// all even though Src and Def are subregisters of the registers used in
194/// PreviousCopy. e.g.
195/// isNopCopy("ecx = COPY eax", AX, CX) == true
196/// isNopCopy("ecx = COPY eax", AH, CL) == false
197static bool isNopCopy(const MachineInstr &PreviousCopy, unsigned Src,
198 unsigned Def, const TargetRegisterInfo *TRI) {
199 unsigned PreviousSrc = PreviousCopy.getOperand(1).getReg();
200 unsigned PreviousDef = PreviousCopy.getOperand(0).getReg();
201 if (Src == PreviousSrc) {
202 assert(Def == PreviousDef);
Evan Cheng63618f92012-02-20 23:28:17 +0000203 return true;
Evan Cheng63618f92012-02-20 23:28:17 +0000204 }
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000205 if (!TRI->isSubRegister(PreviousSrc, Src))
206 return false;
207 unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
208 return SubIdx == TRI->getSubRegIndex(PreviousDef, Def);
209}
Evan Cheng63618f92012-02-20 23:28:17 +0000210
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000211/// Remove instruction \p Copy if there exists a previous copy that copies the
212/// register \p Src to the register \p Def; This may happen indirectly by
213/// copying the super registers.
214bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy, unsigned Src,
215 unsigned Def) {
216 // Avoid eliminating a copy from/to a reserved registers as we cannot predict
217 // the value (Example: The sparc zero register is writable but stays zero).
218 if (MRI->isReserved(Src) || MRI->isReserved(Def))
219 return false;
220
221 // Search for an existing copy.
222 Reg2MIMap::iterator CI = AvailCopyMap.find(Def);
223 if (CI == AvailCopyMap.end())
224 return false;
225
226 // Check that the existing copy uses the correct sub registers.
227 MachineInstr &PrevCopy = *CI->second;
Alexander Timofeev28da0672017-11-10 12:21:10 +0000228 if (PrevCopy.getOperand(0).isDead())
229 return false;
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000230 if (!isNopCopy(PrevCopy, Src, Def, TRI))
231 return false;
232
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000233 LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000234
235 // Copy was redundantly redefining either Src or Def. Remove earlier kill
236 // flags between Copy and PrevCopy because the value will be reused now.
237 assert(Copy.isCopy());
238 unsigned CopyDef = Copy.getOperand(0).getReg();
239 assert(CopyDef == Src || CopyDef == Def);
240 for (MachineInstr &MI :
241 make_range(PrevCopy.getIterator(), Copy.getIterator()))
242 MI.clearRegisterKills(CopyDef, TRI);
243
244 Copy.eraseFromParent();
245 Changed = true;
246 ++NumDeletes;
247 return true;
Evan Cheng63618f92012-02-20 23:28:17 +0000248}
249
Geoff Berrya2b90112018-02-27 16:59:10 +0000250/// Decide whether we should forward the source of \param Copy to its use in
251/// \param UseI based on the physical register class constraints of the opcode
252/// and avoiding introducing more cross-class COPYs.
253bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
254 const MachineInstr &UseI,
255 unsigned UseIdx) {
256
257 unsigned CopySrcReg = Copy.getOperand(1).getReg();
258
259 // If the new register meets the opcode register constraints, then allow
260 // forwarding.
261 if (const TargetRegisterClass *URC =
262 UseI.getRegClassConstraint(UseIdx, TII, TRI))
263 return URC->contains(CopySrcReg);
264
265 if (!UseI.isCopy())
266 return false;
267
268 /// COPYs don't have register class constraints, so if the user instruction
269 /// is a COPY, we just try to avoid introducing additional cross-class
270 /// COPYs. For example:
271 ///
272 /// RegClassA = COPY RegClassB // Copy parameter
273 /// ...
274 /// RegClassB = COPY RegClassA // UseI parameter
275 ///
276 /// which after forwarding becomes
277 ///
278 /// RegClassA = COPY RegClassB
279 /// ...
280 /// RegClassB = COPY RegClassB
281 ///
282 /// so we have reduced the number of cross-class COPYs and potentially
283 /// introduced a nop COPY that can be removed.
284 const TargetRegisterClass *UseDstRC =
285 TRI->getMinimalPhysRegClass(UseI.getOperand(0).getReg());
286
287 const TargetRegisterClass *SuperRC = UseDstRC;
288 for (TargetRegisterClass::sc_iterator SuperRCI = UseDstRC->getSuperClasses();
289 SuperRC; SuperRC = *SuperRCI++)
290 if (SuperRC->contains(CopySrcReg))
291 return true;
292
293 return false;
294}
295
296/// Check that \p MI does not have implicit uses that overlap with it's \p Use
297/// operand (the register being replaced), since these can sometimes be
298/// implicitly tied to other operands. For example, on AMDGPU:
299///
300/// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
301///
302/// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
303/// way of knowing we need to update the latter when updating the former.
304bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
305 const MachineOperand &Use) {
306 for (const MachineOperand &MIUse : MI.uses())
307 if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
308 MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
309 return true;
310
311 return false;
312}
313
314/// Look for available copies whose destination register is used by \p MI and
315/// replace the use in \p MI with the copy's source register.
316void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
317 if (AvailCopyMap.empty())
318 return;
319
320 // Look for non-tied explicit vreg uses that have an active COPY
321 // instruction that defines the physical register allocated to them.
322 // Replace the vreg with the source of the active COPY.
323 for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
324 ++OpIdx) {
325 MachineOperand &MOUse = MI.getOperand(OpIdx);
326 // Don't forward into undef use operands since doing so can cause problems
327 // with the machine verifier, since it doesn't treat undef reads as reads,
328 // so we can end up with a live range that ends on an undef read, leading to
329 // an error that the live range doesn't end on a read of the live range
330 // register.
331 if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
332 MOUse.isImplicit())
333 continue;
334
335 if (!MOUse.getReg())
336 continue;
337
338 // Check that the register is marked 'renamable' so we know it is safe to
339 // rename it without violating any constraints that aren't expressed in the
340 // IR (e.g. ABI or opcode requirements).
341 if (!MOUse.isRenamable())
342 continue;
343
344 auto CI = AvailCopyMap.find(MOUse.getReg());
345 if (CI == AvailCopyMap.end())
346 continue;
347
348 MachineInstr &Copy = *CI->second;
349 unsigned CopyDstReg = Copy.getOperand(0).getReg();
350 const MachineOperand &CopySrc = Copy.getOperand(1);
351 unsigned CopySrcReg = CopySrc.getReg();
352
353 // FIXME: Don't handle partial uses of wider COPYs yet.
354 if (MOUse.getReg() != CopyDstReg) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000355 LLVM_DEBUG(
356 dbgs() << "MCP: FIXME! Not forwarding COPY to sub-register use:\n "
357 << MI);
Geoff Berrya2b90112018-02-27 16:59:10 +0000358 continue;
359 }
360
361 // Don't forward COPYs of reserved regs unless they are constant.
362 if (MRI->isReserved(CopySrcReg) && !MRI->isConstantPhysReg(CopySrcReg))
363 continue;
364
365 if (!isForwardableRegClassCopy(Copy, MI, OpIdx))
366 continue;
367
368 if (hasImplicitOverlap(MI, MOUse))
369 continue;
370
371 if (!DebugCounter::shouldExecute(FwdCounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000372 LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n "
373 << MI);
Geoff Berrya2b90112018-02-27 16:59:10 +0000374 continue;
375 }
376
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000377 LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
378 << "\n with " << printReg(CopySrcReg, TRI)
379 << "\n in " << MI << " from " << Copy);
Geoff Berrya2b90112018-02-27 16:59:10 +0000380
381 MOUse.setReg(CopySrcReg);
382 if (!CopySrc.isRenamable())
383 MOUse.setIsRenamable(false);
384
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000385 LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
Geoff Berrya2b90112018-02-27 16:59:10 +0000386
387 // Clear kill markers that may have been invalidated.
388 for (MachineInstr &KMI :
389 make_range(Copy.getIterator(), std::next(MI.getIterator())))
390 KMI.clearRegisterKills(CopySrcReg, TRI);
391
392 ++NumCopyForwards;
393 Changed = true;
394 }
395}
396
Matthias Braunbd18d752016-02-20 03:56:39 +0000397void MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000398 LLVM_DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
James Molloyd787d3e2014-01-22 09:12:27 +0000399
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000400 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
401 MachineInstr *MI = &*I;
402 ++I;
403
Eli Friedman208fe672018-03-30 00:56:03 +0000404 // Analyze copies (which don't overlap themselves).
405 if (MI->isCopy() && !TRI->regsOverlap(MI->getOperand(0).getReg(),
406 MI->getOperand(1).getReg())) {
Geoff Berryfabedba2017-10-03 16:59:13 +0000407 unsigned Def = MI->getOperand(0).getReg();
408 unsigned Src = MI->getOperand(1).getReg();
409
410 assert(!TargetRegisterInfo::isVirtualRegister(Def) &&
411 !TargetRegisterInfo::isVirtualRegister(Src) &&
412 "MachineCopyPropagation should be run after register allocation!");
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000413
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000414 // The two copies cancel out and the source of the first copy
415 // hasn't been overridden, eliminate the second one. e.g.
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000416 // %ecx = COPY %eax
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +0000417 // ... nothing clobbered eax.
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000418 // %eax = COPY %ecx
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000419 // =>
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000420 // %ecx = COPY %eax
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000421 //
422 // or
423 //
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000424 // %ecx = COPY %eax
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +0000425 // ... nothing clobbered eax.
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000426 // %ecx = COPY %eax
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000427 // =>
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000428 // %ecx = COPY %eax
Geoff Berryfabedba2017-10-03 16:59:13 +0000429 if (eraseIfRedundant(*MI, Def, Src) || eraseIfRedundant(*MI, Src, Def))
430 continue;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000431
Geoff Berrya2b90112018-02-27 16:59:10 +0000432 forwardUses(*MI);
433
434 // Src may have been changed by forwardUses()
435 Src = MI->getOperand(1).getReg();
436
Jun Bum Lim59df5e82016-02-03 15:56:27 +0000437 // If Src is defined by a previous copy, the previous copy cannot be
438 // eliminated.
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000439 ReadRegister(Src);
440 for (const MachineOperand &MO : MI->implicit_operands()) {
441 if (!MO.isReg() || !MO.readsReg())
442 continue;
443 unsigned Reg = MO.getReg();
444 if (!Reg)
445 continue;
446 ReadRegister(Reg);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000447 }
448
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000449 LLVM_DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
James Molloyd787d3e2014-01-22 09:12:27 +0000450
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000451 // Copy is now a candidate for deletion.
Geoff Berryfabedba2017-10-03 16:59:13 +0000452 if (!MRI->isReserved(Def))
Matthias Braun273575d2016-02-20 03:56:36 +0000453 MaybeDeadCopies.insert(MI);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000454
Jun Bum Lim59df5e82016-02-03 15:56:27 +0000455 // If 'Def' is previously source of another copy, then this earlier copy's
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000456 // source is no longer available. e.g.
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000457 // %xmm9 = copy %xmm2
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000458 // ...
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000459 // %xmm2 = copy %xmm0
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000460 // ...
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000461 // %xmm2 = copy %xmm9
Geoff Berryfabedba2017-10-03 16:59:13 +0000462 ClobberRegister(Def);
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000463 for (const MachineOperand &MO : MI->implicit_operands()) {
464 if (!MO.isReg() || !MO.isDef())
465 continue;
Geoff Berryfabedba2017-10-03 16:59:13 +0000466 unsigned Reg = MO.getReg();
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000467 if (!Reg)
468 continue;
469 ClobberRegister(Reg);
470 }
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000471
Alexander Timofeev9dff31c2017-10-16 16:57:37 +0000472 // Remember Def is defined by the copy.
473 for (MCSubRegIterator SR(Def, TRI, /*IncludeSelf=*/true); SR.isValid();
474 ++SR) {
475 CopyMap[*SR] = MI;
476 AvailCopyMap[*SR] = MI;
Alexander Timofeev38282422017-10-16 14:35:29 +0000477 }
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000478
Alexander Timofeev9dff31c2017-10-16 16:57:37 +0000479 // Remember source that's copied to Def. Once it's clobbered, then
480 // it's no longer available for copy propagation.
481 RegList &DestList = SrcMap[Src];
482 if (!is_contained(DestList, Def))
483 DestList.push_back(Def);
484
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000485 continue;
486 }
487
Geoff Berrya2b90112018-02-27 16:59:10 +0000488 // Clobber any earlyclobber regs first.
489 for (const MachineOperand &MO : MI->operands())
490 if (MO.isReg() && MO.isEarlyClobber()) {
491 unsigned Reg = MO.getReg();
492 // If we have a tied earlyclobber, that means it is also read by this
493 // instruction, so we need to make sure we don't remove it as dead
494 // later.
495 if (MO.isTied())
496 ReadRegister(Reg);
497 ClobberRegister(Reg);
498 }
499
500 forwardUses(*MI);
501
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000502 // Not a copy.
503 SmallVector<unsigned, 2> Defs;
Matthias Braun273575d2016-02-20 03:56:36 +0000504 const MachineOperand *RegMask = nullptr;
505 for (const MachineOperand &MO : MI->operands()) {
Jakob Stoklund Olesen8610a592012-02-08 22:37:35 +0000506 if (MO.isRegMask())
Matthias Braun273575d2016-02-20 03:56:36 +0000507 RegMask = &MO;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000508 if (!MO.isReg())
509 continue;
Geoff Berryfabedba2017-10-03 16:59:13 +0000510 unsigned Reg = MO.getReg();
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000511 if (!Reg)
512 continue;
513
Geoff Berryfabedba2017-10-03 16:59:13 +0000514 assert(!TargetRegisterInfo::isVirtualRegister(Reg) &&
515 "MachineCopyPropagation should be run after register allocation!");
516
Geoff Berrya2b90112018-02-27 16:59:10 +0000517 if (MO.isDef() && !MO.isEarlyClobber()) {
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000518 Defs.push_back(Reg);
519 continue;
Krzysztof Parzyszek0b492f72018-07-11 13:30:27 +0000520 } else if (!MO.isDebug() && MO.readsReg())
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000521 ReadRegister(Reg);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000522 }
523
Jakob Stoklund Olesen8610a592012-02-08 22:37:35 +0000524 // The instruction has a register mask operand which means that it clobbers
Matthias Braune39ff702016-02-26 03:18:50 +0000525 // a large set of registers. Treat clobbered registers the same way as
526 // defined registers.
Matthias Braun273575d2016-02-20 03:56:36 +0000527 if (RegMask) {
Jakob Stoklund Olesen938b4d22012-02-09 00:19:08 +0000528 // Erase any MaybeDeadCopies whose destination register is clobbered.
Jun Bum Lim36c53fe2016-03-25 21:15:35 +0000529 for (SmallSetVector<MachineInstr *, 8>::iterator DI =
530 MaybeDeadCopies.begin();
531 DI != MaybeDeadCopies.end();) {
532 MachineInstr *MaybeDead = *DI;
Matthias Braun273575d2016-02-20 03:56:36 +0000533 unsigned Reg = MaybeDead->getOperand(0).getReg();
534 assert(!MRI->isReserved(Reg));
Jun Bum Lim36c53fe2016-03-25 21:15:35 +0000535
536 if (!RegMask->clobbersPhysReg(Reg)) {
537 ++DI;
Jakob Stoklund Olesen938b4d22012-02-09 00:19:08 +0000538 continue;
Jun Bum Lim36c53fe2016-03-25 21:15:35 +0000539 }
540
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000541 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
542 MaybeDead->dump());
Jun Bum Lim36c53fe2016-03-25 21:15:35 +0000543
544 // erase() will return the next valid iterator pointing to the next
545 // element after the erased one.
546 DI = MaybeDeadCopies.erase(DI);
Matthias Braun273575d2016-02-20 03:56:36 +0000547 MaybeDead->eraseFromParent();
Jakob Stoklund Olesen938b4d22012-02-09 00:19:08 +0000548 Changed = true;
549 ++NumDeletes;
550 }
Matthias Braune39ff702016-02-26 03:18:50 +0000551
552 removeClobberedRegsFromMap(AvailCopyMap, *RegMask);
553 removeClobberedRegsFromMap(CopyMap, *RegMask);
554 for (SourceMap::iterator I = SrcMap.begin(), E = SrcMap.end(), Next;
555 I != E; I = Next) {
556 Next = std::next(I);
557 if (RegMask->clobbersPhysReg(I->first)) {
558 removeRegsFromMap(AvailCopyMap, I->second, *TRI);
559 SrcMap.erase(I);
560 }
561 }
Jakob Stoklund Olesen8610a592012-02-08 22:37:35 +0000562 }
563
Matthias Braune39ff702016-02-26 03:18:50 +0000564 // Any previous copy definition or reading the Defs is no longer available.
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000565 for (unsigned Reg : Defs)
Matthias Braune39ff702016-02-26 03:18:50 +0000566 ClobberRegister(Reg);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000567 }
568
569 // If MBB doesn't have successors, delete the copies whose defs are not used.
570 // If MBB does have successors, then conservative assume the defs are live-out
571 // since we don't want to trust live-in lists.
572 if (MBB.succ_empty()) {
Matthias Braun273575d2016-02-20 03:56:36 +0000573 for (MachineInstr *MaybeDead : MaybeDeadCopies) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000574 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
575 MaybeDead->dump());
Matthias Braun273575d2016-02-20 03:56:36 +0000576 assert(!MRI->isReserved(MaybeDead->getOperand(0).getReg()));
577 MaybeDead->eraseFromParent();
578 Changed = true;
579 ++NumDeletes;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000580 }
581 }
582
Matthias Braunbd18d752016-02-20 03:56:39 +0000583 MaybeDeadCopies.clear();
584 AvailCopyMap.clear();
585 CopyMap.clear();
586 SrcMap.clear();
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000587}
588
589bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000590 if (skipFunction(MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000591 return false;
592
Matthias Braunbd18d752016-02-20 03:56:39 +0000593 Changed = false;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000594
Eric Christopherfc6de422014-08-05 02:39:49 +0000595 TRI = MF.getSubtarget().getRegisterInfo();
596 TII = MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesenc30a9af2012-10-15 21:57:41 +0000597 MRI = &MF.getRegInfo();
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000598
Matthias Braun273575d2016-02-20 03:56:36 +0000599 for (MachineBasicBlock &MBB : MF)
Matthias Braunbd18d752016-02-20 03:56:39 +0000600 CopyPropagateBlock(MBB);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000601
602 return Changed;
603}