blob: 4c1717e1ec3c95b2932e2d8292be936b529efedb [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()) {
184 DEBUG(dbgs() << "MCP: Copy is used - not dead: "; CI->second->dump());
185 MaybeDeadCopies.remove(CI->second);
186 }
187 }
188}
189
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000190/// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
191/// This fact may have been obscured by sub register usage or may not be true at
192/// all even though Src and Def are subregisters of the registers used in
193/// PreviousCopy. e.g.
194/// isNopCopy("ecx = COPY eax", AX, CX) == true
195/// isNopCopy("ecx = COPY eax", AH, CL) == false
196static bool isNopCopy(const MachineInstr &PreviousCopy, unsigned Src,
197 unsigned Def, const TargetRegisterInfo *TRI) {
198 unsigned PreviousSrc = PreviousCopy.getOperand(1).getReg();
199 unsigned PreviousDef = PreviousCopy.getOperand(0).getReg();
200 if (Src == PreviousSrc) {
201 assert(Def == PreviousDef);
Evan Cheng63618f92012-02-20 23:28:17 +0000202 return true;
Evan Cheng63618f92012-02-20 23:28:17 +0000203 }
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000204 if (!TRI->isSubRegister(PreviousSrc, Src))
205 return false;
206 unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
207 return SubIdx == TRI->getSubRegIndex(PreviousDef, Def);
208}
Evan Cheng63618f92012-02-20 23:28:17 +0000209
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000210/// Remove instruction \p Copy if there exists a previous copy that copies the
211/// register \p Src to the register \p Def; This may happen indirectly by
212/// copying the super registers.
213bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy, unsigned Src,
214 unsigned Def) {
215 // Avoid eliminating a copy from/to a reserved registers as we cannot predict
216 // the value (Example: The sparc zero register is writable but stays zero).
217 if (MRI->isReserved(Src) || MRI->isReserved(Def))
218 return false;
219
220 // Search for an existing copy.
221 Reg2MIMap::iterator CI = AvailCopyMap.find(Def);
222 if (CI == AvailCopyMap.end())
223 return false;
224
225 // Check that the existing copy uses the correct sub registers.
226 MachineInstr &PrevCopy = *CI->second;
Alexander Timofeev28da0672017-11-10 12:21:10 +0000227 if (PrevCopy.getOperand(0).isDead())
228 return false;
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000229 if (!isNopCopy(PrevCopy, Src, Def, TRI))
230 return false;
231
232 DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
233
234 // Copy was redundantly redefining either Src or Def. Remove earlier kill
235 // flags between Copy and PrevCopy because the value will be reused now.
236 assert(Copy.isCopy());
237 unsigned CopyDef = Copy.getOperand(0).getReg();
238 assert(CopyDef == Src || CopyDef == Def);
239 for (MachineInstr &MI :
240 make_range(PrevCopy.getIterator(), Copy.getIterator()))
241 MI.clearRegisterKills(CopyDef, TRI);
242
243 Copy.eraseFromParent();
244 Changed = true;
245 ++NumDeletes;
246 return true;
Evan Cheng63618f92012-02-20 23:28:17 +0000247}
248
Geoff Berrya2b90112018-02-27 16:59:10 +0000249/// Decide whether we should forward the source of \param Copy to its use in
250/// \param UseI based on the physical register class constraints of the opcode
251/// and avoiding introducing more cross-class COPYs.
252bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
253 const MachineInstr &UseI,
254 unsigned UseIdx) {
255
256 unsigned CopySrcReg = Copy.getOperand(1).getReg();
257
258 // If the new register meets the opcode register constraints, then allow
259 // forwarding.
260 if (const TargetRegisterClass *URC =
261 UseI.getRegClassConstraint(UseIdx, TII, TRI))
262 return URC->contains(CopySrcReg);
263
264 if (!UseI.isCopy())
265 return false;
266
267 /// COPYs don't have register class constraints, so if the user instruction
268 /// is a COPY, we just try to avoid introducing additional cross-class
269 /// COPYs. For example:
270 ///
271 /// RegClassA = COPY RegClassB // Copy parameter
272 /// ...
273 /// RegClassB = COPY RegClassA // UseI parameter
274 ///
275 /// which after forwarding becomes
276 ///
277 /// RegClassA = COPY RegClassB
278 /// ...
279 /// RegClassB = COPY RegClassB
280 ///
281 /// so we have reduced the number of cross-class COPYs and potentially
282 /// introduced a nop COPY that can be removed.
283 const TargetRegisterClass *UseDstRC =
284 TRI->getMinimalPhysRegClass(UseI.getOperand(0).getReg());
285
286 const TargetRegisterClass *SuperRC = UseDstRC;
287 for (TargetRegisterClass::sc_iterator SuperRCI = UseDstRC->getSuperClasses();
288 SuperRC; SuperRC = *SuperRCI++)
289 if (SuperRC->contains(CopySrcReg))
290 return true;
291
292 return false;
293}
294
295/// Check that \p MI does not have implicit uses that overlap with it's \p Use
296/// operand (the register being replaced), since these can sometimes be
297/// implicitly tied to other operands. For example, on AMDGPU:
298///
299/// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
300///
301/// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
302/// way of knowing we need to update the latter when updating the former.
303bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
304 const MachineOperand &Use) {
305 for (const MachineOperand &MIUse : MI.uses())
306 if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
307 MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
308 return true;
309
310 return false;
311}
312
313/// Look for available copies whose destination register is used by \p MI and
314/// replace the use in \p MI with the copy's source register.
315void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
316 if (AvailCopyMap.empty())
317 return;
318
319 // Look for non-tied explicit vreg uses that have an active COPY
320 // instruction that defines the physical register allocated to them.
321 // Replace the vreg with the source of the active COPY.
322 for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
323 ++OpIdx) {
324 MachineOperand &MOUse = MI.getOperand(OpIdx);
325 // Don't forward into undef use operands since doing so can cause problems
326 // with the machine verifier, since it doesn't treat undef reads as reads,
327 // so we can end up with a live range that ends on an undef read, leading to
328 // an error that the live range doesn't end on a read of the live range
329 // register.
330 if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
331 MOUse.isImplicit())
332 continue;
333
334 if (!MOUse.getReg())
335 continue;
336
337 // Check that the register is marked 'renamable' so we know it is safe to
338 // rename it without violating any constraints that aren't expressed in the
339 // IR (e.g. ABI or opcode requirements).
340 if (!MOUse.isRenamable())
341 continue;
342
343 auto CI = AvailCopyMap.find(MOUse.getReg());
344 if (CI == AvailCopyMap.end())
345 continue;
346
347 MachineInstr &Copy = *CI->second;
348 unsigned CopyDstReg = Copy.getOperand(0).getReg();
349 const MachineOperand &CopySrc = Copy.getOperand(1);
350 unsigned CopySrcReg = CopySrc.getReg();
351
352 // FIXME: Don't handle partial uses of wider COPYs yet.
353 if (MOUse.getReg() != CopyDstReg) {
354 DEBUG(dbgs() << "MCP: FIXME! Not forwarding COPY to sub-register use:\n "
355 << MI);
356 continue;
357 }
358
359 // Don't forward COPYs of reserved regs unless they are constant.
360 if (MRI->isReserved(CopySrcReg) && !MRI->isConstantPhysReg(CopySrcReg))
361 continue;
362
363 if (!isForwardableRegClassCopy(Copy, MI, OpIdx))
364 continue;
365
366 if (hasImplicitOverlap(MI, MOUse))
367 continue;
368
369 if (!DebugCounter::shouldExecute(FwdCounter)) {
370 DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n "
371 << MI);
372 continue;
373 }
374
375 DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
376 << "\n with " << printReg(CopySrcReg, TRI) << "\n in "
377 << MI << " from " << Copy);
378
379 MOUse.setReg(CopySrcReg);
380 if (!CopySrc.isRenamable())
381 MOUse.setIsRenamable(false);
382
383 DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
384
385 // Clear kill markers that may have been invalidated.
386 for (MachineInstr &KMI :
387 make_range(Copy.getIterator(), std::next(MI.getIterator())))
388 KMI.clearRegisterKills(CopySrcReg, TRI);
389
390 ++NumCopyForwards;
391 Changed = true;
392 }
393}
394
Matthias Braunbd18d752016-02-20 03:56:39 +0000395void MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
James Molloyd787d3e2014-01-22 09:12:27 +0000396 DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
397
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000398 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
399 MachineInstr *MI = &*I;
400 ++I;
401
402 if (MI->isCopy()) {
Geoff Berryfabedba2017-10-03 16:59:13 +0000403 unsigned Def = MI->getOperand(0).getReg();
404 unsigned Src = MI->getOperand(1).getReg();
405
406 assert(!TargetRegisterInfo::isVirtualRegister(Def) &&
407 !TargetRegisterInfo::isVirtualRegister(Src) &&
408 "MachineCopyPropagation should be run after register allocation!");
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000409
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000410 // The two copies cancel out and the source of the first copy
411 // hasn't been overridden, eliminate the second one. e.g.
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000412 // %ecx = COPY %eax
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +0000413 // ... nothing clobbered eax.
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000414 // %eax = COPY %ecx
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000415 // =>
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000416 // %ecx = COPY %eax
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000417 //
418 // or
419 //
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000420 // %ecx = COPY %eax
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +0000421 // ... nothing clobbered eax.
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000422 // %ecx = COPY %eax
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000423 // =>
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000424 // %ecx = COPY %eax
Geoff Berryfabedba2017-10-03 16:59:13 +0000425 if (eraseIfRedundant(*MI, Def, Src) || eraseIfRedundant(*MI, Src, Def))
426 continue;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000427
Geoff Berrya2b90112018-02-27 16:59:10 +0000428 forwardUses(*MI);
429
430 // Src may have been changed by forwardUses()
431 Src = MI->getOperand(1).getReg();
432
Jun Bum Lim59df5e82016-02-03 15:56:27 +0000433 // If Src is defined by a previous copy, the previous copy cannot be
434 // eliminated.
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000435 ReadRegister(Src);
436 for (const MachineOperand &MO : MI->implicit_operands()) {
437 if (!MO.isReg() || !MO.readsReg())
438 continue;
439 unsigned Reg = MO.getReg();
440 if (!Reg)
441 continue;
442 ReadRegister(Reg);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000443 }
444
James Molloyd787d3e2014-01-22 09:12:27 +0000445 DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
446
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000447 // Copy is now a candidate for deletion.
Geoff Berryfabedba2017-10-03 16:59:13 +0000448 if (!MRI->isReserved(Def))
Matthias Braun273575d2016-02-20 03:56:36 +0000449 MaybeDeadCopies.insert(MI);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000450
Jun Bum Lim59df5e82016-02-03 15:56:27 +0000451 // If 'Def' is previously source of another copy, then this earlier copy's
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000452 // source is no longer available. e.g.
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000453 // %xmm9 = copy %xmm2
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000454 // ...
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000455 // %xmm2 = copy %xmm0
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000456 // ...
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000457 // %xmm2 = copy %xmm9
Geoff Berryfabedba2017-10-03 16:59:13 +0000458 ClobberRegister(Def);
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000459 for (const MachineOperand &MO : MI->implicit_operands()) {
460 if (!MO.isReg() || !MO.isDef())
461 continue;
Geoff Berryfabedba2017-10-03 16:59:13 +0000462 unsigned Reg = MO.getReg();
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000463 if (!Reg)
464 continue;
465 ClobberRegister(Reg);
466 }
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000467
Alexander Timofeev9dff31c2017-10-16 16:57:37 +0000468 // Remember Def is defined by the copy.
469 for (MCSubRegIterator SR(Def, TRI, /*IncludeSelf=*/true); SR.isValid();
470 ++SR) {
471 CopyMap[*SR] = MI;
472 AvailCopyMap[*SR] = MI;
Alexander Timofeev38282422017-10-16 14:35:29 +0000473 }
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000474
Alexander Timofeev9dff31c2017-10-16 16:57:37 +0000475 // Remember source that's copied to Def. Once it's clobbered, then
476 // it's no longer available for copy propagation.
477 RegList &DestList = SrcMap[Src];
478 if (!is_contained(DestList, Def))
479 DestList.push_back(Def);
480
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000481 continue;
482 }
483
Geoff Berrya2b90112018-02-27 16:59:10 +0000484 // Clobber any earlyclobber regs first.
485 for (const MachineOperand &MO : MI->operands())
486 if (MO.isReg() && MO.isEarlyClobber()) {
487 unsigned Reg = MO.getReg();
488 // If we have a tied earlyclobber, that means it is also read by this
489 // instruction, so we need to make sure we don't remove it as dead
490 // later.
491 if (MO.isTied())
492 ReadRegister(Reg);
493 ClobberRegister(Reg);
494 }
495
496 forwardUses(*MI);
497
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000498 // Not a copy.
499 SmallVector<unsigned, 2> Defs;
Matthias Braun273575d2016-02-20 03:56:36 +0000500 const MachineOperand *RegMask = nullptr;
501 for (const MachineOperand &MO : MI->operands()) {
Jakob Stoklund Olesen8610a592012-02-08 22:37:35 +0000502 if (MO.isRegMask())
Matthias Braun273575d2016-02-20 03:56:36 +0000503 RegMask = &MO;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000504 if (!MO.isReg())
505 continue;
Geoff Berryfabedba2017-10-03 16:59:13 +0000506 unsigned Reg = MO.getReg();
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000507 if (!Reg)
508 continue;
509
Geoff Berryfabedba2017-10-03 16:59:13 +0000510 assert(!TargetRegisterInfo::isVirtualRegister(Reg) &&
511 "MachineCopyPropagation should be run after register allocation!");
512
Geoff Berrya2b90112018-02-27 16:59:10 +0000513 if (MO.isDef() && !MO.isEarlyClobber()) {
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000514 Defs.push_back(Reg);
515 continue;
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000516 } else if (MO.readsReg())
517 ReadRegister(Reg);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000518 }
519
Jakob Stoklund Olesen8610a592012-02-08 22:37:35 +0000520 // The instruction has a register mask operand which means that it clobbers
Matthias Braune39ff702016-02-26 03:18:50 +0000521 // a large set of registers. Treat clobbered registers the same way as
522 // defined registers.
Matthias Braun273575d2016-02-20 03:56:36 +0000523 if (RegMask) {
Jakob Stoklund Olesen938b4d22012-02-09 00:19:08 +0000524 // Erase any MaybeDeadCopies whose destination register is clobbered.
Jun Bum Lim36c53fe2016-03-25 21:15:35 +0000525 for (SmallSetVector<MachineInstr *, 8>::iterator DI =
526 MaybeDeadCopies.begin();
527 DI != MaybeDeadCopies.end();) {
528 MachineInstr *MaybeDead = *DI;
Matthias Braun273575d2016-02-20 03:56:36 +0000529 unsigned Reg = MaybeDead->getOperand(0).getReg();
530 assert(!MRI->isReserved(Reg));
Jun Bum Lim36c53fe2016-03-25 21:15:35 +0000531
532 if (!RegMask->clobbersPhysReg(Reg)) {
533 ++DI;
Jakob Stoklund Olesen938b4d22012-02-09 00:19:08 +0000534 continue;
Jun Bum Lim36c53fe2016-03-25 21:15:35 +0000535 }
536
James Molloyd787d3e2014-01-22 09:12:27 +0000537 DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
Matthias Braun273575d2016-02-20 03:56:36 +0000538 MaybeDead->dump());
Jun Bum Lim36c53fe2016-03-25 21:15:35 +0000539
540 // erase() will return the next valid iterator pointing to the next
541 // element after the erased one.
542 DI = MaybeDeadCopies.erase(DI);
Matthias Braun273575d2016-02-20 03:56:36 +0000543 MaybeDead->eraseFromParent();
Jakob Stoklund Olesen938b4d22012-02-09 00:19:08 +0000544 Changed = true;
545 ++NumDeletes;
546 }
Matthias Braune39ff702016-02-26 03:18:50 +0000547
548 removeClobberedRegsFromMap(AvailCopyMap, *RegMask);
549 removeClobberedRegsFromMap(CopyMap, *RegMask);
550 for (SourceMap::iterator I = SrcMap.begin(), E = SrcMap.end(), Next;
551 I != E; I = Next) {
552 Next = std::next(I);
553 if (RegMask->clobbersPhysReg(I->first)) {
554 removeRegsFromMap(AvailCopyMap, I->second, *TRI);
555 SrcMap.erase(I);
556 }
557 }
Jakob Stoklund Olesen8610a592012-02-08 22:37:35 +0000558 }
559
Matthias Braune39ff702016-02-26 03:18:50 +0000560 // Any previous copy definition or reading the Defs is no longer available.
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000561 for (unsigned Reg : Defs)
Matthias Braune39ff702016-02-26 03:18:50 +0000562 ClobberRegister(Reg);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000563 }
564
565 // If MBB doesn't have successors, delete the copies whose defs are not used.
566 // If MBB does have successors, then conservative assume the defs are live-out
567 // since we don't want to trust live-in lists.
568 if (MBB.succ_empty()) {
Matthias Braun273575d2016-02-20 03:56:36 +0000569 for (MachineInstr *MaybeDead : MaybeDeadCopies) {
Geoff Berrya2b90112018-02-27 16:59:10 +0000570 DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
571 MaybeDead->dump());
Matthias Braun273575d2016-02-20 03:56:36 +0000572 assert(!MRI->isReserved(MaybeDead->getOperand(0).getReg()));
573 MaybeDead->eraseFromParent();
574 Changed = true;
575 ++NumDeletes;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000576 }
577 }
578
Matthias Braunbd18d752016-02-20 03:56:39 +0000579 MaybeDeadCopies.clear();
580 AvailCopyMap.clear();
581 CopyMap.clear();
582 SrcMap.clear();
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000583}
584
585bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000586 if (skipFunction(MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000587 return false;
588
Matthias Braunbd18d752016-02-20 03:56:39 +0000589 Changed = false;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000590
Eric Christopherfc6de422014-08-05 02:39:49 +0000591 TRI = MF.getSubtarget().getRegisterInfo();
592 TII = MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesenc30a9af2012-10-15 21:57:41 +0000593 MRI = &MF.getRegInfo();
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000594
Matthias Braun273575d2016-02-20 03:56:36 +0000595 for (MachineBasicBlock &MBB : MF)
Matthias Braunbd18d752016-02-20 03:56:39 +0000596 CopyPropagateBlock(MBB);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000597
598 return Changed;
599}