blob: 19879fe890078c51a6881c677b1823d2ce0425de [file] [log] [blame]
Evan Cheng977679d2012-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 Berryc3ef7ae2017-10-03 16:59:13 +000010// This is an extremely simple MachineInstr-level copy propagation pass.
Evan Cheng977679d2012-01-07 03:02:36 +000011//
Geoff Berry1bfec902018-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 Cheng977679d2012-01-07 03:02:36 +000041//===----------------------------------------------------------------------===//
42
Evan Cheng977679d2012-01-07 03:02:36 +000043#include "llvm/ADT/DenseMap.h"
Eugene Zelenko7cf6af52017-08-29 22:32:07 +000044#include "llvm/ADT/STLExtras.h"
Evan Cheng977679d2012-01-07 03:02:36 +000045#include "llvm/ADT/SetVector.h"
46#include "llvm/ADT/SmallVector.h"
47#include "llvm/ADT/Statistic.h"
Eugene Zelenko7cf6af52017-08-29 22:32:07 +000048#include "llvm/ADT/iterator_range.h"
49#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000050#include "llvm/CodeGen/MachineFunction.h"
51#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko7cf6af52017-08-29 22:32:07 +000052#include "llvm/CodeGen/MachineInstr.h"
53#include "llvm/CodeGen/MachineOperand.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000054#include "llvm/CodeGen/MachineRegisterInfo.h"
Geoff Berry1bfec902018-02-27 16:59:10 +000055#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000056#include "llvm/CodeGen/TargetRegisterInfo.h"
57#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko7cf6af52017-08-29 22:32:07 +000058#include "llvm/MC/MCRegisterInfo.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000059#include "llvm/Pass.h"
60#include "llvm/Support/Debug.h"
Geoff Berry1bfec902018-02-27 16:59:10 +000061#include "llvm/Support/DebugCounter.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000062#include "llvm/Support/raw_ostream.h"
Eugene Zelenko7cf6af52017-08-29 22:32:07 +000063#include <cassert>
64#include <iterator>
65
Evan Cheng977679d2012-01-07 03:02:36 +000066using namespace llvm;
67
Matthias Braun94c49042017-05-25 21:26:32 +000068#define DEBUG_TYPE "machine-cp"
Chandler Carruth8677f2f2014-04-22 02:02:50 +000069
Evan Cheng977679d2012-01-07 03:02:36 +000070STATISTIC(NumDeletes, "Number of dead copies deleted");
Geoff Berry1bfec902018-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 Cheng977679d2012-01-07 03:02:36 +000074
75namespace {
Eugene Zelenko7cf6af52017-08-29 22:32:07 +000076
Justin Bogner97eaa642018-09-21 00:51:04 +000077class CopyTracker {
Justin Bognerdb467842018-10-22 19:51:31 +000078 struct CopyInfo {
79 MachineInstr *MI;
80 SmallVector<unsigned, 4> DefRegs;
81 bool Avail;
82 };
Justin Bogner97eaa642018-09-21 00:51:04 +000083
Justin Bognerdb467842018-10-22 19:51:31 +000084 DenseMap<unsigned, CopyInfo> Copies;
Justin Bogner97eaa642018-09-21 00:51:04 +000085
86public:
87 /// Mark all of the given registers and their subregisters as unavailable for
88 /// copying.
Justin Bognerdb467842018-10-22 19:51:31 +000089 void markRegsUnavailable(ArrayRef<unsigned> Regs,
90 const TargetRegisterInfo &TRI) {
Justin Bogner97eaa642018-09-21 00:51:04 +000091 for (unsigned Reg : Regs) {
92 // Source of copy is no longer available for propagation.
Justin Bognerdb467842018-10-22 19:51:31 +000093 for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) {
94 auto CI = Copies.find(*RUI);
95 if (CI != Copies.end())
96 CI->second.Avail = false;
97 }
Justin Bogner97eaa642018-09-21 00:51:04 +000098 }
99 }
100
Justin Bogner97eaa642018-09-21 00:51:04 +0000101 /// Clobber a single register, removing it from the tracker's copy maps.
102 void clobberRegister(unsigned Reg, const TargetRegisterInfo &TRI) {
Justin Bognerdb467842018-10-22 19:51:31 +0000103 for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) {
104 auto I = Copies.find(*RUI);
105 if (I != Copies.end()) {
106 // When we clobber the source of a copy, we need to clobber everything
107 // it defined.
108 markRegsUnavailable(I->second.DefRegs, TRI);
109 // When we clobber the destination of a copy, we need to clobber the
110 // whole register it defined.
111 if (MachineInstr *MI = I->second.MI)
112 markRegsUnavailable({MI->getOperand(0).getReg()}, TRI);
113 // Now we can erase the copy.
114 Copies.erase(I);
Justin Bogner97eaa642018-09-21 00:51:04 +0000115 }
116 }
117 }
118
119 /// Add this copy's registers into the tracker's copy maps.
Justin Bognerdb467842018-10-22 19:51:31 +0000120 void trackCopy(MachineInstr *MI, const TargetRegisterInfo &TRI) {
121 assert(MI->isCopy() && "Tracking non-copy?");
Justin Bogner97eaa642018-09-21 00:51:04 +0000122
Justin Bognerdb467842018-10-22 19:51:31 +0000123 unsigned Def = MI->getOperand(0).getReg();
124 unsigned Src = MI->getOperand(1).getReg();
Justin Bogner97eaa642018-09-21 00:51:04 +0000125
126 // Remember Def is defined by the copy.
Justin Bognerdb467842018-10-22 19:51:31 +0000127 for (MCRegUnitIterator RUI(Def, &TRI); RUI.isValid(); ++RUI)
128 Copies[*RUI] = {MI, {}, true};
Justin Bogner97eaa642018-09-21 00:51:04 +0000129
130 // Remember source that's copied to Def. Once it's clobbered, then
131 // it's no longer available for copy propagation.
Justin Bognerdb467842018-10-22 19:51:31 +0000132 for (MCRegUnitIterator RUI(Src, &TRI); RUI.isValid(); ++RUI) {
133 auto I = Copies.insert({*RUI, {nullptr, {}, false}});
134 auto &Copy = I.first->second;
135 if (!is_contained(Copy.DefRegs, Def))
136 Copy.DefRegs.push_back(Def);
137 }
Justin Bogner97eaa642018-09-21 00:51:04 +0000138 }
139
Justin Bognerdb467842018-10-22 19:51:31 +0000140 bool hasAnyCopies() {
141 return !Copies.empty();
142 }
Justin Bogner97eaa642018-09-21 00:51:04 +0000143
Justin Bognerdb467842018-10-22 19:51:31 +0000144 MachineInstr *findCopyForUnit(unsigned RegUnit, const TargetRegisterInfo &TRI,
145 bool MustBeAvailable = false) {
146 auto CI = Copies.find(RegUnit);
147 if (CI == Copies.end())
Justin Bogner60a5c772018-09-25 04:45:25 +0000148 return nullptr;
Justin Bognerdb467842018-10-22 19:51:31 +0000149 if (MustBeAvailable && !CI->second.Avail)
150 return nullptr;
151 return CI->second.MI;
152 }
153
154 MachineInstr *findAvailCopy(MachineInstr &DestCopy, unsigned Reg,
155 const TargetRegisterInfo &TRI) {
156 // We check the first RegUnit here, since we'll only be interested in the
157 // copy if it copies the entire register anyway.
158 MCRegUnitIterator RUI(Reg, &TRI);
159 MachineInstr *AvailCopy =
160 findCopyForUnit(*RUI, TRI, /*MustBeAvailable=*/true);
161 if (!AvailCopy ||
162 !TRI.isSubRegisterEq(AvailCopy->getOperand(0).getReg(), Reg))
163 return nullptr;
Justin Bogner60a5c772018-09-25 04:45:25 +0000164
165 // Check that the available copy isn't clobbered by any regmasks between
166 // itself and the destination.
Justin Bognerdb467842018-10-22 19:51:31 +0000167 unsigned AvailSrc = AvailCopy->getOperand(1).getReg();
168 unsigned AvailDef = AvailCopy->getOperand(0).getReg();
Justin Bogner60a5c772018-09-25 04:45:25 +0000169 for (const MachineInstr &MI :
Justin Bognerdb467842018-10-22 19:51:31 +0000170 make_range(AvailCopy->getIterator(), DestCopy.getIterator()))
Justin Bogner60a5c772018-09-25 04:45:25 +0000171 for (const MachineOperand &MO : MI.operands())
172 if (MO.isRegMask())
173 if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
174 return nullptr;
175
Justin Bognerdb467842018-10-22 19:51:31 +0000176 return AvailCopy;
Justin Bogner97eaa642018-09-21 00:51:04 +0000177 }
178
179 void clear() {
Justin Bognerdb467842018-10-22 19:51:31 +0000180 Copies.clear();
Justin Bogner97eaa642018-09-21 00:51:04 +0000181 }
182};
Matthias Brauned2d4b92016-02-26 03:18:50 +0000183
Justin Bognerb69da1b2018-09-21 00:08:33 +0000184class MachineCopyPropagation : public MachineFunctionPass {
185 const TargetRegisterInfo *TRI;
186 const TargetInstrInfo *TII;
187 const MachineRegisterInfo *MRI;
Andrew Trick1df91b02012-02-08 21:22:43 +0000188
Justin Bognerb69da1b2018-09-21 00:08:33 +0000189public:
190 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko7cf6af52017-08-29 22:32:07 +0000191
Justin Bognerb69da1b2018-09-21 00:08:33 +0000192 MachineCopyPropagation() : MachineFunctionPass(ID) {
193 initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
194 }
Evan Cheng977679d2012-01-07 03:02:36 +0000195
Justin Bognerb69da1b2018-09-21 00:08:33 +0000196 void getAnalysisUsage(AnalysisUsage &AU) const override {
197 AU.setPreservesCFG();
198 MachineFunctionPass::getAnalysisUsage(AU);
199 }
Matt Arsenault48de2a92016-06-02 00:04:26 +0000200
Justin Bognerb69da1b2018-09-21 00:08:33 +0000201 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Cheng977679d2012-01-07 03:02:36 +0000202
Justin Bognerb69da1b2018-09-21 00:08:33 +0000203 MachineFunctionProperties getRequiredProperties() const override {
204 return MachineFunctionProperties().set(
205 MachineFunctionProperties::Property::NoVRegs);
206 }
Derek Schufffadd1132016-03-28 17:05:30 +0000207
Justin Bognerb69da1b2018-09-21 00:08:33 +0000208private:
209 void ClobberRegister(unsigned Reg);
210 void ReadRegister(unsigned Reg);
211 void CopyPropagateBlock(MachineBasicBlock &MBB);
212 bool eraseIfRedundant(MachineInstr &Copy, unsigned Src, unsigned Def);
213 void forwardUses(MachineInstr &MI);
214 bool isForwardableRegClassCopy(const MachineInstr &Copy,
215 const MachineInstr &UseI, unsigned UseIdx);
216 bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use);
Matthias Braun4f08db22016-02-20 03:56:39 +0000217
Justin Bognerb69da1b2018-09-21 00:08:33 +0000218 /// Candidates for deletion.
219 SmallSetVector<MachineInstr *, 8> MaybeDeadCopies;
Eugene Zelenko7cf6af52017-08-29 22:32:07 +0000220
Justin Bogner97eaa642018-09-21 00:51:04 +0000221 CopyTracker Tracker;
Eugene Zelenko7cf6af52017-08-29 22:32:07 +0000222
Justin Bognerb69da1b2018-09-21 00:08:33 +0000223 bool Changed;
224};
Eugene Zelenko7cf6af52017-08-29 22:32:07 +0000225
226} // end anonymous namespace
227
Evan Cheng977679d2012-01-07 03:02:36 +0000228char MachineCopyPropagation::ID = 0;
Eugene Zelenko7cf6af52017-08-29 22:32:07 +0000229
Andrew Trick1dd8c852012-02-08 21:23:13 +0000230char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
Evan Cheng977679d2012-01-07 03:02:36 +0000231
Matthias Braun94c49042017-05-25 21:26:32 +0000232INITIALIZE_PASS(MachineCopyPropagation, DEBUG_TYPE,
Evan Cheng977679d2012-01-07 03:02:36 +0000233 "Machine Copy Propagation Pass", false, false)
234
Matthias Braunb6384b22017-02-04 02:27:20 +0000235void MachineCopyPropagation::ReadRegister(unsigned Reg) {
236 // If 'Reg' is defined by a copy, the copy is no longer a candidate
237 // for elimination.
Justin Bognerdb467842018-10-22 19:51:31 +0000238 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI) {
239 if (MachineInstr *Copy = Tracker.findCopyForUnit(*RUI, *TRI)) {
Justin Bogner97eaa642018-09-21 00:51:04 +0000240 LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy->dump());
241 MaybeDeadCopies.remove(Copy);
Matthias Braunb6384b22017-02-04 02:27:20 +0000242 }
243 }
244}
245
Matthias Braune0761c42016-02-26 03:18:55 +0000246/// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
247/// This fact may have been obscured by sub register usage or may not be true at
248/// all even though Src and Def are subregisters of the registers used in
249/// PreviousCopy. e.g.
250/// isNopCopy("ecx = COPY eax", AX, CX) == true
251/// isNopCopy("ecx = COPY eax", AH, CL) == false
252static bool isNopCopy(const MachineInstr &PreviousCopy, unsigned Src,
253 unsigned Def, const TargetRegisterInfo *TRI) {
254 unsigned PreviousSrc = PreviousCopy.getOperand(1).getReg();
255 unsigned PreviousDef = PreviousCopy.getOperand(0).getReg();
256 if (Src == PreviousSrc) {
257 assert(Def == PreviousDef);
Evan Cheng01b623c2012-02-20 23:28:17 +0000258 return true;
Evan Cheng01b623c2012-02-20 23:28:17 +0000259 }
Matthias Braune0761c42016-02-26 03:18:55 +0000260 if (!TRI->isSubRegister(PreviousSrc, Src))
261 return false;
262 unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
263 return SubIdx == TRI->getSubRegIndex(PreviousDef, Def);
264}
Evan Cheng01b623c2012-02-20 23:28:17 +0000265
Matthias Braune0761c42016-02-26 03:18:55 +0000266/// Remove instruction \p Copy if there exists a previous copy that copies the
267/// register \p Src to the register \p Def; This may happen indirectly by
268/// copying the super registers.
269bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy, unsigned Src,
270 unsigned Def) {
271 // Avoid eliminating a copy from/to a reserved registers as we cannot predict
272 // the value (Example: The sparc zero register is writable but stays zero).
273 if (MRI->isReserved(Src) || MRI->isReserved(Def))
274 return false;
275
276 // Search for an existing copy.
Justin Bognerdb467842018-10-22 19:51:31 +0000277 MachineInstr *PrevCopy = Tracker.findAvailCopy(Copy, Def, *TRI);
Justin Bogner97eaa642018-09-21 00:51:04 +0000278 if (!PrevCopy)
Matthias Braune0761c42016-02-26 03:18:55 +0000279 return false;
280
281 // Check that the existing copy uses the correct sub registers.
Justin Bogner97eaa642018-09-21 00:51:04 +0000282 if (PrevCopy->getOperand(0).isDead())
Alexander Timofeev23476c42017-11-10 12:21:10 +0000283 return false;
Justin Bogner97eaa642018-09-21 00:51:04 +0000284 if (!isNopCopy(*PrevCopy, Src, Def, TRI))
Matthias Braune0761c42016-02-26 03:18:55 +0000285 return false;
286
Nicola Zaghen0818e782018-05-14 12:53:11 +0000287 LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
Matthias Braune0761c42016-02-26 03:18:55 +0000288
289 // Copy was redundantly redefining either Src or Def. Remove earlier kill
290 // flags between Copy and PrevCopy because the value will be reused now.
291 assert(Copy.isCopy());
292 unsigned CopyDef = Copy.getOperand(0).getReg();
293 assert(CopyDef == Src || CopyDef == Def);
294 for (MachineInstr &MI :
Justin Bogner97eaa642018-09-21 00:51:04 +0000295 make_range(PrevCopy->getIterator(), Copy.getIterator()))
Matthias Braune0761c42016-02-26 03:18:55 +0000296 MI.clearRegisterKills(CopyDef, TRI);
297
298 Copy.eraseFromParent();
299 Changed = true;
300 ++NumDeletes;
301 return true;
Evan Cheng01b623c2012-02-20 23:28:17 +0000302}
303
Geoff Berry1bfec902018-02-27 16:59:10 +0000304/// Decide whether we should forward the source of \param Copy to its use in
305/// \param UseI based on the physical register class constraints of the opcode
306/// and avoiding introducing more cross-class COPYs.
307bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
308 const MachineInstr &UseI,
309 unsigned UseIdx) {
310
311 unsigned CopySrcReg = Copy.getOperand(1).getReg();
312
313 // If the new register meets the opcode register constraints, then allow
314 // forwarding.
315 if (const TargetRegisterClass *URC =
316 UseI.getRegClassConstraint(UseIdx, TII, TRI))
317 return URC->contains(CopySrcReg);
318
319 if (!UseI.isCopy())
320 return false;
321
322 /// COPYs don't have register class constraints, so if the user instruction
323 /// is a COPY, we just try to avoid introducing additional cross-class
324 /// COPYs. For example:
325 ///
326 /// RegClassA = COPY RegClassB // Copy parameter
327 /// ...
328 /// RegClassB = COPY RegClassA // UseI parameter
329 ///
330 /// which after forwarding becomes
331 ///
332 /// RegClassA = COPY RegClassB
333 /// ...
334 /// RegClassB = COPY RegClassB
335 ///
336 /// so we have reduced the number of cross-class COPYs and potentially
337 /// introduced a nop COPY that can be removed.
338 const TargetRegisterClass *UseDstRC =
339 TRI->getMinimalPhysRegClass(UseI.getOperand(0).getReg());
340
341 const TargetRegisterClass *SuperRC = UseDstRC;
342 for (TargetRegisterClass::sc_iterator SuperRCI = UseDstRC->getSuperClasses();
343 SuperRC; SuperRC = *SuperRCI++)
344 if (SuperRC->contains(CopySrcReg))
345 return true;
346
347 return false;
348}
349
350/// Check that \p MI does not have implicit uses that overlap with it's \p Use
351/// operand (the register being replaced), since these can sometimes be
352/// implicitly tied to other operands. For example, on AMDGPU:
353///
354/// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
355///
356/// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
357/// way of knowing we need to update the latter when updating the former.
358bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
359 const MachineOperand &Use) {
360 for (const MachineOperand &MIUse : MI.uses())
361 if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
362 MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
363 return true;
364
365 return false;
366}
367
368/// Look for available copies whose destination register is used by \p MI and
369/// replace the use in \p MI with the copy's source register.
370void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
Justin Bognerdb467842018-10-22 19:51:31 +0000371 if (!Tracker.hasAnyCopies())
Geoff Berry1bfec902018-02-27 16:59:10 +0000372 return;
373
374 // Look for non-tied explicit vreg uses that have an active COPY
375 // instruction that defines the physical register allocated to them.
376 // Replace the vreg with the source of the active COPY.
377 for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
378 ++OpIdx) {
379 MachineOperand &MOUse = MI.getOperand(OpIdx);
380 // Don't forward into undef use operands since doing so can cause problems
381 // with the machine verifier, since it doesn't treat undef reads as reads,
382 // so we can end up with a live range that ends on an undef read, leading to
383 // an error that the live range doesn't end on a read of the live range
384 // register.
385 if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
386 MOUse.isImplicit())
387 continue;
388
389 if (!MOUse.getReg())
390 continue;
391
392 // Check that the register is marked 'renamable' so we know it is safe to
393 // rename it without violating any constraints that aren't expressed in the
394 // IR (e.g. ABI or opcode requirements).
395 if (!MOUse.isRenamable())
396 continue;
397
Justin Bognerdb467842018-10-22 19:51:31 +0000398 MachineInstr *Copy = Tracker.findAvailCopy(MI, MOUse.getReg(), *TRI);
Justin Bogner97eaa642018-09-21 00:51:04 +0000399 if (!Copy)
Geoff Berry1bfec902018-02-27 16:59:10 +0000400 continue;
401
Justin Bogner97eaa642018-09-21 00:51:04 +0000402 unsigned CopyDstReg = Copy->getOperand(0).getReg();
403 const MachineOperand &CopySrc = Copy->getOperand(1);
Geoff Berry1bfec902018-02-27 16:59:10 +0000404 unsigned CopySrcReg = CopySrc.getReg();
405
406 // FIXME: Don't handle partial uses of wider COPYs yet.
407 if (MOUse.getReg() != CopyDstReg) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000408 LLVM_DEBUG(
409 dbgs() << "MCP: FIXME! Not forwarding COPY to sub-register use:\n "
410 << MI);
Geoff Berry1bfec902018-02-27 16:59:10 +0000411 continue;
412 }
413
414 // Don't forward COPYs of reserved regs unless they are constant.
415 if (MRI->isReserved(CopySrcReg) && !MRI->isConstantPhysReg(CopySrcReg))
416 continue;
417
Justin Bogner97eaa642018-09-21 00:51:04 +0000418 if (!isForwardableRegClassCopy(*Copy, MI, OpIdx))
Geoff Berry1bfec902018-02-27 16:59:10 +0000419 continue;
420
421 if (hasImplicitOverlap(MI, MOUse))
422 continue;
423
424 if (!DebugCounter::shouldExecute(FwdCounter)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000425 LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n "
426 << MI);
Geoff Berry1bfec902018-02-27 16:59:10 +0000427 continue;
428 }
429
Nicola Zaghen0818e782018-05-14 12:53:11 +0000430 LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
431 << "\n with " << printReg(CopySrcReg, TRI)
Justin Bogner97eaa642018-09-21 00:51:04 +0000432 << "\n in " << MI << " from " << *Copy);
Geoff Berry1bfec902018-02-27 16:59:10 +0000433
434 MOUse.setReg(CopySrcReg);
435 if (!CopySrc.isRenamable())
436 MOUse.setIsRenamable(false);
437
Nicola Zaghen0818e782018-05-14 12:53:11 +0000438 LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
Geoff Berry1bfec902018-02-27 16:59:10 +0000439
440 // Clear kill markers that may have been invalidated.
441 for (MachineInstr &KMI :
Justin Bogner97eaa642018-09-21 00:51:04 +0000442 make_range(Copy->getIterator(), std::next(MI.getIterator())))
Geoff Berry1bfec902018-02-27 16:59:10 +0000443 KMI.clearRegisterKills(CopySrcReg, TRI);
444
445 ++NumCopyForwards;
446 Changed = true;
447 }
448}
449
Matthias Braun4f08db22016-02-20 03:56:39 +0000450void MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000451 LLVM_DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
James Molloybb96dfc2014-01-22 09:12:27 +0000452
Evan Cheng977679d2012-01-07 03:02:36 +0000453 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
454 MachineInstr *MI = &*I;
455 ++I;
456
Eli Friedman033a78e2018-03-30 00:56:03 +0000457 // Analyze copies (which don't overlap themselves).
458 if (MI->isCopy() && !TRI->regsOverlap(MI->getOperand(0).getReg(),
459 MI->getOperand(1).getReg())) {
Geoff Berryc3ef7ae2017-10-03 16:59:13 +0000460 unsigned Def = MI->getOperand(0).getReg();
461 unsigned Src = MI->getOperand(1).getReg();
462
463 assert(!TargetRegisterInfo::isVirtualRegister(Def) &&
464 !TargetRegisterInfo::isVirtualRegister(Src) &&
465 "MachineCopyPropagation should be run after register allocation!");
Evan Cheng977679d2012-01-07 03:02:36 +0000466
Matthias Braune0761c42016-02-26 03:18:55 +0000467 // The two copies cancel out and the source of the first copy
468 // hasn't been overridden, eliminate the second one. e.g.
Francis Visoiu Mistrihfd11bc02017-12-07 10:40:31 +0000469 // %ecx = COPY %eax
Francis Visoiu Mistriha4ec08b2017-11-28 17:15:09 +0000470 // ... nothing clobbered eax.
Francis Visoiu Mistrihfd11bc02017-12-07 10:40:31 +0000471 // %eax = COPY %ecx
Matthias Braune0761c42016-02-26 03:18:55 +0000472 // =>
Francis Visoiu Mistrihfd11bc02017-12-07 10:40:31 +0000473 // %ecx = COPY %eax
Matthias Braune0761c42016-02-26 03:18:55 +0000474 //
475 // or
476 //
Francis Visoiu Mistrihfd11bc02017-12-07 10:40:31 +0000477 // %ecx = COPY %eax
Francis Visoiu Mistriha4ec08b2017-11-28 17:15:09 +0000478 // ... nothing clobbered eax.
Francis Visoiu Mistrihfd11bc02017-12-07 10:40:31 +0000479 // %ecx = COPY %eax
Matthias Braune0761c42016-02-26 03:18:55 +0000480 // =>
Francis Visoiu Mistrihfd11bc02017-12-07 10:40:31 +0000481 // %ecx = COPY %eax
Geoff Berryc3ef7ae2017-10-03 16:59:13 +0000482 if (eraseIfRedundant(*MI, Def, Src) || eraseIfRedundant(*MI, Src, Def))
483 continue;
Evan Cheng977679d2012-01-07 03:02:36 +0000484
Geoff Berry1bfec902018-02-27 16:59:10 +0000485 forwardUses(*MI);
486
487 // Src may have been changed by forwardUses()
488 Src = MI->getOperand(1).getReg();
489
Jun Bum Limccdf1892016-02-03 15:56:27 +0000490 // If Src is defined by a previous copy, the previous copy cannot be
491 // eliminated.
Matthias Braunb6384b22017-02-04 02:27:20 +0000492 ReadRegister(Src);
493 for (const MachineOperand &MO : MI->implicit_operands()) {
494 if (!MO.isReg() || !MO.readsReg())
495 continue;
496 unsigned Reg = MO.getReg();
497 if (!Reg)
498 continue;
499 ReadRegister(Reg);
Evan Cheng977679d2012-01-07 03:02:36 +0000500 }
501
Nicola Zaghen0818e782018-05-14 12:53:11 +0000502 LLVM_DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
James Molloybb96dfc2014-01-22 09:12:27 +0000503
Evan Cheng977679d2012-01-07 03:02:36 +0000504 // Copy is now a candidate for deletion.
Geoff Berryc3ef7ae2017-10-03 16:59:13 +0000505 if (!MRI->isReserved(Def))
Matthias Braun4d44c952016-02-20 03:56:36 +0000506 MaybeDeadCopies.insert(MI);
Evan Cheng977679d2012-01-07 03:02:36 +0000507
Jun Bum Limccdf1892016-02-03 15:56:27 +0000508 // If 'Def' is previously source of another copy, then this earlier copy's
Evan Cheng977679d2012-01-07 03:02:36 +0000509 // source is no longer available. e.g.
Francis Visoiu Mistrihfd11bc02017-12-07 10:40:31 +0000510 // %xmm9 = copy %xmm2
Evan Cheng977679d2012-01-07 03:02:36 +0000511 // ...
Francis Visoiu Mistrihfd11bc02017-12-07 10:40:31 +0000512 // %xmm2 = copy %xmm0
Evan Cheng977679d2012-01-07 03:02:36 +0000513 // ...
Francis Visoiu Mistrihfd11bc02017-12-07 10:40:31 +0000514 // %xmm2 = copy %xmm9
Justin Bogner97eaa642018-09-21 00:51:04 +0000515 Tracker.clobberRegister(Def, *TRI);
Matthias Braunb6384b22017-02-04 02:27:20 +0000516 for (const MachineOperand &MO : MI->implicit_operands()) {
517 if (!MO.isReg() || !MO.isDef())
518 continue;
Geoff Berryc3ef7ae2017-10-03 16:59:13 +0000519 unsigned Reg = MO.getReg();
Matthias Braunb6384b22017-02-04 02:27:20 +0000520 if (!Reg)
521 continue;
Justin Bogner97eaa642018-09-21 00:51:04 +0000522 Tracker.clobberRegister(Reg, *TRI);
Matthias Braunb6384b22017-02-04 02:27:20 +0000523 }
Evan Cheng977679d2012-01-07 03:02:36 +0000524
Justin Bogner97eaa642018-09-21 00:51:04 +0000525 Tracker.trackCopy(MI, *TRI);
Alexander Timofeevf6eb7ff2017-10-16 16:57:37 +0000526
Evan Cheng977679d2012-01-07 03:02:36 +0000527 continue;
528 }
529
Geoff Berry1bfec902018-02-27 16:59:10 +0000530 // Clobber any earlyclobber regs first.
531 for (const MachineOperand &MO : MI->operands())
532 if (MO.isReg() && MO.isEarlyClobber()) {
533 unsigned Reg = MO.getReg();
534 // If we have a tied earlyclobber, that means it is also read by this
535 // instruction, so we need to make sure we don't remove it as dead
536 // later.
537 if (MO.isTied())
538 ReadRegister(Reg);
Justin Bogner97eaa642018-09-21 00:51:04 +0000539 Tracker.clobberRegister(Reg, *TRI);
Geoff Berry1bfec902018-02-27 16:59:10 +0000540 }
541
542 forwardUses(*MI);
543
Evan Cheng977679d2012-01-07 03:02:36 +0000544 // Not a copy.
545 SmallVector<unsigned, 2> Defs;
Matthias Braun4d44c952016-02-20 03:56:36 +0000546 const MachineOperand *RegMask = nullptr;
547 for (const MachineOperand &MO : MI->operands()) {
Jakob Stoklund Olesena8fc1712012-02-08 22:37:35 +0000548 if (MO.isRegMask())
Matthias Braun4d44c952016-02-20 03:56:36 +0000549 RegMask = &MO;
Evan Cheng977679d2012-01-07 03:02:36 +0000550 if (!MO.isReg())
551 continue;
Geoff Berryc3ef7ae2017-10-03 16:59:13 +0000552 unsigned Reg = MO.getReg();
Evan Cheng977679d2012-01-07 03:02:36 +0000553 if (!Reg)
554 continue;
555
Geoff Berryc3ef7ae2017-10-03 16:59:13 +0000556 assert(!TargetRegisterInfo::isVirtualRegister(Reg) &&
557 "MachineCopyPropagation should be run after register allocation!");
558
Geoff Berry1bfec902018-02-27 16:59:10 +0000559 if (MO.isDef() && !MO.isEarlyClobber()) {
Evan Cheng977679d2012-01-07 03:02:36 +0000560 Defs.push_back(Reg);
561 continue;
Krzysztof Parzyszek873b4b62018-07-11 13:30:27 +0000562 } else if (!MO.isDebug() && MO.readsReg())
Matthias Braunb6384b22017-02-04 02:27:20 +0000563 ReadRegister(Reg);
Evan Cheng977679d2012-01-07 03:02:36 +0000564 }
565
Jakob Stoklund Olesena8fc1712012-02-08 22:37:35 +0000566 // The instruction has a register mask operand which means that it clobbers
Matthias Brauned2d4b92016-02-26 03:18:50 +0000567 // a large set of registers. Treat clobbered registers the same way as
568 // defined registers.
Matthias Braun4d44c952016-02-20 03:56:36 +0000569 if (RegMask) {
Jakob Stoklund Olesenf56ce532012-02-09 00:19:08 +0000570 // Erase any MaybeDeadCopies whose destination register is clobbered.
Jun Bum Lim386c67f2016-03-25 21:15:35 +0000571 for (SmallSetVector<MachineInstr *, 8>::iterator DI =
572 MaybeDeadCopies.begin();
573 DI != MaybeDeadCopies.end();) {
574 MachineInstr *MaybeDead = *DI;
Matthias Braun4d44c952016-02-20 03:56:36 +0000575 unsigned Reg = MaybeDead->getOperand(0).getReg();
576 assert(!MRI->isReserved(Reg));
Jun Bum Lim386c67f2016-03-25 21:15:35 +0000577
578 if (!RegMask->clobbersPhysReg(Reg)) {
579 ++DI;
Jakob Stoklund Olesenf56ce532012-02-09 00:19:08 +0000580 continue;
Jun Bum Lim386c67f2016-03-25 21:15:35 +0000581 }
582
Nicola Zaghen0818e782018-05-14 12:53:11 +0000583 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
584 MaybeDead->dump());
Jun Bum Lim386c67f2016-03-25 21:15:35 +0000585
Justin Bogner60a5c772018-09-25 04:45:25 +0000586 // Make sure we invalidate any entries in the copy maps before erasing
587 // the instruction.
588 Tracker.clobberRegister(Reg, *TRI);
589
Jun Bum Lim386c67f2016-03-25 21:15:35 +0000590 // erase() will return the next valid iterator pointing to the next
591 // element after the erased one.
592 DI = MaybeDeadCopies.erase(DI);
Matthias Braun4d44c952016-02-20 03:56:36 +0000593 MaybeDead->eraseFromParent();
Jakob Stoklund Olesenf56ce532012-02-09 00:19:08 +0000594 Changed = true;
595 ++NumDeletes;
596 }
Jakob Stoklund Olesena8fc1712012-02-08 22:37:35 +0000597 }
598
Matthias Brauned2d4b92016-02-26 03:18:50 +0000599 // Any previous copy definition or reading the Defs is no longer available.
Matthias Braune0761c42016-02-26 03:18:55 +0000600 for (unsigned Reg : Defs)
Justin Bogner97eaa642018-09-21 00:51:04 +0000601 Tracker.clobberRegister(Reg, *TRI);
Evan Cheng977679d2012-01-07 03:02:36 +0000602 }
603
604 // If MBB doesn't have successors, delete the copies whose defs are not used.
605 // If MBB does have successors, then conservative assume the defs are live-out
606 // since we don't want to trust live-in lists.
607 if (MBB.succ_empty()) {
Matthias Braun4d44c952016-02-20 03:56:36 +0000608 for (MachineInstr *MaybeDead : MaybeDeadCopies) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000609 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
610 MaybeDead->dump());
Matthias Braun4d44c952016-02-20 03:56:36 +0000611 assert(!MRI->isReserved(MaybeDead->getOperand(0).getReg()));
Carlos Alberto Enciso42b54432018-10-01 08:14:44 +0000612
613 // Update matching debug values.
614 assert(MaybeDead->isCopy());
615 MaybeDead->changeDebugValuesDefReg(MaybeDead->getOperand(1).getReg());
616
Matthias Braun4d44c952016-02-20 03:56:36 +0000617 MaybeDead->eraseFromParent();
618 Changed = true;
619 ++NumDeletes;
Evan Cheng977679d2012-01-07 03:02:36 +0000620 }
621 }
622
Matthias Braun4f08db22016-02-20 03:56:39 +0000623 MaybeDeadCopies.clear();
Justin Bogner97eaa642018-09-21 00:51:04 +0000624 Tracker.clear();
Evan Cheng977679d2012-01-07 03:02:36 +0000625}
626
627bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
Matthias Braund3181392017-12-15 22:22:58 +0000628 if (skipFunction(MF.getFunction()))
Paul Robinson5fa58a52014-03-31 17:43:35 +0000629 return false;
630
Matthias Braun4f08db22016-02-20 03:56:39 +0000631 Changed = false;
Evan Cheng977679d2012-01-07 03:02:36 +0000632
Eric Christopher60355182014-08-05 02:39:49 +0000633 TRI = MF.getSubtarget().getRegisterInfo();
634 TII = MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesenfb9ebbf2012-10-15 21:57:41 +0000635 MRI = &MF.getRegInfo();
Evan Cheng977679d2012-01-07 03:02:36 +0000636
Matthias Braun4d44c952016-02-20 03:56:36 +0000637 for (MachineBasicBlock &MBB : MF)
Matthias Braun4f08db22016-02-20 03:56:39 +0000638 CopyPropagateBlock(MBB);
Evan Cheng977679d2012-01-07 03:02:36 +0000639
640 return Changed;
641}