LLVM 24.0.0git
MachineCopyPropagation.cpp
Go to the documentation of this file.
1//===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This is an extremely simple MachineInstr-level copy propagation pass.
10//
11// This pass forwards the source of COPYs to the users of their destinations
12// when doing so is legal. For example:
13//
14// %reg1 = COPY %reg0
15// ...
16// ... = OP %reg1
17//
18// If
19// - %reg0 has not been clobbered by the time of the use of %reg1
20// - the register class constraints are satisfied
21// - the COPY def is the only value that reaches OP
22// then this pass replaces the above with:
23//
24// %reg1 = COPY %reg0
25// ...
26// ... = OP %reg0
27//
28// This pass also removes some redundant COPYs. For example:
29//
30// %R1 = COPY %R0
31// ... // No clobber of %R1
32// %R0 = COPY %R1 <<< Removed
33//
34// or
35//
36// %R1 = COPY %R0
37// ... // No clobber of %R0
38// %R1 = COPY %R0 <<< Removed
39//
40// or
41//
42// $R0 = OP ...
43// ... // No read/clobber of $R0 and $R1
44// $R1 = COPY $R0 // $R0 is killed
45// Replace $R0 with $R1 and remove the COPY
46// $R1 = OP ...
47// ...
48//
49//===----------------------------------------------------------------------===//
50
52#include "llvm/ADT/DenseMap.h"
53#include "llvm/ADT/STLExtras.h"
54#include "llvm/ADT/SetVector.h"
55#include "llvm/ADT/SmallSet.h"
57#include "llvm/ADT/Statistic.h"
70#include "llvm/MC/MCRegister.h"
72#include "llvm/Pass.h"
73#include "llvm/Support/Debug.h"
76#include <cassert>
77#include <iterator>
78
79using namespace llvm;
80
81#define DEBUG_TYPE "machine-cp"
82
83STATISTIC(NumDeletes, "Number of dead copies deleted");
84STATISTIC(NumCopyForwards, "Number of copy uses forwarded");
85STATISTIC(NumCopyBackwardPropagated, "Number of copy defs backward propagated");
86STATISTIC(SpillageChainsLength, "Length of spillage chains");
87STATISTIC(NumSpillageChains, "Number of spillage chains");
88DEBUG_COUNTER(FwdCounter, "machine-cp-fwd",
89 "Controls which register COPYs are forwarded");
90
91static cl::opt<bool> MCPUseCopyInstr("mcp-use-is-copy-instr", cl::init(false),
94 EnableSpillageCopyElimination("enable-spill-copy-elim", cl::Hidden);
95
96namespace {
97
98MCRegister asPhysMCReg(const MachineOperand *Operand) {
99 Register Reg = Operand->getReg();
100 assert(Reg.isPhysical() &&
101 "MachineCopyPropagation should be run after register allocation!");
102 return Reg;
103}
104
105MCRegister getDstMCReg(const DestSourcePair &DSP) {
106 return asPhysMCReg(DSP.Destination);
107}
108MCRegister getSrcMCReg(const DestSourcePair &DSP) {
109 return asPhysMCReg(DSP.Source);
110}
111std::pair<MCRegister, MCRegister> getDstSrcMCRegs(const DestSourcePair &DSP) {
112 return {getDstMCReg(DSP), getSrcMCReg(DSP)};
113}
114
115std::optional<DestSourcePair> isCopyInstr(const MachineInstr &MI,
116 const TargetInstrInfo &TII,
117 bool UseCopyInstr) {
118 if (UseCopyInstr)
119 return TII.isCopyInstr(MI);
120
121 if (MI.isCopy())
122 return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
123
124 return std::nullopt;
125}
126
127class CopyTracker {
128 struct CopyInfo {
129 MachineInstr *MI = nullptr;
130 MachineInstr *LastSeenUseInCopy = nullptr;
131 SmallPtrSet<MachineInstr *, 4> SrcUsers;
133 bool Avail = false;
134 };
135
136 DenseMap<MCRegUnit, CopyInfo> Copies;
137
138 // Memoised sets of register units which are preserved by each register mask,
139 // needed to efficiently remove copies which are invalidated by call
140 // instructions.
141 DenseMap<const uint32_t *, BitVector> RegMaskToPreservedRegUnits;
142
143public:
144 /// Get the set of register units which are preserved by RegMaskOp.
145 BitVector &getPreservedRegUnits(const MachineOperand &RegMaskOp,
146 const TargetRegisterInfo &TRI) {
147 const uint32_t *RegMask = RegMaskOp.getRegMask();
148 auto [It, Inserted] = RegMaskToPreservedRegUnits.try_emplace(RegMask);
149 if (!Inserted)
150 return It->second;
151 BitVector &PreservedRegUnits = It->second;
152
153 PreservedRegUnits.resize(TRI.getNumRegUnits());
154 for (unsigned SafeReg = 0, E = TRI.getNumRegs(); SafeReg < E; ++SafeReg)
155 if (!RegMaskOp.clobbersPhysReg(SafeReg))
156 for (MCRegUnit SafeUnit : TRI.regunits(SafeReg))
157 PreservedRegUnits.set(static_cast<unsigned>(SafeUnit));
158
159 return PreservedRegUnits;
160 }
161
162 /// Mark all of the given registers and their subregisters as unavailable for
163 /// copying.
164 void markRegsUnavailable(ArrayRef<MCRegister> Regs,
165 const TargetRegisterInfo &TRI) {
166 for (MCRegister Reg : Regs) {
167 // Source of copy is no longer available for propagation.
168 for (MCRegUnit Unit : TRI.regunits(Reg)) {
169 auto CI = Copies.find(Unit);
170 if (CI != Copies.end())
171 CI->second.Avail = false;
172 }
173 }
174 }
175
176 /// Remove register from copy maps.
177 void invalidateRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
178 const TargetInstrInfo &TII, bool UseCopyInstr) {
179 // Early exit if there are no copies, as the function wouldn't do anything
180 // in that case.
181 if (Copies.empty())
182 return;
183
184 // Since Reg might be a subreg of some registers, only invalidate Reg is not
185 // enough. We have to find the COPY defines Reg or registers defined by Reg
186 // and invalidate all of them. Similarly, we must invalidate all of the
187 // the subregisters used in the source of the COPY.
188 SmallSet<MCRegUnit, 8> RegUnitsToInvalidate;
189 auto InvalidateCopy = [&](MachineInstr *MI) {
190 DestSourcePair CopyOperands = *isCopyInstr(*MI, TII, UseCopyInstr);
191 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
192 auto DstUnits = TRI.regunits(Dst);
193 auto SrcUnits = TRI.regunits(Src);
194 RegUnitsToInvalidate.insert_range(DstUnits);
195 RegUnitsToInvalidate.insert_range(SrcUnits);
196 };
197
198 for (MCRegUnit Unit : TRI.regunits(Reg)) {
199 auto I = Copies.find(Unit);
200 if (I != Copies.end()) {
201 if (MachineInstr *MI = I->second.MI)
202 InvalidateCopy(MI);
203 if (MachineInstr *MI = I->second.LastSeenUseInCopy)
204 InvalidateCopy(MI);
205 }
206 }
207 for (MCRegUnit Unit : RegUnitsToInvalidate)
208 Copies.erase(Unit);
209 }
210
211 /// Clobber a single register unit, removing it from the tracker's copy maps.
212 void clobberRegUnit(MCRegUnit Unit, const TargetRegisterInfo &TRI,
213 const TargetInstrInfo &TII, bool UseCopyInstr) {
214 auto I = Copies.find(Unit);
215 if (I != Copies.end()) {
216 // When we clobber the source of a copy, we need to clobber everything
217 // it defined.
218 markRegsUnavailable(I->second.DefRegs, TRI);
219 // When we clobber the destination of a copy, we need to clobber the
220 // whole register it defined.
221 if (MachineInstr *MI = I->second.MI) {
222 DestSourcePair CopyOperands = *isCopyInstr(*MI, TII, UseCopyInstr);
223 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
224
225 markRegsUnavailable(Dst, TRI);
226
227 // Since we clobber the destination of a copy, the semantic of Src's
228 // "DefRegs" to contain Def is no longer effectual. We will also need
229 // to remove the record from the copy maps that indicates Src defined
230 // Def. Failing to do so might cause the target to miss some
231 // opportunities to further eliminate redundant copy instructions.
232 // Consider the following sequence during the
233 // ForwardCopyPropagateBlock procedure:
234 // L1: r0 = COPY r9 <- TrackMI
235 // L2: r0 = COPY r8 <- TrackMI (Remove r9 defined r0 from tracker)
236 // L3: use r0 <- Remove L2 from MaybeDeadCopies
237 // L4: early-clobber r9 <- Clobber r9 (L2 is still valid in tracker)
238 // L5: r0 = COPY r8 <- Remove NopCopy
239 for (MCRegUnit SrcUnit : TRI.regunits(Src)) {
240 auto SrcCopy = Copies.find(SrcUnit);
241 if (SrcCopy != Copies.end() && SrcCopy->second.LastSeenUseInCopy) {
242 // If SrcCopy defines multiple values, we only need
243 // to erase the record for Def in DefRegs.
244 // NOLINTNEXTLINE(llvm-qualified-auto)
245 for (auto Itr = SrcCopy->second.DefRegs.begin();
246 Itr != SrcCopy->second.DefRegs.end(); Itr++) {
247 if (*Itr == Dst) {
248 SrcCopy->second.DefRegs.erase(Itr);
249 // If DefReg becomes empty after removal, we can remove the
250 // SrcCopy from the tracker's copy maps. We only remove those
251 // entries solely record the Def is defined by Src. If an
252 // entry also contains the definition record of other Def'
253 // registers, it cannot be cleared.
254 if (SrcCopy->second.DefRegs.empty() && !SrcCopy->second.MI) {
255 Copies.erase(SrcCopy);
256 }
257 break;
258 }
259 }
260 }
261 }
262 }
263 // Now we can erase the copy.
264 Copies.erase(Unit);
265 }
266 }
267
268 /// Clobber a single register, removing it from the tracker's copy maps.
269 void clobberRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
270 const TargetInstrInfo &TII, bool UseCopyInstr) {
271 // Early exit if there are no copies, as the function wouldn't do anything
272 // in that case.
273 if (Copies.empty())
274 return;
275
276 for (MCRegUnit Unit : TRI.regunits(Reg)) {
277 clobberRegUnit(Unit, TRI, TII, UseCopyInstr);
278 }
279 }
280
281 /// Track copy's src users, and return false if that can't be done.
282 /// We can only track if we have a COPY instruction which source is
283 /// the same as the Reg.
284 bool trackSrcUsers(MCRegister Reg, MachineInstr &MI,
285 const TargetRegisterInfo &TRI, const TargetInstrInfo &TII,
286 bool UseCopyInstr) {
287 MCRegUnit RU = *TRI.regunits(Reg).begin();
288 MachineInstr *AvailCopy = findCopyDefViaUnit(RU, TRI);
289 if (!AvailCopy)
290 return false;
291
292 DestSourcePair CopyOperands = *isCopyInstr(*AvailCopy, TII, UseCopyInstr);
293 MCRegister Src = getSrcMCReg(CopyOperands);
294
295 // Bail out, if the source of the copy is not the same as the Reg.
296 if (Src != Reg)
297 return false;
298
299 auto I = Copies.find(RU);
300 if (I == Copies.end())
301 return false;
302
303 I->second.SrcUsers.insert(&MI);
304 return true;
305 }
306
307 /// Return the users for a given register.
308 SmallPtrSet<MachineInstr *, 4> getSrcUsers(MCRegister Reg,
309 const TargetRegisterInfo &TRI) {
310 MCRegUnit RU = *TRI.regunits(Reg).begin();
311 auto I = Copies.find(RU);
312 if (I == Copies.end())
313 return {};
314 return I->second.SrcUsers;
315 }
316
317 /// Add this copy's registers into the tracker's copy maps.
318 void trackCopy(MachineInstr *MI, const TargetRegisterInfo &TRI,
319 const TargetInstrInfo &TII, bool UseCopyInstr) {
320 DestSourcePair CopyOperands = *isCopyInstr(*MI, TII, UseCopyInstr);
321 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
322
323 // Remember Dst is defined by the copy.
324 for (MCRegUnit Unit : TRI.regunits(Dst))
325 Copies[Unit] = {MI, nullptr, {}, {}, true};
326
327 // Remember source that's copied to Dst. Once it's clobbered, then
328 // it's no longer available for copy propagation.
329 for (MCRegUnit Unit : TRI.regunits(Src)) {
330 auto &Copy = Copies[Unit];
331 if (!is_contained(Copy.DefRegs, Dst))
332 Copy.DefRegs.push_back(Dst);
333 Copy.LastSeenUseInCopy = MI;
334 }
335 }
336
337 bool hasAnyCopies() {
338 return !Copies.empty();
339 }
340
341 MachineInstr *findCopyForUnit(MCRegUnit RegUnit,
342 const TargetRegisterInfo &TRI,
343 bool MustBeAvailable = false) {
344 auto CI = Copies.find(RegUnit);
345 if (CI == Copies.end())
346 return nullptr;
347 if (MustBeAvailable && !CI->second.Avail)
348 return nullptr;
349 return CI->second.MI;
350 }
351
352 MachineInstr *findCopyDefViaUnit(MCRegUnit RegUnit,
353 const TargetRegisterInfo &TRI) {
354 auto CI = Copies.find(RegUnit);
355 if (CI == Copies.end())
356 return nullptr;
357 if (CI->second.DefRegs.size() != 1)
358 return nullptr;
359 MCRegUnit RU = *TRI.regunits(CI->second.DefRegs[0]).begin();
360 return findCopyForUnit(RU, TRI, true);
361 }
362
363 MachineInstr *findAvailBackwardCopy(MachineInstr &I, MCRegister Reg,
364 const TargetRegisterInfo &TRI,
365 const TargetInstrInfo &TII,
366 bool UseCopyInstr) {
367 MCRegUnit RU = *TRI.regunits(Reg).begin();
368 MachineInstr *AvailCopy = findCopyDefViaUnit(RU, TRI);
369
370 if (!AvailCopy)
371 return nullptr;
372
373 DestSourcePair CopyOperands = *isCopyInstr(*AvailCopy, TII, UseCopyInstr);
374 auto [AvailDst, AvailSrc] = getDstSrcMCRegs(CopyOperands);
375 if (!TRI.isSubRegisterEq(AvailSrc, Reg))
376 return nullptr;
377
378 for (const MachineInstr &MI :
379 make_range(AvailCopy->getReverseIterator(), I.getReverseIterator()))
380 for (const MachineOperand &MO : MI.operands())
381 if (MO.isRegMask())
382 // FIXME: Shall we simultaneously invalidate AvailSrc or AvailDst?
383 if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDst))
384 return nullptr;
385
386 return AvailCopy;
387 }
388
389 MachineInstr *findAvailCopy(MachineInstr &DestCopy, MCRegister Reg,
390 const TargetRegisterInfo &TRI,
391 const TargetInstrInfo &TII, bool UseCopyInstr) {
392 // We check the first RegUnit here, since we'll only be interested in the
393 // copy if it copies the entire register anyway.
394 MCRegUnit RU = *TRI.regunits(Reg).begin();
395 MachineInstr *AvailCopy =
396 findCopyForUnit(RU, TRI, /*MustBeAvailable=*/true);
397
398 if (!AvailCopy)
399 return nullptr;
400
401 DestSourcePair CopyOperands = *isCopyInstr(*AvailCopy, TII, UseCopyInstr);
402 auto [AvailDst, AvailSrc] = getDstSrcMCRegs(CopyOperands);
403 if (!TRI.isSubRegisterEq(AvailDst, Reg))
404 return nullptr;
405
406 // Check that the available copy isn't clobbered by any regmasks between
407 // itself and the destination.
408 for (const MachineInstr &MI :
409 make_range(AvailCopy->getIterator(), DestCopy.getIterator()))
410 for (const MachineOperand &MO : MI.operands())
411 if (MO.isRegMask())
412 if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDst))
413 return nullptr;
414
415 return AvailCopy;
416 }
417
418 // Find last COPY that defines Reg before Current MachineInstr.
419 MachineInstr *findLastSeenDefInCopy(const MachineInstr &Current,
420 MCRegister Reg,
421 const TargetRegisterInfo &TRI,
422 const TargetInstrInfo &TII,
423 bool UseCopyInstr) {
424 MCRegUnit RU = *TRI.regunits(Reg).begin();
425 auto CI = Copies.find(RU);
426 if (CI == Copies.end() || !CI->second.Avail)
427 return nullptr;
428
429 MachineInstr *DefCopy = CI->second.MI;
430 DestSourcePair CopyOperands = *isCopyInstr(*DefCopy, TII, UseCopyInstr);
431 MCRegister Dst = getDstMCReg(CopyOperands);
432 if (!TRI.isSubRegisterEq(Dst, Reg))
433 return nullptr;
434
435 return DefCopy;
436 }
437
438 void clobberNonPreservedRegs(const BitVector &PreservedRegUnits,
439 const TargetRegisterInfo &TRI,
440 const TargetInstrInfo &TII) {
441 SmallVector<MCRegUnit, 8> UnitsToClobber;
442 for (auto &[Unit, _] : Copies)
443 if (!PreservedRegUnits.test(static_cast<unsigned>(Unit)))
444 UnitsToClobber.push_back(Unit);
445
446 for (MCRegUnit Unit : UnitsToClobber) {
447 // If we clobber the RegUnit, it will mark all the DefReg Units
448 // as unavailable, which leads to issues if the Destination Reg Unit is
449 // preserved, and used later. As such, only mark them as unavailable if
450 // they are not preserved.
451 auto RegUnitInfo = Copies.find(Unit);
452 if (RegUnitInfo == Copies.end())
453 continue;
454
455 for (MCRegister DstReg : RegUnitInfo->second.DefRegs) {
456 for (MCRegUnit DstUnit : TRI.regunits(DstReg)) {
457 if (!PreservedRegUnits.test(static_cast<unsigned>(DstUnit))) {
458 if (auto CI = Copies.find(DstUnit); CI != Copies.end()) {
459 CI->second.Avail = false;
460 }
461 }
462 }
463 }
464 Copies.erase(RegUnitInfo);
465 }
466 }
467
468 // Find last COPY that uses Reg.
469 MachineInstr *findLastSeenUseInCopy(MCRegister Reg,
470 const TargetRegisterInfo &TRI) {
471 MCRegUnit RU = *TRI.regunits(Reg).begin();
472 auto CI = Copies.find(RU);
473 if (CI == Copies.end())
474 return nullptr;
475 return CI->second.LastSeenUseInCopy;
476 }
477
478 void clear() {
479 Copies.clear();
480 }
481};
482
483class MachineCopyPropagation {
484 const TargetRegisterInfo *TRI = nullptr;
485 const TargetInstrInfo *TII = nullptr;
486 const MachineRegisterInfo *MRI = nullptr;
487
488 // Return true if this is a copy instruction and false otherwise.
489 bool UseCopyInstr;
490
491public:
492 MachineCopyPropagation(bool CopyInstr = false)
493 : UseCopyInstr(CopyInstr || MCPUseCopyInstr) {}
494
495 bool run(MachineFunction &MF);
496
497private:
498 typedef enum { DebugUse = false, RegularUse = true } DebugType;
499
500 void readRegister(MCRegister Reg, MachineInstr &Reader, DebugType DT);
501 void readSuccessorLiveIns(const MachineBasicBlock &MBB);
502 void forwardCopyPropagateBlock(MachineBasicBlock &MBB);
503 void backwardCopyPropagateBlock(MachineBasicBlock &MBB);
504 void eliminateSpillageCopies(MachineBasicBlock &MBB);
505 bool eraseIfRedundant(MachineInstr &Copy, MCRegister Dst, MCRegister Src);
506 void forwardUses(MachineInstr &MI);
507 void propagateDefs(MachineInstr &MI);
508 bool isForwardableRegClassCopy(const MachineInstr &Copy,
509 const MachineInstr &UseI, unsigned UseIdx);
510 bool isBackwardPropagatableRegClassCopy(const MachineInstr &Copy,
511 const MachineInstr &UseI,
512 unsigned UseIdx);
513 bool isBackwardPropagatableCopy(const MachineInstr &Copy,
514 const DestSourcePair &CopyOperands);
515 /// Returns true iff a copy instruction having operand @p CopyOperand must
516 /// never be eliminated as redundant.
517 bool isNeverRedundant(MCRegister CopyOperand) {
518 // Avoid eliminating a copy from/to a reserved registers as we cannot
519 // predict the value (Example: The sparc zero register is writable but stays
520 // zero).
521 return MRI->isReserved(CopyOperand);
522 }
523 /// Returns true iff the @p Copy instruction must never be eliminated as
524 /// redundant. This overload does not consider the operands of @p Copy.
525 bool isNeverRedundant(const MachineInstr &Copy) {
526 return Copy.getFlag(MachineInstr::FrameSetup) ||
528 }
529 bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use);
530 bool hasOverlappingMultipleDef(const MachineInstr &MI,
531 const MachineOperand &MODef, MCRegister Def);
532 bool canUpdateSrcUsers(const MachineInstr &Copy,
533 const MachineOperand &CopySrc);
534
535 /// Candidates for deletion.
536 SmallSetVector<MachineInstr *, 8> MaybeDeadCopies;
537
538 /// Multimap tracking debug users in current BB
539 DenseMap<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> CopyDbgUsers;
540
541 CopyTracker Tracker;
542
543 bool Changed = false;
544};
545
546class MachineCopyPropagationLegacy : public MachineFunctionPass {
547 bool UseCopyInstr;
548
549public:
550 static char ID; // pass identification
551
552 MachineCopyPropagationLegacy(bool UseCopyInstr = false)
553 : MachineFunctionPass(ID), UseCopyInstr(UseCopyInstr) {}
554
555 void getAnalysisUsage(AnalysisUsage &AU) const override {
556 AU.setPreservesCFG();
557 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
559 }
560
561 bool runOnMachineFunction(MachineFunction &MF) override;
562
563 MachineFunctionProperties getRequiredProperties() const override {
564 return MachineFunctionProperties().setNoVRegs();
565 }
566};
567
568} // end anonymous namespace
569
570char MachineCopyPropagationLegacy::ID = 0;
571
572char &llvm::MachineCopyPropagationID = MachineCopyPropagationLegacy::ID;
573
574INITIALIZE_PASS(MachineCopyPropagationLegacy, DEBUG_TYPE,
575 "Machine Copy Propagation Pass", false, false)
576
577void MachineCopyPropagation::readRegister(MCRegister Reg, MachineInstr &Reader,
578 DebugType DT) {
579 // If 'Reg' is defined by a copy, the copy is no longer a candidate
580 // for elimination. If a copy is "read" by a debug user, record the user
581 // for propagation.
582 for (MCRegUnit Unit : TRI->regunits(Reg)) {
583 if (MachineInstr *Copy = Tracker.findCopyForUnit(Unit, *TRI)) {
584 if (DT == RegularUse) {
585 LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy->dump());
586 MaybeDeadCopies.remove(Copy);
587 } else {
588 CopyDbgUsers[Copy].insert(&Reader);
589 }
590 }
591 }
592}
593
594void MachineCopyPropagation::readSuccessorLiveIns(
595 const MachineBasicBlock &MBB) {
596 if (MaybeDeadCopies.empty())
597 return;
598
599 // If a copy result is livein to a successor, it is not dead.
600 for (const MachineBasicBlock *Succ : MBB.successors()) {
601 for (const auto &LI : Succ->liveins()) {
602 for (MCRegUnitMaskIterator U(LI.PhysReg, TRI); U.isValid(); ++U) {
603 auto [Unit, Mask] = *U;
604 if ((Mask & LI.LaneMask).any()) {
605 if (MachineInstr *Copy = Tracker.findCopyForUnit(Unit, *TRI))
606 MaybeDeadCopies.remove(Copy);
607 }
608 }
609 }
610 }
611}
612
613/// Return true if \p PreviousCopy did copy register \p Src to register \p Dst.
614/// This fact may have been obscured by sub register usage or may not be true at
615/// all even though Src and Dst are subregisters of the registers used in
616/// PreviousCopy. e.g.
617/// isNopCopy("ecx = COPY eax", AX, CX) == true
618/// isNopCopy("ecx = COPY eax", AH, CL) == false
619static bool isNopCopy(const MachineInstr &PreviousCopy, MCRegister Src,
621 const TargetInstrInfo *TII, bool UseCopyInstr) {
622
623 DestSourcePair CopyOperands = *isCopyInstr(PreviousCopy, *TII, UseCopyInstr);
624 auto [PreviousDst, PreviousSrc] = getDstSrcMCRegs(CopyOperands);
625 if (Src == PreviousSrc && Dst == PreviousDst)
626 return true;
627 if (!TRI->isSubRegister(PreviousSrc, Src))
628 return false;
629 unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
630 return SubIdx == TRI->getSubRegIndex(PreviousDst, Dst);
631}
632
633/// Remove instruction \p Copy if there exists a previous copy that copies the
634/// register \p Src to the register \p Dst; This may happen indirectly by
635/// copying the super registers.
636bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy,
637 MCRegister Dst, MCRegister Src) {
638 if (isNeverRedundant(Copy) || isNeverRedundant(Src) || isNeverRedundant(Dst))
639 return false;
640
641 // Search for an existing copy.
642 MachineInstr *PrevCopy =
643 Tracker.findAvailCopy(Copy, Dst, *TRI, *TII, UseCopyInstr);
644 if (!PrevCopy)
645 return false;
646
647 DestSourcePair PrevCopyOperands = *isCopyInstr(*PrevCopy, *TII, UseCopyInstr);
648 // Check that the existing copy uses the correct sub registers.
649 if (PrevCopyOperands.Destination->isDead())
650 return false;
651 if (!isNopCopy(*PrevCopy, Src, Dst, TRI, TII, UseCopyInstr))
652 return false;
653
654 LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
655
656 // Copy was redundantly redefining either Src or Dst. Remove earlier kill
657 // flags between Copy and PrevCopy because the value will be reused now.
658 DestSourcePair CopyOperands = *isCopyInstr(Copy, *TII, UseCopyInstr);
659
660 MCRegister CopyDst = getDstMCReg(CopyOperands);
661 assert(CopyDst == Src || CopyDst == Dst);
662 for (MachineInstr &MI :
663 make_range(PrevCopy->getIterator(), Copy.getIterator()))
664 MI.clearRegisterKills(CopyDst, TRI);
665
666 // Clear undef flag from remaining copy if needed.
667 if (!CopyOperands.Source->isUndef()) {
668 PrevCopy->getOperand(PrevCopyOperands.Source->getOperandNo())
669 .setIsUndef(false);
670 }
671
672 Copy.eraseFromParent();
673 Changed = true;
674 ++NumDeletes;
675 return true;
676}
677
678bool MachineCopyPropagation::isBackwardPropagatableRegClassCopy(
679 const MachineInstr &Copy, const MachineInstr &UseI, unsigned UseIdx) {
680 DestSourcePair CopyOperands = *isCopyInstr(Copy, *TII, UseCopyInstr);
681 MCRegister Dst = getDstMCReg(CopyOperands);
682
683 if (const TargetRegisterClass *URC =
684 UseI.getRegClassConstraint(UseIdx, TII, TRI))
685 return URC->contains(Dst);
686
687 // We don't process further if UseI is a COPY, since forward copy propagation
688 // should handle that.
689 return false;
690}
691
692bool MachineCopyPropagation::isBackwardPropagatableCopy(
693 const MachineInstr &Copy, const DestSourcePair &CopyOperands) {
694 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
695
696 if (!Dst || !Src)
697 return false;
698
699 if (isNeverRedundant(Copy) || isNeverRedundant(Dst) || isNeverRedundant(Src))
700 return false;
701
702 return CopyOperands.Source->isRenamable() && CopyOperands.Source->isKill();
703}
704
705/// Decide whether we should forward the source of \param Copy to its use in
706/// \param UseI based on the physical register class constraints of the opcode
707/// and avoiding introducing more cross-class COPYs.
708bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
709 const MachineInstr &UseI,
710 unsigned UseIdx) {
711 DestSourcePair CopyOperands = *isCopyInstr(Copy, *TII, UseCopyInstr);
712 MCRegister CopySrc = getSrcMCReg(CopyOperands);
713
714 // If the new register meets the opcode register constraints, then allow
715 // forwarding.
716 if (const TargetRegisterClass *URC =
717 UseI.getRegClassConstraint(UseIdx, TII, TRI))
718 return URC->contains(CopySrc);
719
720 std::optional<DestSourcePair> UseICopyOperands =
721 isCopyInstr(UseI, *TII, UseCopyInstr);
722 if (!UseICopyOperands)
723 return false;
724
725 /// COPYs don't have register class constraints, so if the user instruction
726 /// is a COPY, we just try to avoid introducing additional cross-class
727 /// COPYs. For example:
728 ///
729 /// RegClassA = COPY RegClassB // Copy parameter
730 /// ...
731 /// RegClassB = COPY RegClassA // UseI parameter
732 ///
733 /// which after forwarding becomes
734 ///
735 /// RegClassA = COPY RegClassB
736 /// ...
737 /// RegClassB = COPY RegClassB
738 ///
739 /// so we have reduced the number of cross-class COPYs and potentially
740 /// introduced a nop COPY that can be removed.
741
742 // Allow forwarding if src and dst belong to any common class, so long as they
743 // don't belong to any (possibly smaller) common class that requires copies to
744 // go via a different class.
745 MCRegister UseDst = getDstMCReg(*UseICopyOperands);
746 bool Found = false;
747 bool IsCrossClass = false;
748 for (const TargetRegisterClass &RC : TRI->regclasses()) {
749 if (RC.contains(CopySrc) && RC.contains(UseDst)) {
750 Found = true;
751 if (TRI->getCrossCopyRegClass(&RC) != &RC) {
752 IsCrossClass = true;
753 break;
754 }
755 }
756 }
757 if (!Found)
758 return false;
759 if (!IsCrossClass)
760 return true;
761 // The forwarded copy would be cross-class. Only do this if the original copy
762 // was also cross-class.
763 MCRegister CopyDst = getDstMCReg(CopyOperands);
764 for (const TargetRegisterClass &RC : TRI->regclasses()) {
765 if (RC.contains(CopySrc) && RC.contains(CopyDst) &&
766 TRI->getCrossCopyRegClass(&RC) != &RC)
767 return true;
768 }
769 return false;
770}
771
772/// Check that \p MI does not have implicit uses that overlap with it's \p Use
773/// operand (the register being replaced), since these can sometimes be
774/// implicitly tied to other operands. For example, on AMDGPU:
775///
776/// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
777///
778/// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
779/// way of knowing we need to update the latter when updating the former.
780bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
781 const MachineOperand &Use) {
782 for (const MachineOperand &MIUse : MI.uses())
783 if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
784 MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
785 return true;
786
787 return false;
788}
789
790/// For an MI that has multiple definitions, check whether \p MI has
791/// a definition that overlaps with another of its definitions.
792/// For example, on ARM: umull r9, r9, lr, r0
793/// The umull instruction is unpredictable unless RdHi and RdLo are different.
794bool MachineCopyPropagation::hasOverlappingMultipleDef(
795 const MachineInstr &MI, const MachineOperand &MODef, MCRegister Def) {
796 for (const MachineOperand &MIDef : MI.all_defs()) {
797 if ((&MIDef != &MODef) && MIDef.isReg() &&
798 TRI->regsOverlap(Def, MIDef.getReg()))
799 return true;
800 }
801
802 return false;
803}
804
805/// Return true if it is safe to update all users of the \p CopySrc register
806/// in the given \p Copy instruction.
807bool MachineCopyPropagation::canUpdateSrcUsers(const MachineInstr &Copy,
808 const MachineOperand &CopySrc) {
809 assert(CopySrc.isReg() && "Expected a register operand");
810 for (auto *SrcUser : Tracker.getSrcUsers(CopySrc.getReg(), *TRI)) {
811 if (hasImplicitOverlap(*SrcUser, CopySrc))
812 return false;
813
814 for (MachineOperand &MO : SrcUser->uses()) {
815 if (!MO.isReg() || !MO.isUse() || MO.getReg() != CopySrc.getReg())
816 continue;
817 if (MO.isTied() || !MO.isRenamable() ||
818 !isBackwardPropagatableRegClassCopy(Copy, *SrcUser,
819 MO.getOperandNo()))
820 return false;
821 }
822 }
823 return true;
824}
825
826/// Look for available copies whose destination register is used by \p MI and
827/// replace the use in \p MI with the copy's source register.
828void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
829 if (!Tracker.hasAnyCopies())
830 return;
831
832 // Look for non-tied explicit vreg uses that have an active COPY
833 // instruction that defines the physical register allocated to them.
834 // Replace the vreg with the source of the active COPY.
835 for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
836 ++OpIdx) {
837 MachineOperand &MOUse = MI.getOperand(OpIdx);
838 // Don't forward into undef use operands since doing so can cause problems
839 // with the machine verifier, since it doesn't treat undef reads as reads,
840 // so we can end up with a live range that ends on an undef read, leading to
841 // an error that the live range doesn't end on a read of the live range
842 // register.
843 if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
844 MOUse.isImplicit())
845 continue;
846
847 if (!MOUse.getReg())
848 continue;
849
850 // Check that the register is marked 'renamable' so we know it is safe to
851 // rename it without violating any constraints that aren't expressed in the
852 // IR (e.g. ABI or opcode requirements).
853 if (!MOUse.isRenamable())
854 continue;
855
856 MachineInstr *Copy = Tracker.findAvailCopy(MI, MOUse.getReg().asMCReg(),
857 *TRI, *TII, UseCopyInstr);
858 if (!Copy)
859 continue;
860
861 DestSourcePair CopyOperands = *isCopyInstr(*Copy, *TII, UseCopyInstr);
862 auto [CopyDst, CopySrc] = getDstSrcMCRegs(CopyOperands);
863 const MachineOperand &CopySrcOperand = *CopyOperands.Source;
864
865 MCRegister ForwardedReg = CopySrc;
866 // MI might use a sub-register of the Copy destination, in which case the
867 // forwarded register is the matching sub-register of the Copy source.
868 if (MOUse.getReg() != CopyDst) {
869 unsigned SubRegIdx = TRI->getSubRegIndex(CopyDst, MOUse.getReg());
870 assert(SubRegIdx &&
871 "MI source is not a sub-register of Copy destination");
872 ForwardedReg = TRI->getSubReg(CopySrc, SubRegIdx);
873 if (!ForwardedReg || TRI->isArtificial(ForwardedReg)) {
874 LLVM_DEBUG(dbgs() << "MCP: Copy source does not have sub-register "
875 << TRI->getSubRegIndexName(SubRegIdx) << '\n');
876 continue;
877 }
878 }
879
880 // Don't forward COPYs of reserved regs unless they are constant.
881 if (MRI->isReserved(CopySrc) && !MRI->isConstantPhysReg(CopySrc))
882 continue;
883
884 if (!isForwardableRegClassCopy(*Copy, MI, OpIdx))
885 continue;
886
887 if (hasImplicitOverlap(MI, MOUse))
888 continue;
889
890 // Check that the instruction is not a copy that partially overwrites the
891 // original copy source that we are about to use. The tracker mechanism
892 // cannot cope with that.
893 if (isCopyInstr(MI, *TII, UseCopyInstr) &&
894 MI.modifiesRegister(CopySrc, TRI) &&
895 !MI.definesRegister(CopySrc, /*TRI=*/nullptr)) {
896 LLVM_DEBUG(dbgs() << "MCP: Copy source overlap with dest in " << MI);
897 continue;
898 }
899
900 if (!DebugCounter::shouldExecute(FwdCounter)) {
901 LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n "
902 << MI);
903 continue;
904 }
905
906 LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
907 << "\n with " << printReg(ForwardedReg, TRI)
908 << "\n in " << MI << " from " << *Copy);
909
910 MOUse.setReg(ForwardedReg);
911
912 if (!CopySrcOperand.isRenamable())
913 MOUse.setIsRenamable(false);
914 MOUse.setIsUndef(CopySrcOperand.isUndef());
915
916 LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
917
918 // Clear kill markers that may have been invalidated.
919 for (MachineInstr &KMI :
920 make_range(Copy->getIterator(), std::next(MI.getIterator())))
921 KMI.clearRegisterKills(CopySrc, TRI);
922
923 ++NumCopyForwards;
924 Changed = true;
925 }
926}
927
928void MachineCopyPropagation::forwardCopyPropagateBlock(MachineBasicBlock &MBB) {
929 LLVM_DEBUG(dbgs() << "MCP: ForwardCopyPropagateBlock " << MBB.getName()
930 << "\n");
931
932 for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
933 // Analyze copies (which don't overlap themselves).
934 std::optional<DestSourcePair> CopyOperands =
935 isCopyInstr(MI, *TII, UseCopyInstr);
936 if (CopyOperands) {
937 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
938 if (!TRI->regsOverlap(Dst, Src)) {
939 // The two copies cancel out and the source of the first copy
940 // hasn't been overridden, eliminate the second one. e.g.
941 // %ecx = COPY %eax
942 // ... nothing clobbered eax.
943 // %eax = COPY %ecx
944 // =>
945 // %ecx = COPY %eax
946 //
947 // or
948 //
949 // %ecx = COPY %eax
950 // ... nothing clobbered eax.
951 // %ecx = COPY %eax
952 // =>
953 // %ecx = COPY %eax
954 if (eraseIfRedundant(MI, Dst, Src) || eraseIfRedundant(MI, Src, Dst))
955 continue;
956 }
957 }
958
959 // Clobber any earlyclobber regs first.
960 for (const MachineOperand &MO : MI.operands())
961 if (MO.isReg() && MO.isEarlyClobber()) {
962 MCRegister Reg = MO.getReg().asMCReg();
963 // If we have a tied earlyclobber, that means it is also read by this
964 // instruction, so we need to make sure we don't remove it as dead
965 // later.
966 if (MO.isTied())
967 readRegister(Reg, MI, RegularUse);
968 Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
969 }
970
971 forwardUses(MI);
972
973 // Attempt to canonicalize/optimize the instruction now its arguments have
974 // been mutated. This may convert MI from a non-copy to a copy instruction.
975 if (TII->simplifyInstruction(MI)) {
976 Changed = true;
977 LLVM_DEBUG(dbgs() << "MCP: After simplifyInstruction: " << MI);
978 }
979
980 CopyOperands = isCopyInstr(MI, *TII, UseCopyInstr);
981 if (CopyOperands) {
982 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
983 if (!TRI->regsOverlap(Dst, Src)) {
984 // FIXME: Document why this does not consider `RegSrc`, similar to how
985 // `backwardCopyPropagateBlock` does.
986 if (!isNeverRedundant(MI) && !isNeverRedundant(Dst))
987 MaybeDeadCopies.insert(&MI);
988 }
989 }
990
992 const MachineOperand *RegMask = nullptr;
993 for (const MachineOperand &MO : MI.operands()) {
994 if (MO.isRegMask())
995 RegMask = &MO;
996 if (!MO.isReg())
997 continue;
998 Register Reg = MO.getReg();
999 if (!Reg)
1000 continue;
1001
1002 assert(Reg.isPhysical() &&
1003 "MachineCopyPropagation should be run after register allocation!");
1004
1005 if (MO.isDef() && !MO.isEarlyClobber()) {
1006 // Skip invalidating constant registers.
1007 if (!MRI->isConstantPhysReg(Reg)) {
1008 Defs.push_back(Reg.asMCReg());
1009 continue;
1010 }
1011 } else if (MO.readsReg()) {
1012 readRegister(Reg.asMCReg(), MI, MO.isDebug() ? DebugUse : RegularUse);
1013 }
1014 }
1015
1016 // The instruction has a register mask operand which means that it clobbers
1017 // a large set of registers. Treat clobbered registers the same way as
1018 // defined registers.
1019 if (RegMask) {
1020 BitVector &PreservedRegUnits =
1021 Tracker.getPreservedRegUnits(*RegMask, *TRI);
1022
1023 // Erase any MaybeDeadCopies whose destination register is clobbered.
1024 for (SmallSetVector<MachineInstr *, 8>::iterator DI =
1025 MaybeDeadCopies.begin();
1026 DI != MaybeDeadCopies.end();) {
1027 MachineInstr *MaybeDead = *DI;
1028 std::optional<DestSourcePair> CopyOperands =
1029 isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
1030 MCRegister Reg = CopyOperands->Destination->getReg().asMCReg();
1031 assert(!isNeverRedundant(*MaybeDead) && !isNeverRedundant(Reg));
1032
1033 if (!RegMask->clobbersPhysReg(Reg)) {
1034 ++DI;
1035 continue;
1036 }
1037
1038 // Invalidate all entries in the copy map which are not preserved by
1039 // this register mask.
1040 bool MIRefedinCopyInfo = false;
1041 for (MCRegUnit RegUnit : TRI->regunits(Reg)) {
1042 if (!PreservedRegUnits.test(static_cast<unsigned>(RegUnit)))
1043 Tracker.clobberRegUnit(RegUnit, *TRI, *TII, UseCopyInstr);
1044 else {
1045 if (MaybeDead == Tracker.findCopyForUnit(RegUnit, *TRI)) {
1046 MIRefedinCopyInfo = true;
1047 }
1048 }
1049 }
1050
1051 // erase() will return the next valid iterator pointing to the next
1052 // element after the erased one.
1053 DI = MaybeDeadCopies.erase(DI);
1054
1055 // Preserved by RegMask, DO NOT remove copy
1056 if (MIRefedinCopyInfo)
1057 continue;
1058
1059 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: "
1060 << *MaybeDead);
1061
1062 MaybeDead->eraseFromParent();
1063 Changed = true;
1064 ++NumDeletes;
1065 }
1066 }
1067
1068 // Any previous copy definition or reading the Defs is no longer available.
1069 for (MCRegister Reg : Defs)
1070 Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
1071
1072 if (CopyOperands) {
1073 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
1074 if (!TRI->regsOverlap(Dst, Src)) {
1075 Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
1076 }
1077 }
1078 }
1079
1080 bool TracksLiveness = MRI->tracksLiveness();
1081
1082 // If liveness is tracked, we can use the live-in lists to know which
1083 // copies aren't dead.
1084 if (TracksLiveness)
1085 readSuccessorLiveIns(MBB);
1086
1087 // If MBB doesn't have succesor, delete copies whose defs are not used.
1088 // If MBB does have successors, we can only delete copies if we are able to
1089 // use liveness information from successors to confirm they are really dead.
1090 if (MBB.succ_empty() || TracksLiveness) {
1091 for (MachineInstr *MaybeDead : MaybeDeadCopies) {
1092 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
1093 MaybeDead->dump());
1094
1095 DestSourcePair CopyOperands =
1096 *isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
1097
1098 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
1099 assert(!isNeverRedundant(*MaybeDead) && !isNeverRedundant(Dst));
1100
1101 // Update matching debug values, if any.
1102 const auto &DbgUsers = CopyDbgUsers[MaybeDead];
1103 SmallVector<MachineInstr *> MaybeDeadDbgUsers(DbgUsers.begin(),
1104 DbgUsers.end());
1105 MRI->updateDbgUsersToReg(Dst, Src, MaybeDeadDbgUsers);
1106
1107 MaybeDead->eraseFromParent();
1108 Changed = true;
1109 ++NumDeletes;
1110 }
1111 }
1112
1113 MaybeDeadCopies.clear();
1114 CopyDbgUsers.clear();
1115 Tracker.clear();
1116}
1117
1118void MachineCopyPropagation::propagateDefs(MachineInstr &MI) {
1119 if (!Tracker.hasAnyCopies())
1120 return;
1121
1122 for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx != OpEnd;
1123 ++OpIdx) {
1124 MachineOperand &MODef = MI.getOperand(OpIdx);
1125
1126 if (!MODef.isReg() || MODef.isUse())
1127 continue;
1128
1129 // Ignore non-trivial cases.
1130 if (MODef.isTied() || MODef.isUndef() || MODef.isImplicit())
1131 continue;
1132
1133 if (!MODef.getReg())
1134 continue;
1135
1136 // We only handle if the register comes from a vreg.
1137 if (!MODef.isRenamable())
1138 continue;
1139
1140 MachineInstr *Copy = Tracker.findAvailBackwardCopy(
1141 MI, MODef.getReg().asMCReg(), *TRI, *TII, UseCopyInstr);
1142 if (!Copy)
1143 continue;
1144
1145 DestSourcePair CopyOperands = *isCopyInstr(*Copy, *TII, UseCopyInstr);
1146 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
1147
1148 if (MODef.getReg() != Src)
1149 continue;
1150
1151 if (!isBackwardPropagatableRegClassCopy(*Copy, MI, OpIdx))
1152 continue;
1153
1154 if (hasImplicitOverlap(MI, MODef))
1155 continue;
1156
1157 if (hasOverlappingMultipleDef(MI, MODef, Dst))
1158 continue;
1159
1160 if (!canUpdateSrcUsers(*Copy, *CopyOperands.Source))
1161 continue;
1162
1163 LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MODef.getReg(), TRI)
1164 << "\n with " << printReg(Dst, TRI) << "\n in "
1165 << MI << " from " << *Copy);
1166
1167 MODef.setReg(Dst);
1168 MODef.setIsRenamable(CopyOperands.Destination->isRenamable());
1169
1170 for (auto *SrcUser : Tracker.getSrcUsers(Src, *TRI)) {
1171 for (MachineOperand &MO : SrcUser->uses()) {
1172 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Src)
1173 continue;
1174 MO.setReg(Dst);
1175 MO.setIsRenamable(CopyOperands.Destination->isRenamable());
1176 }
1177 }
1178
1179 LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
1180 MaybeDeadCopies.insert(Copy);
1181 Changed = true;
1182 ++NumCopyBackwardPropagated;
1183 }
1184}
1185
1186void MachineCopyPropagation::backwardCopyPropagateBlock(
1187 MachineBasicBlock &MBB) {
1188 LLVM_DEBUG(dbgs() << "MCP: BackwardCopyPropagateBlock " << MBB.getName()
1189 << "\n");
1190
1191 for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(MBB))) {
1192 // Ignore non-trivial COPYs.
1193 std::optional<DestSourcePair> CopyOperands =
1194 isCopyInstr(MI, *TII, UseCopyInstr);
1195 if (CopyOperands && MI.getNumImplicitOperands() == 0) {
1196 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
1197
1198 if (!TRI->regsOverlap(Dst, Src)) {
1199 // Unlike forward cp, we don't invoke propagateDefs here,
1200 // just let forward cp do COPY-to-COPY propagation.
1201 if (isBackwardPropagatableCopy(MI, *CopyOperands)) {
1202 Tracker.invalidateRegister(Src, *TRI, *TII, UseCopyInstr);
1203 Tracker.invalidateRegister(Dst, *TRI, *TII, UseCopyInstr);
1204 Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
1205 continue;
1206 }
1207 }
1208 }
1209
1210 // Invalidate any earlyclobber regs first.
1211 for (const MachineOperand &MO : MI.operands())
1212 if (MO.isReg() && MO.isEarlyClobber()) {
1213 MCRegister Reg = MO.getReg().asMCReg();
1214 if (!Reg)
1215 continue;
1216 Tracker.invalidateRegister(Reg, *TRI, *TII, UseCopyInstr);
1217 }
1218
1219 propagateDefs(MI);
1220 for (const MachineOperand &MO : MI.operands()) {
1221 if (!MO.isReg())
1222 continue;
1223
1224 if (!MO.getReg())
1225 continue;
1226
1227 if (MO.isDef())
1228 Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
1229 UseCopyInstr);
1230
1231 if (MO.readsReg()) {
1232 if (MO.isDebug()) {
1233 // Check if the register in the debug instruction is utilized
1234 // in a copy instruction, so we can update the debug info if the
1235 // register is changed.
1236 for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
1237 if (auto *Copy = Tracker.findCopyDefViaUnit(Unit, *TRI)) {
1238 CopyDbgUsers[Copy].insert(&MI);
1239 }
1240 }
1241 } else if (!Tracker.trackSrcUsers(MO.getReg().asMCReg(), MI, *TRI, *TII,
1242 UseCopyInstr)) {
1243 // If we can't track the source users, invalidate the register.
1244 Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
1245 UseCopyInstr);
1246 }
1247 }
1248 }
1249 }
1250
1251 for (auto *Copy : MaybeDeadCopies) {
1252 DestSourcePair CopyOperands = *isCopyInstr(*Copy, *TII, UseCopyInstr);
1253 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
1254 const auto &DbgUsers = CopyDbgUsers[Copy];
1255 SmallVector<MachineInstr *> MaybeDeadDbgUsers(DbgUsers.begin(),
1256 DbgUsers.end());
1257
1258 MRI->updateDbgUsersToReg(Src, Dst, MaybeDeadDbgUsers);
1259 Copy->eraseFromParent();
1260 ++NumDeletes;
1261 }
1262
1263 MaybeDeadCopies.clear();
1264 CopyDbgUsers.clear();
1265 Tracker.clear();
1266}
1267
1268[[maybe_unused]] static void printSpillReloadChain(
1271 MachineInstr *Leader) {
1272 auto &SC = SpillChain[Leader];
1273 auto &RC = ReloadChain[Leader];
1274 for (auto I = SC.rbegin(), E = SC.rend(); I != E; ++I)
1275 (*I)->dump();
1276 for (MachineInstr *MI : RC)
1277 MI->dump();
1278}
1279
1280// Remove spill-reload like copy chains. For example
1281// r0 = COPY r1
1282// r1 = COPY r2
1283// r2 = COPY r3
1284// r3 = COPY r4
1285// <def-use r4>
1286// r4 = COPY r3
1287// r3 = COPY r2
1288// r2 = COPY r1
1289// r1 = COPY r0
1290// will be folded into
1291// r0 = COPY r1
1292// r1 = COPY r4
1293// <def-use r4>
1294// r4 = COPY r1
1295// r1 = COPY r0
1296// TODO: Currently we don't track usage of r0 outside the chain, so we
1297// conservatively keep its value as it was before the rewrite.
1298//
1299// The algorithm is trying to keep
1300// property#1: No Dst of spill COPY in the chain is used or defined until the
1301// paired reload COPY in the chain uses the Dst.
1302//
1303// property#2: NO Source of COPY in the chain is used or defined until the next
1304// COPY in the chain defines the Source, except the innermost spill-reload
1305// pair.
1306//
1307// The algorithm is conducted by checking every COPY inside the MBB, assuming
1308// the COPY is a reload COPY, then try to find paired spill COPY by searching
1309// the COPY defines the Src of the reload COPY backward. If such pair is found,
1310// it either belongs to an existing chain or a new chain depends on
1311// last available COPY uses the Dst of the reload COPY.
1312// Implementation notes, we use CopyTracker::findLastDefCopy(Reg, ...) to find
1313// out last COPY that defines Reg; we use CopyTracker::findLastUseCopy(Reg, ...)
1314// to find out last COPY that uses Reg. When we are encountered with a Non-COPY
1315// instruction, we check registers in the operands of this instruction. If this
1316// Reg is defined by a COPY, we untrack this Reg via
1317// CopyTracker::clobberRegister(Reg, ...).
1318void MachineCopyPropagation::eliminateSpillageCopies(MachineBasicBlock &MBB) {
1319
1320 // Perform some cost modelling to ensure that only MBB's with more
1321 // than 6 copies are checked. To create a chain that can be optimised,
1322 // 6 copies are needed.
1323 unsigned CopyCount = 0;
1324 for (const MachineInstr &MI : MBB) {
1325 if (isCopyInstr(MI, *TII, UseCopyInstr) && ++CopyCount > 6)
1326 break;
1327 }
1328 if (CopyCount < 6)
1329 return;
1330
1331 // ChainLeader maps MI inside a spill-reload chain to its innermost reload COPY.
1332 // Thus we can track if a MI belongs to an existing spill-reload chain.
1333 DenseMap<MachineInstr *, MachineInstr *> ChainLeader;
1334 // SpillChain maps innermost reload COPY of a spill-reload chain to a sequence
1335 // of COPYs that forms spills of a spill-reload chain.
1336 // ReloadChain maps innermost reload COPY of a spill-reload chain to a
1337 // sequence of COPYs that forms reloads of a spill-reload chain.
1338 DenseMap<MachineInstr *, SmallVector<MachineInstr *>> SpillChain, ReloadChain;
1339 // If a COPY's Source has use or def until next COPY defines the Source,
1340 // we put the COPY in this set to keep property#2.
1341 DenseSet<const MachineInstr *> CopySourceInvalid;
1342
1343 auto TryFoldSpillageCopies =
1344 [&, this](const SmallVectorImpl<MachineInstr *> &SC,
1345 const SmallVectorImpl<MachineInstr *> &RC) {
1346 assert(SC.size() == RC.size() && "Spill-reload should be paired");
1347
1348 // We need at least 3 pairs of copies for the transformation to apply,
1349 // because the first outermost pair cannot be removed since we don't
1350 // recolor outside of the chain and that we need at least one temporary
1351 // spill slot to shorten the chain. If we only have a chain of two
1352 // pairs, we already have the shortest sequence this code can handle:
1353 // the outermost pair for the temporary spill slot, and the pair that
1354 // use that temporary spill slot for the other end of the chain.
1355 // TODO: We might be able to simplify to one spill-reload pair if collecting
1356 // more infomation about the outermost COPY.
1357 if (SC.size() <= 2)
1358 return;
1359
1360 // If violate property#2, we don't fold the chain.
1361 for (const MachineInstr *Spill : drop_begin(SC))
1362 if (CopySourceInvalid.count(Spill))
1363 return;
1364
1365 for (const MachineInstr *Reload : drop_end(RC))
1366 if (CopySourceInvalid.count(Reload))
1367 return;
1368
1369 auto CheckCopyConstraint = [this](Register Dst, Register Src) {
1370 return TRI->getCommonMinimalPhysRegClass(Dst, Src);
1371 };
1372
1373 auto UpdateReg = [](MachineInstr *MI, const MachineOperand *Old,
1374 const MachineOperand *New) {
1375 for (MachineOperand &MO : MI->operands()) {
1376 if (&MO == Old)
1377 MO.setReg(New->getReg());
1378 }
1379 };
1380
1381 DestSourcePair InnerMostSpillCopy =
1382 *isCopyInstr(*SC[0], *TII, UseCopyInstr);
1383 DestSourcePair OuterMostSpillCopy =
1384 *isCopyInstr(*SC.back(), *TII, UseCopyInstr);
1385 DestSourcePair InnerMostReloadCopy =
1386 *isCopyInstr(*RC[0], *TII, UseCopyInstr);
1387 DestSourcePair OuterMostReloadCopy =
1388 *isCopyInstr(*RC.back(), *TII, UseCopyInstr);
1389 if (!CheckCopyConstraint(getSrcMCReg(OuterMostSpillCopy),
1390 getSrcMCReg(InnerMostSpillCopy)) ||
1391 !CheckCopyConstraint(getDstMCReg(InnerMostReloadCopy),
1392 getDstMCReg(OuterMostReloadCopy)))
1393 return;
1394
1395 SpillageChainsLength += SC.size() + RC.size();
1396 NumSpillageChains += 1;
1397 UpdateReg(SC[0], InnerMostSpillCopy.Destination,
1398 OuterMostSpillCopy.Source);
1399 UpdateReg(RC[0], InnerMostReloadCopy.Source,
1400 OuterMostReloadCopy.Destination);
1401
1402 for (size_t I = 1; I < SC.size() - 1; ++I) {
1403 SC[I]->eraseFromParent();
1404 RC[I]->eraseFromParent();
1405 NumDeletes += 2;
1406 }
1407 };
1408
1409 auto GetFoldableCopy =
1410 [this](const MachineInstr &MaybeCopy) -> std::optional<DestSourcePair> {
1411 if (MaybeCopy.getNumImplicitOperands() > 0)
1412 return std::nullopt;
1413 std::optional<DestSourcePair> CopyOperands =
1414 isCopyInstr(MaybeCopy, *TII, UseCopyInstr);
1415 if (!CopyOperands)
1416 return std::nullopt;
1417 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
1418 if (Src && Dst && !TRI->regsOverlap(Src, Dst) &&
1419 CopyOperands->Source->isRenamable() &&
1420 CopyOperands->Destination->isRenamable())
1421 return CopyOperands;
1422
1423 return std::nullopt;
1424 };
1425
1426 auto IsSpillReloadPair = [&](const MachineInstr &Spill,
1427 const MachineInstr &Reload) {
1428 std::optional<DestSourcePair> FoldableSpillCopy = GetFoldableCopy(Spill);
1429 if (!FoldableSpillCopy)
1430 return false;
1431 std::optional<DestSourcePair> FoldableReloadCopy = GetFoldableCopy(Reload);
1432 if (!FoldableReloadCopy)
1433 return false;
1434 return FoldableSpillCopy->Source->getReg() ==
1435 FoldableReloadCopy->Destination->getReg() &&
1436 FoldableSpillCopy->Destination->getReg() ==
1437 FoldableReloadCopy->Source->getReg();
1438 };
1439
1440 auto IsChainedCopy = [&](const MachineInstr &Prev,
1441 const MachineInstr &Current) {
1442 std::optional<DestSourcePair> FoldablePrevCopy = GetFoldableCopy(Prev);
1443 if (!FoldablePrevCopy)
1444 return false;
1445 std::optional<DestSourcePair> FoldableCurrentCopy =
1446 GetFoldableCopy(Current);
1447 if (!FoldableCurrentCopy)
1448 return false;
1449 return FoldablePrevCopy->Source->getReg() ==
1450 FoldableCurrentCopy->Destination->getReg();
1451 };
1452
1453 for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
1454 std::optional<DestSourcePair> CopyOperands =
1455 isCopyInstr(MI, *TII, UseCopyInstr);
1456
1457 // Update track information via non-copy instruction.
1458 SmallSet<Register, 8> RegsToClobber;
1459 if (!CopyOperands) {
1460 for (const MachineOperand &MO : MI.operands()) {
1461 if (MO.isRegMask()) {
1462 BitVector &PreservedRegUnits = Tracker.getPreservedRegUnits(MO, *TRI);
1463 Tracker.clobberNonPreservedRegs(PreservedRegUnits, *TRI, *TII);
1464 continue;
1465 }
1466 if (!MO.isReg())
1467 continue;
1468 Register Reg = MO.getReg();
1469 if (!Reg)
1470 continue;
1471 MachineInstr *LastUseCopy =
1472 Tracker.findLastSeenUseInCopy(Reg.asMCReg(), *TRI);
1473 if (LastUseCopy) {
1474 LLVM_DEBUG(dbgs() << "MCP: Copy source of\n");
1475 LLVM_DEBUG(LastUseCopy->dump());
1476 LLVM_DEBUG(dbgs() << "might be invalidated by\n");
1477 LLVM_DEBUG(MI.dump());
1478 CopySourceInvalid.insert(LastUseCopy);
1479 }
1480 // Must be noted Tracker.clobberRegister(Reg, ...) removes tracking of
1481 // Reg, i.e, COPY that defines Reg is removed from the mapping as well
1482 // as marking COPYs that uses Reg unavailable.
1483 // We don't invoke CopyTracker::clobberRegister(Reg, ...) if Reg is not
1484 // defined by a previous COPY, since we don't want to make COPYs uses
1485 // Reg unavailable.
1486 if (Tracker.findLastSeenDefInCopy(MI, Reg.asMCReg(), *TRI, *TII,
1487 UseCopyInstr))
1488 // Thus we can keep the property#1.
1489 RegsToClobber.insert(Reg);
1490 }
1491 for (Register Reg : RegsToClobber) {
1492 Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
1493 LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Reg, TRI)
1494 << "\n");
1495 }
1496 continue;
1497 }
1498
1499 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
1500 // Check if we can find a pair spill-reload copy.
1501 LLVM_DEBUG(dbgs() << "MCP: Searching paired spill for reload: ");
1502 LLVM_DEBUG(MI.dump());
1503 MachineInstr *MaybeSpill =
1504 Tracker.findAvailCopy(MI, Src, *TRI, *TII, UseCopyInstr);
1505 bool MaybeSpillIsChained = ChainLeader.count(MaybeSpill);
1506 if (!MaybeSpillIsChained && MaybeSpill &&
1507 IsSpillReloadPair(*MaybeSpill, MI)) {
1508 // Check if we already have an existing chain. Now we have a
1509 // spill-reload pair.
1510 // L2: r2 = COPY r3
1511 // L5: r3 = COPY r2
1512 // Looking for a valid COPY before L5 which uses r3.
1513 // This can be serverial cases.
1514 // Case #1:
1515 // No COPY is found, which can be r3 is def-use between (L2, L5), we
1516 // create a new chain for L2 and L5.
1517 // Case #2:
1518 // L2: r2 = COPY r3
1519 // L5: r3 = COPY r2
1520 // Such COPY is found and is L2, we create a new chain for L2 and L5.
1521 // Case #3:
1522 // L2: r2 = COPY r3
1523 // L3: r1 = COPY r3
1524 // L5: r3 = COPY r2
1525 // we create a new chain for L2 and L5.
1526 // Case #4:
1527 // L2: r2 = COPY r3
1528 // L3: r1 = COPY r3
1529 // L4: r3 = COPY r1
1530 // L5: r3 = COPY r2
1531 // Such COPY won't be found since L4 defines r3. we create a new chain
1532 // for L2 and L5.
1533 // Case #5:
1534 // L2: r2 = COPY r3
1535 // L3: r3 = COPY r1
1536 // L4: r1 = COPY r3
1537 // L5: r3 = COPY r2
1538 // COPY is found and is L4 which belongs to an existing chain, we add
1539 // L2 and L5 to this chain.
1540 LLVM_DEBUG(dbgs() << "MCP: Found spill: ");
1541 LLVM_DEBUG(MaybeSpill->dump());
1542 MachineInstr *MaybePrevReload = Tracker.findLastSeenUseInCopy(Dst, *TRI);
1543 auto Leader = ChainLeader.find(MaybePrevReload);
1544 MachineInstr *L = nullptr;
1545 if (Leader == ChainLeader.end() ||
1546 (MaybePrevReload && !IsChainedCopy(*MaybePrevReload, MI))) {
1547 L = &MI;
1548 assert(!SpillChain.count(L) &&
1549 "SpillChain should not have contained newly found chain");
1550 } else {
1551 assert(MaybePrevReload &&
1552 "Found a valid leader through nullptr should not happend");
1553 L = Leader->second;
1554 assert(SpillChain[L].size() > 0 &&
1555 "Existing chain's length should be larger than zero");
1556 }
1557 assert(!ChainLeader.count(&MI) && !ChainLeader.count(MaybeSpill) &&
1558 "Newly found paired spill-reload should not belong to any chain "
1559 "at this point");
1560 ChainLeader.insert({MaybeSpill, L});
1561 ChainLeader.insert({&MI, L});
1562 SpillChain[L].push_back(MaybeSpill);
1563 ReloadChain[L].push_back(&MI);
1564 LLVM_DEBUG(dbgs() << "MCP: Chain " << L << " now is:\n");
1565 LLVM_DEBUG(printSpillReloadChain(SpillChain, ReloadChain, L));
1566 } else if (MaybeSpill && !MaybeSpillIsChained) {
1567 // MaybeSpill is unable to pair with MI. That's to say adding MI makes
1568 // the chain invalid.
1569 // The COPY defines Src is no longer considered as a candidate of a
1570 // valid chain. Since we expect the Dst of a spill copy isn't used by
1571 // any COPY instruction until a reload copy. For example:
1572 // L1: r1 = COPY r2
1573 // L2: r3 = COPY r1
1574 // If we later have
1575 // L1: r1 = COPY r2
1576 // L2: r3 = COPY r1
1577 // L3: r2 = COPY r1
1578 // L1 and L3 can't be a valid spill-reload pair.
1579 // Thus we keep the property#1.
1580 LLVM_DEBUG(dbgs() << "MCP: Not paired spill-reload:\n");
1581 LLVM_DEBUG(MaybeSpill->dump());
1582 LLVM_DEBUG(MI.dump());
1583 Tracker.clobberRegister(Src, *TRI, *TII, UseCopyInstr);
1584 LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Src, TRI)
1585 << "\n");
1586 }
1587 Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
1588 }
1589
1590 for (auto I = SpillChain.begin(), E = SpillChain.end(); I != E; ++I) {
1591 auto &SC = I->second;
1592 assert(ReloadChain.count(I->first) &&
1593 "Reload chain of the same leader should exist");
1594 auto &RC = ReloadChain[I->first];
1595 TryFoldSpillageCopies(SC, RC);
1596 }
1597
1598 MaybeDeadCopies.clear();
1599 CopyDbgUsers.clear();
1600 Tracker.clear();
1601}
1602
1603bool MachineCopyPropagationLegacy::runOnMachineFunction(MachineFunction &MF) {
1604 if (skipFunction(MF.getFunction()))
1605 return false;
1606
1607 return MachineCopyPropagation(UseCopyInstr).run(MF);
1608}
1609
1610PreservedAnalyses
1613 MFPropsModifier _(*this, MF);
1614 if (!MachineCopyPropagation(UseCopyInstr).run(MF))
1615 return PreservedAnalyses::all();
1617 PA.preserveSet<CFGAnalyses>();
1618 return PA;
1619}
1620
1621bool MachineCopyPropagation::run(MachineFunction &MF) {
1622 bool IsSpillageCopyElimEnabled = false;
1625 IsSpillageCopyElimEnabled =
1627 break;
1629 IsSpillageCopyElimEnabled = true;
1630 break;
1632 IsSpillageCopyElimEnabled = false;
1633 break;
1634 }
1635
1636 Changed = false;
1637
1639 TII = MF.getSubtarget().getInstrInfo();
1640 MRI = &MF.getRegInfo();
1641
1642 for (MachineBasicBlock &MBB : MF) {
1643 if (IsSpillageCopyElimEnabled)
1644 eliminateSpillageCopies(MBB);
1645 backwardCopyPropagateBlock(MBB);
1646 forwardCopyPropagateBlock(MBB);
1647 }
1648
1649 return Changed;
1650}
1651
1652MachineFunctionPass *
1653llvm::createMachineCopyPropagationPass(bool UseCopyInstr = false) {
1654 return new MachineCopyPropagationLegacy(UseCopyInstr);
1655}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file defines the DenseMap class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
static cl::opt< cl::boolOrDefault > EnableSpillageCopyElimination("enable-spill-copy-elim", cl::Hidden)
static void printSpillReloadChain(DenseMap< MachineInstr *, SmallVector< MachineInstr * > > &SpillChain, DenseMap< MachineInstr *, SmallVector< MachineInstr * > > &ReloadChain, MachineInstr *Leader)
static bool isNopCopy(const MachineInstr &PreviousCopy, MCRegister Src, MCRegister Dst, const TargetRegisterInfo *TRI, const TargetInstrInfo *TII, bool UseCopyInstr)
Return true if PreviousCopy did copy register Src to register Dst.
static cl::opt< bool > MCPUseCopyInstr("mcp-use-is-copy-instr", cl::init(false), cl::Hidden)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
MachineInstr unsigned OpIdx
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:355
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static bool shouldExecute(CounterInfo &Counter)
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
iterator begin()
Definition DenseMap.h:137
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:219
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
An RAII based helper class to modify MachineFunctionProperties when running pass.
iterator_range< succ_iterator > successors()
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
LLVM_ABI void dump() const
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
LLVM_ABI const TargetRegisterClass * getRegClassConstraint(unsigned OpIdx, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
Compute the static register class constraint for operand OpIdx.
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
LLVM_ABI void setIsRenamable(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
LLVM_ABI bool isRenamable() const
isRenamable - Returns true if this register may be renamed, i.e.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
LLVM_ABI void updateDbgUsersToReg(MCRegister OldReg, MCRegister NewReg, ArrayRef< MachineInstr * > Users) const
updateDbgUsersToReg - Update a collection of debug instructions to refer to the designated register.
LLVM_ABI bool isConstantPhysReg(MCRegister PhysReg) const
Returns true if PhysReg is unallocatable and constant throughout the function.
void dump() const
Definition Pass.cpp:146
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
void insert_range(Range &&R)
Definition SmallSet.h:196
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual bool enableSpillageCopyElimination() const
Enable spillage copy elimination in MachineCopyPropagation pass.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
reverse_self_iterator getReverseIterator()
Definition ilist_node.h:126
self_iterator getIterator()
Definition ilist_node.h:123
Changed
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
LLVM_ABI Value * readRegister(IRBuilder<> &IRB, StringRef Name)
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:322
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI MachineFunctionPass * createMachineCopyPropagationPass(bool UseCopyInstr)
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI char & MachineCopyPropagationID
MachineCopyPropagation - This pass performs copy propagation on machine instructions.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
const MachineOperand * Source
const MachineOperand * Destination