81#define DEBUG_TYPE "machine-cp"
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");
89 "Controls which register COPYs are forwarded");
96 "MachineCopyPropagation should be run after register allocation!");
104 return asPhysMCReg(DSP.
Source);
106std::pair<MCRegister, MCRegister> getDstSrcMCRegs(
const DestSourcePair &DSP) {
107 return {getDstMCReg(DSP), getSrcMCReg(DSP)};
114 return TII.isCopyInstr(
MI);
124 MachineInstr *MI =
nullptr;
125 MachineInstr *LastSeenUseInCopy =
nullptr;
126 SmallPtrSet<MachineInstr *, 4> SrcUsers;
131 DenseMap<MCRegUnit, CopyInfo> Copies;
136 DenseMap<const uint32_t *, BitVector> RegMaskToPreservedRegUnits;
140 BitVector &getPreservedRegUnits(
const MachineOperand &RegMaskOp,
141 const TargetRegisterInfo &
TRI) {
142 const uint32_t *RegMask = RegMaskOp.
getRegMask();
143 auto [It,
Inserted] = RegMaskToPreservedRegUnits.try_emplace(RegMask);
146 BitVector &PreservedRegUnits = It->second;
148 PreservedRegUnits.
resize(
TRI.getNumRegUnits());
149 for (
unsigned SafeReg = 0,
E =
TRI.getNumRegs(); SafeReg <
E; ++SafeReg)
151 for (MCRegUnit SafeUnit :
TRI.regunits(SafeReg))
152 PreservedRegUnits.
set(
static_cast<unsigned>(SafeUnit));
154 return PreservedRegUnits;
160 const TargetRegisterInfo &
TRI) {
161 for (MCRegister
Reg : Regs) {
163 for (MCRegUnit Unit :
TRI.regunits(
Reg)) {
164 auto CI = Copies.find(Unit);
165 if (CI != Copies.end())
166 CI->second.Avail =
false;
172 void invalidateRegister(MCRegister
Reg,
const TargetRegisterInfo &
TRI,
173 const TargetInstrInfo &
TII,
bool UseCopyInstr) {
183 SmallSet<MCRegUnit, 8> RegUnitsToInvalidate;
184 auto InvalidateCopy = [&](MachineInstr *
MI) {
185 DestSourcePair CopyOperands = *isCopyInstr(*
MI,
TII, UseCopyInstr);
186 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
187 auto DstUnits =
TRI.regunits(Dst);
188 auto SrcUnits =
TRI.regunits(Src);
193 for (MCRegUnit Unit :
TRI.regunits(
Reg)) {
194 auto I = Copies.find(Unit);
195 if (
I != Copies.end()) {
196 if (MachineInstr *
MI =
I->second.MI)
198 if (MachineInstr *
MI =
I->second.LastSeenUseInCopy)
202 for (MCRegUnit Unit : RegUnitsToInvalidate)
207 void clobberRegUnit(MCRegUnit Unit,
const TargetRegisterInfo &
TRI,
208 const TargetInstrInfo &
TII,
bool UseCopyInstr) {
209 auto I = Copies.find(Unit);
210 if (
I != Copies.end()) {
213 markRegsUnavailable(
I->second.DefRegs,
TRI);
216 if (MachineInstr *
MI =
I->second.MI) {
217 DestSourcePair CopyOperands = *isCopyInstr(*
MI,
TII, UseCopyInstr);
218 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
220 markRegsUnavailable(Dst,
TRI);
234 for (MCRegUnit SrcUnit :
TRI.regunits(Src)) {
235 auto SrcCopy = Copies.find(SrcUnit);
236 if (SrcCopy != Copies.end() && SrcCopy->second.LastSeenUseInCopy) {
240 for (
auto Itr = SrcCopy->second.DefRegs.begin();
241 Itr != SrcCopy->second.DefRegs.end(); Itr++) {
243 SrcCopy->second.DefRegs.erase(Itr);
249 if (SrcCopy->second.DefRegs.empty() && !SrcCopy->second.MI) {
250 Copies.erase(SrcCopy);
264 void clobberRegister(MCRegister
Reg,
const TargetRegisterInfo &
TRI,
265 const TargetInstrInfo &
TII,
bool UseCopyInstr) {
271 for (MCRegUnit Unit :
TRI.regunits(
Reg)) {
272 clobberRegUnit(Unit,
TRI,
TII, UseCopyInstr);
279 bool trackSrcUsers(MCRegister
Reg, MachineInstr &
MI,
280 const TargetRegisterInfo &
TRI,
const TargetInstrInfo &
TII,
282 MCRegUnit RU = *
TRI.regunits(
Reg).begin();
283 MachineInstr *AvailCopy = findCopyDefViaUnit(RU,
TRI);
287 DestSourcePair CopyOperands = *isCopyInstr(*AvailCopy,
TII, UseCopyInstr);
288 MCRegister Src = getSrcMCReg(CopyOperands);
294 auto I = Copies.find(RU);
295 if (
I == Copies.end())
298 I->second.SrcUsers.insert(&
MI);
303 SmallPtrSet<MachineInstr *, 4> getSrcUsers(MCRegister
Reg,
304 const TargetRegisterInfo &
TRI) {
305 MCRegUnit RU = *
TRI.regunits(
Reg).begin();
306 auto I = Copies.find(RU);
307 if (
I == Copies.end())
309 return I->second.SrcUsers;
313 void trackCopy(MachineInstr *
MI,
const TargetRegisterInfo &
TRI,
314 const TargetInstrInfo &
TII,
bool UseCopyInstr) {
315 DestSourcePair CopyOperands = *isCopyInstr(*
MI,
TII, UseCopyInstr);
316 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
319 for (MCRegUnit Unit :
TRI.regunits(Dst))
320 Copies[
Unit] = {
MI,
nullptr, {}, {},
true};
324 for (MCRegUnit Unit :
TRI.regunits(Src)) {
327 Copy.DefRegs.push_back(Dst);
328 Copy.LastSeenUseInCopy =
MI;
332 bool hasAnyCopies() {
333 return !Copies.empty();
336 MachineInstr *findCopyForUnit(MCRegUnit RegUnit,
337 const TargetRegisterInfo &
TRI,
338 bool MustBeAvailable =
false) {
339 auto CI = Copies.find(RegUnit);
340 if (CI == Copies.end())
342 if (MustBeAvailable && !CI->second.Avail)
344 return CI->second.MI;
347 MachineInstr *findCopyDefViaUnit(MCRegUnit RegUnit,
348 const TargetRegisterInfo &
TRI) {
349 auto CI = Copies.find(RegUnit);
350 if (CI == Copies.end())
352 if (CI->second.DefRegs.size() != 1)
354 MCRegUnit RU = *
TRI.regunits(CI->second.DefRegs[0]).begin();
355 return findCopyForUnit(RU,
TRI,
true);
358 MachineInstr *findAvailBackwardCopy(MachineInstr &
I, MCRegister
Reg,
359 const TargetRegisterInfo &
TRI,
360 const TargetInstrInfo &
TII,
362 MCRegUnit RU = *
TRI.regunits(
Reg).begin();
363 MachineInstr *AvailCopy = findCopyDefViaUnit(RU,
TRI);
368 DestSourcePair CopyOperands = *isCopyInstr(*AvailCopy,
TII, UseCopyInstr);
369 auto [AvailDst, AvailSrc] = getDstSrcMCRegs(CopyOperands);
370 if (!
TRI.isSubRegisterEq(AvailSrc,
Reg))
373 for (
const MachineInstr &
MI :
375 for (
const MachineOperand &MO :
MI.operands())
378 if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDst))
384 MachineInstr *findAvailCopy(MachineInstr &DestCopy, MCRegister
Reg,
385 const TargetRegisterInfo &
TRI,
386 const TargetInstrInfo &
TII,
bool UseCopyInstr) {
389 MCRegUnit RU = *
TRI.regunits(
Reg).begin();
390 MachineInstr *AvailCopy =
391 findCopyForUnit(RU,
TRI,
true);
396 DestSourcePair CopyOperands = *isCopyInstr(*AvailCopy,
TII, UseCopyInstr);
397 auto [AvailDst, AvailSrc] = getDstSrcMCRegs(CopyOperands);
398 if (!
TRI.isSubRegisterEq(AvailDst,
Reg))
403 for (
const MachineInstr &
MI :
405 for (
const MachineOperand &MO :
MI.operands())
407 if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDst))
414 MachineInstr *findLastSeenDefInCopy(
const MachineInstr &Current,
416 const TargetRegisterInfo &
TRI,
417 const TargetInstrInfo &
TII,
419 MCRegUnit RU = *
TRI.regunits(
Reg).begin();
420 auto CI = Copies.find(RU);
421 if (CI == Copies.end() || !CI->second.Avail)
424 MachineInstr *DefCopy = CI->second.MI;
425 DestSourcePair CopyOperands = *isCopyInstr(*DefCopy,
TII, UseCopyInstr);
426 MCRegister Dst = getDstMCReg(CopyOperands);
427 if (!
TRI.isSubRegisterEq(Dst,
Reg))
433 void clobberNonPreservedRegs(
const BitVector &PreservedRegUnits,
434 const TargetRegisterInfo &
TRI,
435 const TargetInstrInfo &
TII) {
437 for (
auto &[Unit,
_] : Copies)
438 if (!PreservedRegUnits.
test(
static_cast<unsigned>(Unit)))
441 for (MCRegUnit Unit : UnitsToClobber) {
446 auto RegUnitInfo = Copies.find(Unit);
447 if (RegUnitInfo == Copies.end())
450 for (MCRegister DstReg : RegUnitInfo->second.DefRegs) {
451 for (MCRegUnit DstUnit :
TRI.regunits(DstReg)) {
452 if (!PreservedRegUnits.
test(
static_cast<unsigned>(DstUnit))) {
453 if (
auto CI = Copies.find(DstUnit); CI != Copies.end()) {
454 CI->second.Avail =
false;
459 Copies.erase(RegUnitInfo);
464 MachineInstr *findLastSeenUseInCopy(MCRegister
Reg,
465 const TargetRegisterInfo &
TRI) {
466 MCRegUnit RU = *
TRI.regunits(
Reg).begin();
467 auto CI = Copies.find(RU);
468 if (CI == Copies.end())
470 return CI->second.LastSeenUseInCopy;
478class MachineCopyPropagation {
479 const CodeGenOptions &Opts;
480 const TargetRegisterInfo *TRI =
nullptr;
481 const TargetInstrInfo *TII =
nullptr;
482 const MachineRegisterInfo *MRI =
nullptr;
488 MachineCopyPropagation(
const CodeGenOptions &Opts,
bool CopyInstr)
489 : Opts(Opts), UseCopyInstr(CopyInstr || Opts.mcp_use_is_copy_instr) {}
494 typedef enum { DebugUse =
false, RegularUse =
true } DebugType;
497 void readSuccessorLiveIns(
const MachineBasicBlock &
MBB);
498 void forwardCopyPropagateBlock(MachineBasicBlock &
MBB);
499 void backwardCopyPropagateBlock(MachineBasicBlock &
MBB);
500 void eliminateSpillageCopies(MachineBasicBlock &
MBB);
501 bool eraseIfRedundant(MachineInstr &Copy, MCRegister Dst, MCRegister Src);
502 void forwardUses(MachineInstr &
MI);
503 void propagateDefs(MachineInstr &
MI);
504 bool isForwardableRegClassCopy(
const MachineInstr &Copy,
505 const MachineInstr &UseI,
unsigned UseIdx);
506 bool isBackwardPropagatableRegClassCopy(
const MachineInstr &Copy,
507 const MachineInstr &UseI,
509 bool isBackwardPropagatableCopy(
const MachineInstr &Copy,
510 const DestSourcePair &CopyOperands);
513 bool isNeverRedundant(MCRegister CopyOperand) {
517 return MRI->isReserved(CopyOperand);
521 bool isNeverRedundant(
const MachineInstr &Copy) {
525 bool hasImplicitOverlap(
const MachineInstr &
MI,
const MachineOperand &Use);
526 bool hasOverlappingMultipleDef(
const MachineInstr &
MI,
527 const MachineOperand &MODef, MCRegister Def);
528 bool canUpdateSrcUsers(
const MachineInstr &Copy,
529 const MachineOperand &CopySrc);
532 SmallSetVector<MachineInstr *, 8> MaybeDeadCopies;
535 DenseMap<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> CopyDbgUsers;
539 bool Changed =
false;
548 MachineCopyPropagationLegacy(
bool UseCopyInstr =
false)
549 : MachineFunctionPass(ID), UseCopyInstr(UseCopyInstr) {}
551 void getAnalysisUsage(AnalysisUsage &AU)
const override {
558 MachineFunctionProperties getRequiredProperties()
const override {
559 return MachineFunctionProperties().setNoVRegs();
565char MachineCopyPropagationLegacy::ID = 0;
570 "Machine Copy Propagation Pass",
false,
false)
577 for (MCRegUnit Unit :
TRI->regunits(
Reg)) {
578 if (MachineInstr *Copy = Tracker.findCopyForUnit(Unit, *TRI)) {
579 if (DT == RegularUse) {
580 LLVM_DEBUG(dbgs() <<
"MCP: Copy is used - not dead: "; Copy->dump());
581 MaybeDeadCopies.remove(Copy);
583 CopyDbgUsers[Copy].insert(&Reader);
589void MachineCopyPropagation::readSuccessorLiveIns(
591 if (MaybeDeadCopies.empty())
596 for (
const auto &LI : Succ->liveins()) {
597 for (MCRegUnitMaskIterator
U(LI.PhysReg,
TRI);
U.isValid(); ++U) {
599 if ((Mask & LI.LaneMask).any()) {
600 if (MachineInstr *Copy = Tracker.findCopyForUnit(Unit, *
TRI))
601 MaybeDeadCopies.remove(Copy);
619 auto [PreviousDst, PreviousSrc] = getDstSrcMCRegs(CopyOperands);
620 if (Src == PreviousSrc && Dst == PreviousDst)
622 if (!
TRI->isSubRegister(PreviousSrc, Src))
624 unsigned SubIdx =
TRI->getSubRegIndex(PreviousSrc, Src);
625 return SubIdx ==
TRI->getSubRegIndex(PreviousDst, Dst);
631bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy,
632 MCRegister Dst, MCRegister Src) {
633 if (isNeverRedundant(Copy) || isNeverRedundant(Src) || isNeverRedundant(Dst))
637 MachineInstr *PrevCopy =
638 Tracker.findAvailCopy(Copy, Dst, *
TRI, *
TII, UseCopyInstr);
642 DestSourcePair PrevCopyOperands = *isCopyInstr(*PrevCopy, *
TII, UseCopyInstr);
653 DestSourcePair CopyOperands = *isCopyInstr(Copy, *
TII, UseCopyInstr);
655 MCRegister CopyDst = getDstMCReg(CopyOperands);
656 assert(CopyDst == Src || CopyDst == Dst);
657 for (MachineInstr &
MI :
659 MI.clearRegisterKills(CopyDst,
TRI);
667 Copy.eraseFromParent();
673bool MachineCopyPropagation::isBackwardPropagatableRegClassCopy(
674 const MachineInstr &Copy,
const MachineInstr &UseI,
unsigned UseIdx) {
675 DestSourcePair CopyOperands = *isCopyInstr(Copy, *
TII, UseCopyInstr);
676 MCRegister Dst = getDstMCReg(CopyOperands);
680 return URC->contains(Dst);
687bool MachineCopyPropagation::isBackwardPropagatableCopy(
688 const MachineInstr &Copy,
const DestSourcePair &CopyOperands) {
689 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
694 if (isNeverRedundant(Copy) || isNeverRedundant(Dst) || isNeverRedundant(Src))
703bool MachineCopyPropagation::isForwardableRegClassCopy(
const MachineInstr &Copy,
704 const MachineInstr &UseI,
706 DestSourcePair CopyOperands = *isCopyInstr(Copy, *
TII, UseCopyInstr);
707 MCRegister CopySrc = getSrcMCReg(CopyOperands);
713 return URC->contains(CopySrc);
715 std::optional<DestSourcePair> UseICopyOperands =
716 isCopyInstr(UseI, *
TII, UseCopyInstr);
717 if (!UseICopyOperands)
740 MCRegister UseDst = getDstMCReg(*UseICopyOperands);
742 bool IsCrossClass =
false;
744 if (RC.contains(CopySrc) && RC.contains(UseDst)) {
746 if (
TRI->getCrossCopyRegClass(&RC) != &RC) {
758 MCRegister CopyDst = getDstMCReg(CopyOperands);
760 if (RC.contains(CopySrc) && RC.contains(CopyDst) &&
761 TRI->getCrossCopyRegClass(&RC) != &RC)
775bool MachineCopyPropagation::hasImplicitOverlap(
const MachineInstr &
MI,
776 const MachineOperand &Use) {
777 for (
const MachineOperand &MIUse :
MI.uses())
778 if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
779 MIUse.isUse() &&
TRI->regsOverlap(
Use.getReg(), MIUse.getReg()))
789bool MachineCopyPropagation::hasOverlappingMultipleDef(
790 const MachineInstr &
MI,
const MachineOperand &MODef, MCRegister Def) {
791 for (
const MachineOperand &MIDef :
MI.all_defs()) {
792 if ((&MIDef != &MODef) && MIDef.isReg() &&
793 TRI->regsOverlap(Def, MIDef.getReg()))
802bool MachineCopyPropagation::canUpdateSrcUsers(
const MachineInstr &Copy,
803 const MachineOperand &CopySrc) {
804 assert(CopySrc.
isReg() &&
"Expected a register operand");
805 for (
auto *SrcUser : Tracker.getSrcUsers(CopySrc.
getReg(), *
TRI)) {
806 if (hasImplicitOverlap(*SrcUser, CopySrc))
809 for (MachineOperand &MO : SrcUser->uses()) {
810 if (!MO.isReg() || !MO.isUse() || MO.getReg() != CopySrc.
getReg())
812 if (MO.isTied() || !MO.isRenamable() ||
813 !isBackwardPropagatableRegClassCopy(Copy, *SrcUser,
823void MachineCopyPropagation::forwardUses(MachineInstr &
MI) {
824 if (!Tracker.hasAnyCopies())
830 for (
unsigned OpIdx = 0, OpEnd =
MI.getNumOperands(); OpIdx < OpEnd;
832 MachineOperand &MOUse =
MI.getOperand(OpIdx);
852 *
TRI, *
TII, UseCopyInstr);
856 DestSourcePair CopyOperands = *isCopyInstr(*Copy, *
TII, UseCopyInstr);
857 auto [CopyDst, CopySrc] = getDstSrcMCRegs(CopyOperands);
858 const MachineOperand &CopySrcOperand = *CopyOperands.
Source;
860 MCRegister ForwardedReg = CopySrc;
863 if (MOUse.
getReg() != CopyDst) {
864 unsigned SubRegIdx =
TRI->getSubRegIndex(CopyDst, MOUse.
getReg());
866 "MI source is not a sub-register of Copy destination");
867 ForwardedReg =
TRI->getSubReg(CopySrc, SubRegIdx);
868 if (!ForwardedReg ||
TRI->isArtificial(ForwardedReg)) {
869 LLVM_DEBUG(
dbgs() <<
"MCP: Copy source does not have sub-register "
870 <<
TRI->getSubRegIndexName(SubRegIdx) <<
'\n');
879 if (!isForwardableRegClassCopy(*Copy,
MI, OpIdx))
882 if (hasImplicitOverlap(
MI, MOUse))
888 if (isCopyInstr(
MI, *
TII, UseCopyInstr) &&
889 MI.modifiesRegister(CopySrc,
TRI) &&
890 !
MI.definesRegister(CopySrc,
nullptr)) {
896 LLVM_DEBUG(
dbgs() <<
"MCP: Skipping forwarding due to debug counter:\n "
903 <<
"\n in " <<
MI <<
" from " << *Copy);
905 MOUse.
setReg(ForwardedReg);
914 for (MachineInstr &KMI :
916 KMI.clearRegisterKills(CopySrc,
TRI);
923void MachineCopyPropagation::forwardCopyPropagateBlock(MachineBasicBlock &
MBB) {
929 std::optional<DestSourcePair> CopyOperands =
930 isCopyInstr(
MI, *
TII, UseCopyInstr);
932 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
933 if (!
TRI->regsOverlap(Dst, Src)) {
949 if (eraseIfRedundant(
MI, Dst, Src) || eraseIfRedundant(
MI, Src, Dst))
955 for (
const MachineOperand &MO :
MI.operands())
956 if (MO.isReg() && MO.isEarlyClobber()) {
963 Tracker.clobberRegister(
Reg, *
TRI, *
TII, UseCopyInstr);
970 if (
TII->simplifyInstruction(
MI)) {
975 CopyOperands = isCopyInstr(
MI, *
TII, UseCopyInstr);
977 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
978 if (!
TRI->regsOverlap(Dst, Src)) {
981 if (!isNeverRedundant(
MI) && !isNeverRedundant(Dst))
982 MaybeDeadCopies.insert(&
MI);
987 const MachineOperand *RegMask =
nullptr;
988 for (
const MachineOperand &MO :
MI.operands()) {
998 "MachineCopyPropagation should be run after register allocation!");
1000 if (MO.isDef() && !MO.isEarlyClobber()) {
1006 }
else if (MO.readsReg()) {
1015 BitVector &PreservedRegUnits =
1016 Tracker.getPreservedRegUnits(*RegMask, *
TRI);
1019 for (SmallSetVector<MachineInstr *, 8>::iterator DI =
1020 MaybeDeadCopies.begin();
1021 DI != MaybeDeadCopies.end();) {
1022 MachineInstr *MaybeDead = *DI;
1023 std::optional<DestSourcePair> CopyOperands =
1024 isCopyInstr(*MaybeDead, *
TII, UseCopyInstr);
1025 MCRegister
Reg = CopyOperands->Destination->getReg().asMCReg();
1026 assert(!isNeverRedundant(*MaybeDead) && !isNeverRedundant(
Reg));
1035 bool MIRefedinCopyInfo =
false;
1036 for (MCRegUnit RegUnit :
TRI->regunits(
Reg)) {
1037 if (!PreservedRegUnits.
test(
static_cast<unsigned>(RegUnit)))
1038 Tracker.clobberRegUnit(RegUnit, *
TRI, *
TII, UseCopyInstr);
1040 if (MaybeDead == Tracker.findCopyForUnit(RegUnit, *
TRI)) {
1041 MIRefedinCopyInfo =
true;
1048 DI = MaybeDeadCopies.erase(DI);
1051 if (MIRefedinCopyInfo)
1054 LLVM_DEBUG(
dbgs() <<
"MCP: Removing copy due to regmask clobbering: "
1064 for (MCRegister
Reg : Defs)
1065 Tracker.clobberRegister(
Reg, *
TRI, *
TII, UseCopyInstr);
1068 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
1069 if (!
TRI->regsOverlap(Dst, Src)) {
1070 Tracker.trackCopy(&
MI, *
TRI, *
TII, UseCopyInstr);
1080 readSuccessorLiveIns(
MBB);
1086 for (MachineInstr *MaybeDead : MaybeDeadCopies) {
1087 LLVM_DEBUG(
dbgs() <<
"MCP: Removing copy due to no live-out succ: ";
1090 DestSourcePair CopyOperands =
1091 *isCopyInstr(*MaybeDead, *
TII, UseCopyInstr);
1093 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
1094 assert(!isNeverRedundant(*MaybeDead) && !isNeverRedundant(Dst));
1097 const auto &DbgUsers = CopyDbgUsers[MaybeDead];
1108 MaybeDeadCopies.clear();
1109 CopyDbgUsers.clear();
1113void MachineCopyPropagation::propagateDefs(MachineInstr &
MI) {
1114 if (!Tracker.hasAnyCopies())
1117 for (
unsigned OpIdx = 0, OpEnd =
MI.getNumOperands(); OpIdx != OpEnd;
1119 MachineOperand &MODef =
MI.getOperand(OpIdx);
1135 MachineInstr *
Copy = Tracker.findAvailBackwardCopy(
1140 DestSourcePair CopyOperands = *isCopyInstr(*Copy, *
TII, UseCopyInstr);
1141 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
1143 if (MODef.
getReg() != Src)
1146 if (!isBackwardPropagatableRegClassCopy(*Copy,
MI, OpIdx))
1149 if (hasImplicitOverlap(
MI, MODef))
1152 if (hasOverlappingMultipleDef(
MI, MODef, Dst))
1155 if (!canUpdateSrcUsers(*Copy, *CopyOperands.
Source))
1160 <<
MI <<
" from " << *Copy);
1165 for (
auto *SrcUser : Tracker.getSrcUsers(Src, *
TRI)) {
1166 for (MachineOperand &MO : SrcUser->uses()) {
1167 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Src)
1175 MaybeDeadCopies.insert(Copy);
1177 ++NumCopyBackwardPropagated;
1181void MachineCopyPropagation::backwardCopyPropagateBlock(
1182 MachineBasicBlock &
MBB) {
1188 std::optional<DestSourcePair> CopyOperands =
1189 isCopyInstr(
MI, *
TII, UseCopyInstr);
1190 if (CopyOperands &&
MI.getNumImplicitOperands() == 0) {
1191 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
1193 if (!
TRI->regsOverlap(Dst, Src)) {
1196 if (isBackwardPropagatableCopy(
MI, *CopyOperands)) {
1197 Tracker.invalidateRegister(Src, *
TRI, *
TII, UseCopyInstr);
1198 Tracker.invalidateRegister(Dst, *
TRI, *
TII, UseCopyInstr);
1199 Tracker.trackCopy(&
MI, *
TRI, *
TII, UseCopyInstr);
1206 for (
const MachineOperand &MO :
MI.operands())
1207 if (MO.isReg() && MO.isEarlyClobber()) {
1211 Tracker.invalidateRegister(
Reg, *
TRI, *
TII, UseCopyInstr);
1215 for (
const MachineOperand &MO :
MI.operands()) {
1223 Tracker.invalidateRegister(MO.getReg().asMCReg(), *
TRI, *
TII,
1226 if (MO.readsReg()) {
1231 for (MCRegUnit Unit :
TRI->regunits(MO.getReg().asMCReg())) {
1232 if (
auto *Copy = Tracker.findCopyDefViaUnit(Unit, *
TRI)) {
1233 CopyDbgUsers[
Copy].insert(&
MI);
1236 }
else if (!Tracker.trackSrcUsers(MO.getReg().asMCReg(),
MI, *
TRI, *
TII,
1239 Tracker.invalidateRegister(MO.getReg().asMCReg(), *
TRI, *
TII,
1246 for (
auto *Copy : MaybeDeadCopies) {
1247 DestSourcePair CopyOperands = *isCopyInstr(*Copy, *
TII, UseCopyInstr);
1248 auto [Dst, Src] = getDstSrcMCRegs(CopyOperands);
1249 const auto &DbgUsers = CopyDbgUsers[
Copy];
1254 Copy->eraseFromParent();
1258 MaybeDeadCopies.clear();
1259 CopyDbgUsers.clear();
1267 auto &SC = SpillChain[Leader];
1268 auto &RC = ReloadChain[Leader];
1269 for (
auto I = SC.rbegin(),
E = SC.rend();
I !=
E; ++
I)
1313void MachineCopyPropagation::eliminateSpillageCopies(MachineBasicBlock &
MBB) {
1318 unsigned CopyCount = 0;
1319 for (
const MachineInstr &
MI :
MBB) {
1320 if (isCopyInstr(
MI, *
TII, UseCopyInstr) && ++CopyCount > 6)
1328 DenseMap<MachineInstr *, MachineInstr *> ChainLeader;
1333 DenseMap<MachineInstr *, SmallVector<MachineInstr *>> SpillChain, ReloadChain;
1336 DenseSet<const MachineInstr *> CopySourceInvalid;
1338 auto TryFoldSpillageCopies =
1339 [&,
this](
const SmallVectorImpl<MachineInstr *> &SC,
1340 const SmallVectorImpl<MachineInstr *> &RC) {
1341 assert(SC.
size() == RC.size() &&
"Spill-reload should be paired");
1356 for (
const MachineInstr *Spill :
drop_begin(SC))
1357 if (CopySourceInvalid.
count(Spill))
1360 for (
const MachineInstr *Reload :
drop_end(RC))
1361 if (CopySourceInvalid.
count(Reload))
1365 return TRI->getCommonMinimalPhysRegClass(Dst, Src);
1368 auto UpdateReg = [](MachineInstr *
MI,
const MachineOperand *Old,
1369 const MachineOperand *
New) {
1370 for (MachineOperand &MO :
MI->operands()) {
1372 MO.setReg(
New->getReg());
1376 DestSourcePair InnerMostSpillCopy =
1377 *isCopyInstr(*SC[0], *
TII, UseCopyInstr);
1378 DestSourcePair OuterMostSpillCopy =
1379 *isCopyInstr(*SC.
back(), *
TII, UseCopyInstr);
1380 DestSourcePair InnerMostReloadCopy =
1381 *isCopyInstr(*RC[0], *
TII, UseCopyInstr);
1382 DestSourcePair OuterMostReloadCopy =
1383 *isCopyInstr(*RC.back(), *
TII, UseCopyInstr);
1384 if (!CheckCopyConstraint(getSrcMCReg(OuterMostSpillCopy),
1385 getSrcMCReg(InnerMostSpillCopy)) ||
1386 !CheckCopyConstraint(getDstMCReg(InnerMostReloadCopy),
1387 getDstMCReg(OuterMostReloadCopy)))
1390 SpillageChainsLength += SC.
size() + RC.size();
1391 NumSpillageChains += 1;
1393 OuterMostSpillCopy.
Source);
1394 UpdateReg(RC[0], InnerMostReloadCopy.
Source,
1397 for (
size_t I = 1;
I < SC.
size() - 1; ++
I) {
1398 SC[
I]->eraseFromParent();
1399 RC[
I]->eraseFromParent();
1404 auto GetFoldableCopy =
1405 [
this](
const MachineInstr &MaybeCopy) -> std::optional<DestSourcePair> {
1406 if (MaybeCopy.getNumImplicitOperands() > 0)
1407 return std::nullopt;
1408 std::optional<DestSourcePair> CopyOperands =
1409 isCopyInstr(MaybeCopy, *
TII, UseCopyInstr);
1411 return std::nullopt;
1412 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
1413 if (Src && Dst && !
TRI->regsOverlap(Src, Dst) &&
1414 CopyOperands->Source->isRenamable() &&
1415 CopyOperands->Destination->isRenamable())
1416 return CopyOperands;
1418 return std::nullopt;
1421 auto IsSpillReloadPair = [&](
const MachineInstr &
Spill,
1422 const MachineInstr &Reload) {
1423 std::optional<DestSourcePair> FoldableSpillCopy = GetFoldableCopy(Spill);
1424 if (!FoldableSpillCopy)
1426 std::optional<DestSourcePair> FoldableReloadCopy = GetFoldableCopy(Reload);
1427 if (!FoldableReloadCopy)
1429 return FoldableSpillCopy->Source->getReg() ==
1430 FoldableReloadCopy->Destination->getReg() &&
1431 FoldableSpillCopy->Destination->getReg() ==
1432 FoldableReloadCopy->Source->getReg();
1435 auto IsChainedCopy = [&](
const MachineInstr &Prev,
1436 const MachineInstr &Current) {
1437 std::optional<DestSourcePair> FoldablePrevCopy = GetFoldableCopy(Prev);
1438 if (!FoldablePrevCopy)
1440 std::optional<DestSourcePair> FoldableCurrentCopy =
1441 GetFoldableCopy(Current);
1442 if (!FoldableCurrentCopy)
1444 return FoldablePrevCopy->Source->getReg() ==
1445 FoldableCurrentCopy->Destination->getReg();
1449 std::optional<DestSourcePair> CopyOperands =
1450 isCopyInstr(
MI, *
TII, UseCopyInstr);
1453 SmallSet<Register, 8> RegsToClobber;
1454 if (!CopyOperands) {
1455 for (
const MachineOperand &MO :
MI.operands()) {
1456 if (MO.isRegMask()) {
1457 BitVector &PreservedRegUnits = Tracker.getPreservedRegUnits(MO, *
TRI);
1458 Tracker.clobberNonPreservedRegs(PreservedRegUnits, *
TRI, *
TII);
1466 MachineInstr *LastUseCopy =
1473 CopySourceInvalid.
insert(LastUseCopy);
1487 Tracker.clobberRegister(
Reg, *
TRI, *
TII, UseCopyInstr);
1494 auto [Dst, Src] = getDstSrcMCRegs(*CopyOperands);
1496 LLVM_DEBUG(
dbgs() <<
"MCP: Searching paired spill for reload: ");
1498 MachineInstr *MaybeSpill =
1499 Tracker.findAvailCopy(
MI, Src, *
TRI, *
TII, UseCopyInstr);
1500 bool MaybeSpillIsChained = ChainLeader.
count(MaybeSpill);
1501 if (!MaybeSpillIsChained && MaybeSpill &&
1502 IsSpillReloadPair(*MaybeSpill,
MI)) {
1537 MachineInstr *MaybePrevReload = Tracker.findLastSeenUseInCopy(Dst, *
TRI);
1538 auto Leader = ChainLeader.
find(MaybePrevReload);
1539 MachineInstr *
L =
nullptr;
1540 if (Leader == ChainLeader.
end() ||
1541 (MaybePrevReload && !IsChainedCopy(*MaybePrevReload,
MI))) {
1544 "SpillChain should not have contained newly found chain");
1546 assert(MaybePrevReload &&
1547 "Found a valid leader through nullptr should not happend");
1550 "Existing chain's length should be larger than zero");
1553 "Newly found paired spill-reload should not belong to any chain "
1555 ChainLeader.
insert({MaybeSpill,
L});
1557 SpillChain[
L].push_back(MaybeSpill);
1558 ReloadChain[
L].push_back(&
MI);
1561 }
else if (MaybeSpill && !MaybeSpillIsChained) {
1578 Tracker.clobberRegister(Src, *
TRI, *
TII, UseCopyInstr);
1582 Tracker.trackCopy(&
MI, *
TRI, *
TII, UseCopyInstr);
1585 for (
auto I = SpillChain.
begin(),
E = SpillChain.
end();
I !=
E; ++
I) {
1586 auto &SC =
I->second;
1588 "Reload chain of the same leader should exist");
1589 auto &RC = ReloadChain[
I->first];
1590 TryFoldSpillageCopies(SC, RC);
1593 MaybeDeadCopies.clear();
1594 CopyDbgUsers.clear();
1598bool MachineCopyPropagationLegacy::runOnMachineFunction(
MachineFunction &MF) {
1617 bool IsSpillageCopyElimEnabled =
1618 valueOr(Opts.mcp_spill_copy_elim,
1628 if (IsSpillageCopyElimEnabled)
1629 eliminateSpillageCopies(
MBB);
1630 backwardCopyPropagateBlock(
MBB);
1631 forwardCopyPropagateBlock(
MBB);
1637MachineFunctionPass *
1639 return new MachineCopyPropagationLegacy(UseCopyInstr);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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.
const HexagonInstrInfo * TII
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.
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
MachineRegisterInfo & MRI
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)
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
bool test(unsigned Idx) const
Returns true if bit Idx is set.
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
BitVector & set()
Set all bits in the bitvector.
Represents analyses that only rely on functions' control flow.
static bool shouldExecute(CounterInfo &Counter)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Wrapper class representing physical registers. Should be passed by value.
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.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Wrapper class representing virtual and physical registers.
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
void insert_range(Range &&R)
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
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)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
reverse_self_iterator getReverseIterator()
self_iterator getIterator()
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.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
LLVM_ABI Value * readRegister(IRBuilder<> &IRB, StringRef Name)
NodeAddr< UseNode * > Use
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.
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.
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...
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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.
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
constexpr bool valueOr(BoolOrDefault X, bool Default)
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.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
MCRegisterClass TargetRegisterClass
const MachineOperand * Source
const MachineOperand * Destination