34#define DEBUG_TYPE "si-pre-emit-peephole"
37 "Number of redundant mode register writes removed");
43struct ModeFieldState {
44 std::optional<int64_t>
Value;
45 std::optional<int64_t> ValueBeforePendingWrite;
48 bool isTracked()
const {
return PendingWrite ||
Value; }
51class SIPreEmitPeephole {
53 const SIInstrInfo *TII =
nullptr;
54 const SIRegisterInfo *TRI =
nullptr;
55 MachineLoopInfo *MLI =
nullptr;
57 std::optional<int64_t> matchVccMask(MachineInstr &
A,
Register &SReg,
59 bool optimizeVccBranch(MachineInstr &
MI)
const;
60 void updateMLIBeforeRemovingEdge(MachineBasicBlock *From,
61 MachineBasicBlock *To)
const;
62 bool optimizeSetGPR(MachineInstr &
First, MachineInstr &
MI)
const;
63 bool getBlockDestinations(MachineBasicBlock &SrcMBB,
64 MachineBasicBlock *&TrueMBB,
65 MachineBasicBlock *&FalseMBB,
66 SmallVectorImpl<MachineOperand> &
Cond);
67 bool hasPendingWMMACoexecutionHazard(
const MachineInstr &Branch)
const;
68 bool mustRetainExeczBranch(
const MachineInstr &Branch,
69 const MachineBasicBlock &From,
70 const MachineBasicBlock &To)
const;
71 bool removeExeczBranch(MachineInstr &
MI, MachineBasicBlock &SrcMBB);
72 bool removeRedundantModeWrites(MachineBasicBlock &SrcMBB)
const;
76 void collectUnpackingCandidates(MachineInstr &BeginMI,
77 SetVector<MachineInstr *> &InstrsToUnpack,
78 uint16_t NumMFMACycles);
86 bool canUnpackingClobberRegister(
const MachineInstr &
MI);
90 void performF32Unpacking(MachineInstr &
I);
92 uint32_t mapToUnpackedOpcode(MachineInstr &
I);
96 MachineInstrBuilder createUnpackedMI(MachineInstr &
I, uint32_t UnpackedOpcode,
100 void addOperandAndMods(MachineInstrBuilder &NewMI,
unsigned SrcMods,
101 bool IsHiBits,
const MachineOperand &SrcMO);
111 SIPreEmitPeepholeLegacy() : MachineFunctionPass(ID) {}
113 void getAnalysisUsage(AnalysisUsage &AU)
const override {
120 auto *MLIWrapper = getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
121 MachineLoopInfo *MLI = MLIWrapper ? &MLIWrapper->getLI() :
nullptr;
122 return SIPreEmitPeephole().run(MF, MLI);
129 "SI peephole optimizations",
false,
false)
131char SIPreEmitPeepholeLegacy::ID = 0;
135void SIPreEmitPeephole::updateMLIBeforeRemovingEdge(
146 unsigned BackEdgeCount = 0;
148 if (Loop->contains(Pred))
152 if (BackEdgeCount > 1)
159 if (MLI->getLoopFor(BB) == Loop)
160 MLI->changeLoopFor(BB, ParentLoop);
165 MachineLoop *Child = Loop->removeChildLoop(std::prev(Loop->end()));
167 ParentLoop->addChildLoop(Child);
169 MLI->addTopLevelLoop(Child);
183std::optional<int64_t> SIPreEmitPeephole::matchVccMask(
MachineInstr &
A,
186 const GCNSubtarget &
ST =
A.getMF()->getSubtarget<GCNSubtarget>();
187 const bool IsWave32 =
ST.isWave32();
188 const unsigned ExecReg = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
189 const unsigned AndN2 = IsWave32 ? AMDGPU::S_ANDN2_B32 : AMDGPU::S_ANDN2_B64;
190 const unsigned Mov = IsWave32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
192 const unsigned Opc =
A.getOpcode();
193 if (
Opc == Mov ||
Opc == AMDGPU::COPY) {
194 const MachineOperand &Src =
A.getOperand(1);
195 if (Src.isImm() && Src.getImm() == 0)
197 if (Src.isReg() && Src.getReg() == ExecReg)
202 MachineOperand &Op1 =
A.getOperand(1);
203 MachineOperand &Op2 =
A.getOperand(2);
205 Op2.
getReg() == ExecReg) {
206 TII->commuteInstruction(
A);
214 int64_t MaskValue = 0;
220 bool ReadsSreg =
false;
221 for (;
M !=
E; ++
M) {
222 if (
M->definesRegister(SReg,
TRI))
224 if (
M->modifiesRegister(SReg,
TRI))
226 ReadsSreg |=
M->readsRegister(SReg,
TRI);
231 if (!
M->isMoveImmediate() || !
M->getOperand(1).isImm() ||
232 (
M->getOperand(1).getImm() != -1 &&
M->getOperand(1).getImm() != 0))
234 MaskValue =
M->getOperand(1).getImm();
237 if (!ReadsSreg && Op2.
isKill()) {
238 A.getOperand(2).ChangeToImmediate(MaskValue);
239 M->eraseFromParent();
241 }
else if (Op2.
isImm()) {
248 assert(MaskValue == 0 || MaskValue == -1);
250 MaskValue = ~MaskValue;
254bool SIPreEmitPeephole::optimizeVccBranch(MachineInstr &
MI)
const {
264 const bool IsWave32 =
ST.isWave32();
265 const unsigned CondReg =
TRI->getVCC();
266 const unsigned ExecReg = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
267 const unsigned And = IsWave32 ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
268 const unsigned AndN2 = IsWave32 ? AMDGPU::S_ANDN2_B32 : AMDGPU::S_ANDN2_B64;
269 const unsigned Mov = IsWave32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
273 bool ReadsCond =
false;
274 unsigned Threshold = 5;
275 for (++
A;
A !=
E; ++
A) {
278 if (
A->modifiesRegister(ExecReg,
TRI))
280 if (
A->modifiesRegister(CondReg,
TRI)) {
281 unsigned Opc =
A->getOpcode();
282 if (!
A->definesRegister(CondReg,
TRI) ||
287 ReadsCond |=
A->readsRegister(CondReg,
TRI);
293 std::optional<int64_t> Match = matchVccMask(*
A, SReg,
Changed);
296 int64_t MaskValue = *Match;
298 const bool IsAnd =
A->getOpcode() ==
And ||
A->getOpcode() == AndN2;
300 (!IsAnd ||
A->registerDefIsDead(AMDGPU::SCC,
nullptr))) {
301 const bool KillsCond =
MI.killsRegister(CondReg,
TRI);
302 if (IsAnd && !KillsCond) {
304 if (MaskValue == 0) {
305 BuildMI(*
A->getParent(), *
A,
A->getDebugLoc(),
TII->get(Mov), CondReg)
308 BuildMI(*
A->getParent(), *
A,
A->getDebugLoc(),
TII->get(Mov), CondReg)
312 if (IsAnd || KillsCond)
313 A->eraseFromParent();
316 bool IsVCCZ =
MI.getOpcode() == AMDGPU::S_CBRANCH_VCCZ;
317 if (SReg == ExecReg) {
320 MI.eraseFromParent();
323 MI.setDesc(
TII->get(AMDGPU::S_BRANCH));
324 }
else if (IsVCCZ && MaskValue == 0) {
327 MachineBasicBlock *Parent =
MI.getParent();
328 SmallVector<MachineInstr *, 4>
ToRemove;
335 Found =
Term.isIdenticalTo(
MI);
338 assert(Found &&
"conditional branch is not terminator");
340 MachineOperand &Dst = BranchMI->getOperand(0);
341 assert(Dst.isMBB() &&
"destination is not basic block");
342 updateMLIBeforeRemovingEdge(Parent, Dst.getMBB());
344 BranchMI->eraseFromParent();
348 updateMLIBeforeRemovingEdge(Parent, Succ);
353 MI.setDesc(
TII->get(AMDGPU::S_BRANCH));
354 }
else if (!IsVCCZ && MaskValue == 0) {
356 MachineOperand &Dst =
MI.getOperand(0);
357 assert(Dst.isMBB() &&
"destination is not basic block");
359 updateMLIBeforeRemovingEdge(Parent, Dst.getMBB());
361 MI.eraseFromParent();
363 }
else if (MaskValue == -1) {
366 TII->get(IsVCCZ ? AMDGPU::S_CBRANCH_EXECZ : AMDGPU::S_CBRANCH_EXECNZ));
369 MI.removeOperand(
MI.findRegisterUseOperandIdx(CondReg,
TRI,
false ));
375bool SIPreEmitPeephole::optimizeSetGPR(MachineInstr &
First,
376 MachineInstr &
MI)
const {
380 MachineOperand *
Idx =
TII->getNamedOperand(
MI, AMDGPU::OpName::src0);
382 SmallVector<MachineInstr *, 4>
ToRemove;
390 E =
MI.getIterator();
392 if (
I->isBundle() ||
I->isDebugInstr())
394 switch (
I->getOpcode()) {
395 case AMDGPU::S_SET_GPR_IDX_MODE:
397 case AMDGPU::S_SET_GPR_IDX_OFF:
402 if (
I->modifiesRegister(AMDGPU::M0,
TRI))
404 if (IdxReg &&
I->modifiesRegister(IdxReg,
TRI))
407 return MO.isReg() && TRI->isVectorRegister(MRI, MO.getReg());
411 if (!IdxOn || !(
I->getOpcode() == AMDGPU::V_MOV_B32_indirect_write ||
412 I->getOpcode() == AMDGPU::V_MOV_B32_indirect_read))
418 MI.eraseFromBundle();
420 RI->eraseFromBundle();
424bool SIPreEmitPeephole::getBlockDestinations(
425 MachineBasicBlock &SrcMBB, MachineBasicBlock *&TrueMBB,
426 MachineBasicBlock *&FalseMBB, SmallVectorImpl<MachineOperand> &
Cond) {
437class BranchWeightCostModel {
438 const SIInstrInfo &
TII;
439 const TargetSchedModel &SchedModel;
440 BranchProbability BranchProb;
441 static constexpr uint64_t BranchNotTakenCost = 1;
446 BranchWeightCostModel(
const SIInstrInfo &
TII,
const MachineInstr &Branch,
447 const MachineBasicBlock &Succ)
448 :
TII(
TII), SchedModel(
TII.getSchedModel()) {
449 const MachineBasicBlock &Head = *
Branch.getParent();
456 BranchTakenCost = SchedModel.computeInstrLatency(&Branch);
460 if (
TII.isWaitcnt(
MI.getOpcode()))
463 ThenCyclesCost += SchedModel.computeInstrLatency(&
MI);
475 return (Denominator - Numerator) * ThenCyclesCost <=
476 ((Denominator - Numerator) * BranchTakenCost +
477 Numerator * BranchNotTakenCost);
484bool SIPreEmitPeephole::hasPendingWMMACoexecutionHazard(
485 const MachineInstr &Branch)
const {
487 Branch.getMF()->getSubtarget<GCNSubtarget>());
494 for (;
I !=
E && VALUs < Window; ++
I) {
495 if (
I->isBundle() ||
I->isMetaInstruction())
497 if (
TII->isXDLWMMA(*
I))
505 const MachineBasicBlock *
MBB =
Branch.getParent();
513 DenseMap<const MachineBasicBlock *, unsigned> MinVALUsAtEnd;
518 while (!Worklist.
empty()) {
522 if (It->second <=
Count)
530 for (
const MachineBasicBlock *
Pred :
Block->predecessors())
536bool SIPreEmitPeephole::mustRetainExeczBranch(
537 const MachineInstr &Branch,
const MachineBasicBlock &From,
538 const MachineBasicBlock &To)
const {
540 BranchWeightCostModel CostModel{*
TII,
Branch, From};
541 bool HasVALU =
false;
544 const bool CheckWMMA =
545 MF->
getSubtarget<GCNSubtarget>().hasWMMACoexecutionHazards();
548 const MachineBasicBlock &
MBB = *
MBBI;
550 for (
const MachineInstr &
MI :
MBB) {
554 if (
MI.isConditionalBranch())
557 if (
MI.isUnconditionalBranch() &&
561 if (
MI.isMetaInstruction())
564 if (
TII->hasUnwantedEffectsWhenEXECEmpty(
MI))
569 if (CheckWMMA &&
TII->isXDLWMMA(
MI))
572 if (!CostModel.isProfitable(
MI))
581 return CheckWMMA && HasVALU && hasPendingWMMACoexecutionHazard(Branch);
586bool SIPreEmitPeephole::removeExeczBranch(MachineInstr &
MI,
587 MachineBasicBlock &SrcMBB) {
589 if (!
TII->getSchedModel().hasInstrSchedModel())
592 MachineBasicBlock *TrueMBB =
nullptr;
593 MachineBasicBlock *FalseMBB =
nullptr;
596 if (!getBlockDestinations(SrcMBB, TrueMBB, FalseMBB,
Cond))
604 if (mustRetainExeczBranch(
MI, *FalseMBB, *TrueMBB))
608 MI.eraseFromParent();
625bool SIPreEmitPeephole::removeRedundantModeWrites(
626 MachineBasicBlock &SrcMBB)
const {
628 ModeFieldState DenormMode;
629 ModeFieldState RoundMode;
632 if (
MI.isDebugInstr())
635 unsigned Opc =
MI.getOpcode();
636 if (
Opc == AMDGPU::S_DENORM_MODE ||
Opc == AMDGPU::S_ROUND_MODE) {
637 ModeFieldState &
Field =
638 Opc == AMDGPU::S_DENORM_MODE ? DenormMode : RoundMode;
639 int64_t NewValue =
MI.getOperand(0).getImm();
641 if (
Field.PendingWrite) {
643 << *
Field.PendingWrite);
644 Field.PendingWrite->eraseFromParent();
645 ++NumModeWritesRemoved;
647 Field.PendingWrite =
nullptr;
651 if (
Field.Value == NewValue) {
653 MI.eraseFromParent();
654 ++NumModeWritesRemoved;
661 Field.Value = NewValue;
666 if (!DenormMode.isTracked() && !RoundMode.isTracked())
670 if (
MI.isInlineAsm() ||
MI.modifiesRegister(AMDGPU::MODE,
TRI)) {
671 DenormMode = ModeFieldState();
672 RoundMode = ModeFieldState();
676 if (
MI.readsRegister(AMDGPU::MODE,
TRI) ||
MI.hasUnmodeledSideEffects()) {
677 DenormMode.PendingWrite =
nullptr;
678 RoundMode.PendingWrite =
nullptr;
684bool SIPreEmitPeephole::canUnpackingClobberRegister(
const MachineInstr &
MI) {
694 Register UnpackedDstReg =
TRI->getSubReg(DstReg, AMDGPU::sub0);
696 const MachineOperand *Src0MO =
TII->getNamedOperand(
MI, AMDGPU::OpName::src0);
697 if (Src0MO && Src0MO->
isReg()) {
700 TII->getNamedOperand(
MI, AMDGPU::OpName::src0_modifiers)->getImm();
702 ?
TRI->getSubReg(SrcReg0, AMDGPU::sub1)
703 :
TRI->getSubReg(SrcReg0, AMDGPU::sub0);
706 if (
TRI->regsOverlap(UnpackedDstReg, HiSrc0Reg))
710 const MachineOperand *Src1MO =
TII->getNamedOperand(
MI, AMDGPU::OpName::src1);
711 if (Src1MO && Src1MO->
isReg()) {
714 TII->getNamedOperand(
MI, AMDGPU::OpName::src1_modifiers)->getImm();
716 ?
TRI->getSubReg(SrcReg1, AMDGPU::sub1)
717 :
TRI->getSubReg(SrcReg1, AMDGPU::sub0);
718 if (
TRI->regsOverlap(UnpackedDstReg, HiSrc1Reg))
725 const MachineOperand *Src2MO =
726 TII->getNamedOperand(
MI, AMDGPU::OpName::src2);
727 if (Src2MO && Src2MO->
isReg()) {
730 TII->getNamedOperand(
MI, AMDGPU::OpName::src2_modifiers)->getImm();
732 ?
TRI->getSubReg(SrcReg2, AMDGPU::sub1)
733 :
TRI->getSubReg(SrcReg2, AMDGPU::sub0);
734 if (
TRI->regsOverlap(UnpackedDstReg, HiSrc2Reg))
741uint32_t SIPreEmitPeephole::mapToUnpackedOpcode(MachineInstr &
I) {
742 unsigned Opcode =
I.getOpcode();
747 case AMDGPU::V_PK_ADD_F32:
748 case AMDGPU::V_PK_ADD_F32_gfx1250:
749 return AMDGPU::V_ADD_F32_e64;
750 case AMDGPU::V_PK_MUL_F32:
751 case AMDGPU::V_PK_MUL_F32_gfx1250:
752 return AMDGPU::V_MUL_F32_e64;
753 case AMDGPU::V_PK_FMA_F32:
754 case AMDGPU::V_PK_FMA_F32_gfx1250:
755 return AMDGPU::V_FMA_F32_e64;
757 return std::numeric_limits<uint32_t>::max();
762void SIPreEmitPeephole::addOperandAndMods(MachineInstrBuilder &NewMI,
763 unsigned SrcMods,
bool IsHiBits,
764 const MachineOperand &SrcMO) {
765 unsigned NewSrcMods = 0;
777 if (SrcMods & NegModifier)
788 Register UnpackedSrcReg = (SrcMods & OpSelModifier)
789 ?
TRI->getSubReg(SrcMO.
getReg(), AMDGPU::sub1)
790 :
TRI->getSubReg(SrcMO.
getReg(), AMDGPU::sub0);
792 MachineOperand UnpackedSrcMO =
809 bool KillState =
true;
810 if ((OpSel == OpSelHi) && !IsHiBits)
814 NewMI.
add(UnpackedSrcMO);
817void SIPreEmitPeephole::collectUnpackingCandidates(
818 MachineInstr &BeginMI, SetVector<MachineInstr *> &InstrsToUnpack,
819 uint16_t NumMFMACycles) {
822 int TotalCyclesBetweenCandidates = 0;
823 const TargetSchedModel &SchedModel =
TII->getSchedModel();
828 uint32_t UnpackedOpCode = mapToUnpackedOpcode(Instr);
830 !(UnpackedOpCode == std::numeric_limits<uint32_t>::max());
831 if (
Instr.isMetaInstruction())
833 if ((
Instr.isTerminator()) ||
834 (
TII->isNeverCoissue(Instr) && !IsUnpackable) ||
836 Instr.modifiesRegister(AMDGPU::EXEC,
TRI)))
839 const MCSchedClassDesc *InstrSchedClassDesc =
843 TotalCyclesBetweenCandidates +=
Latency;
845 if (TotalCyclesBetweenCandidates >= NumMFMACycles - 1)
852 for (
const MachineOperand &InstrMO :
Instr.operands()) {
853 if (!InstrMO.isReg() || !InstrMO.getReg().isValid())
855 if (
TRI->regsOverlap(MFMADef, InstrMO.getReg()))
861 if (canUnpackingClobberRegister(Instr))
866 TotalCyclesBetweenCandidates -=
Latency;
868 TotalCyclesBetweenCandidates += 2;
870 if (TotalCyclesBetweenCandidates < NumMFMACycles - 1)
871 InstrsToUnpack.
insert(&Instr);
875void SIPreEmitPeephole::performF32Unpacking(MachineInstr &
I) {
876 const MachineOperand &DstOp =
I.getOperand(0);
878 uint32_t UnpackedOpcode = mapToUnpackedOpcode(
I);
879 assert(UnpackedOpcode != std::numeric_limits<uint32_t>::max() &&
880 "Unsupported Opcode");
882 MachineInstrBuilder Op0LOp1L =
883 createUnpackedMI(
I, UnpackedOpcode,
false);
884 MachineOperand &LoDstOp = Op0LOp1L->
getOperand(0);
888 MachineInstrBuilder Op0HOp1H =
889 createUnpackedMI(
I, UnpackedOpcode,
true);
890 MachineOperand &HiDstOp = Op0HOp1H->
getOperand(0);
892 uint32_t
IFlags =
I.getFlags();
901MachineInstrBuilder SIPreEmitPeephole::createUnpackedMI(MachineInstr &
I,
902 uint32_t UnpackedOpcode,
906 const MachineOperand *SrcMO0 =
TII->getNamedOperand(
I, AMDGPU::OpName::src0);
907 const MachineOperand *SrcMO1 =
TII->getNamedOperand(
I, AMDGPU::OpName::src1);
908 Register DstReg =
I.getOperand(0).getReg();
909 unsigned OpCode =
I.getOpcode();
910 Register UnpackedDstReg = IsHiBits ?
TRI->getSubReg(DstReg, AMDGPU::sub1)
911 :
TRI->getSubReg(DstReg, AMDGPU::sub0);
913 int64_t ClampVal =
TII->getNamedOperand(
I, AMDGPU::OpName::clamp)->getImm();
915 TII->getNamedOperand(
I, AMDGPU::OpName::src0_modifiers)->getImm();
917 TII->getNamedOperand(
I, AMDGPU::OpName::src1_modifiers)->getImm();
920 NewMI.
addDef(UnpackedDstReg);
921 addOperandAndMods(NewMI, Src0Mods, IsHiBits, *SrcMO0);
922 addOperandAndMods(NewMI, Src1Mods, IsHiBits, *SrcMO1);
925 const MachineOperand *SrcMO2 =
926 TII->getNamedOperand(
I, AMDGPU::OpName::src2);
928 TII->getNamedOperand(
I, AMDGPU::OpName::src2_modifiers)->getImm();
929 addOperandAndMods(NewMI, Src2Mods, IsHiBits, *SrcMO2);
942 SIPreEmitPeephole Impl;
944 if (Impl.run(MF, MLI)) {
961enum class VALUCoexecClass {
A = 0,
B = 1,
C = 2 };
966 return static_cast<unsigned>(Younger) +
static_cast<unsigned>(Older) <= 1;
971 return MO.isReg() && AMDGPU::AV_64RegClass.contains(MO.getReg());
981 AMDGPU::getVOPCoexecClassInfo(
MI.getOpcode());
983 return VALUCoexecClass::B;
984 const bool Has64BitAndMul32 = ST.hasCrossWaveVALUCoexec64BitAndMul32();
985 return static_cast<VALUCoexecClass
>(
986 Younger ? (Has64BitAndMul32 ? Info->CoexecYounger64BitAndMul32
987 : Info->CoexecYounger)
988 : (Has64BitAndMul32 ? Info->CoexecOlder64BitAndMul32
989 : Info->CoexecOlder));
998 return VALUCoexecClass::C;
1005 if (AMDGPU::getVOPCoexecClassInfo(
MI.getOpcode()) ==
nullptr &&
1008 return VALUCoexecClass::C;
1012 if (Class == VALUCoexecClass::B &&
1014 return VALUCoexecClass::C;
1026 unsigned NumVGPRs =
TRI->getNumUsedPhysRegs(
MRI, AMDGPU::VGPR_32RegClass,
1028 unsigned NumAGPRs =
TRI->getNumUsedPhysRegs(
MRI, AMDGPU::AGPR_32RegClass,
1050 unsigned NumInstrs = 0, NumOlderAB = 0, NumYoungerA = 0;
1053 if (
MI.isMetaInstruction() ||
MI.isBundle())
1056 return std::nullopt;
1074class CrossWaveVALUCoexecScanner {
1075 const GCNSubtarget &
ST;
1076 const SIInstrInfo &
TII;
1085 VALUCoexecClass XClass;
1089 unsigned getPasses(
const MachineInstr &
MI)
const;
1090 bool closeVALUSeq();
1093 explicit CrossWaveVALUCoexecScanner(
const GCNSubtarget &ST)
1097 bool scanBlock(MachineBasicBlock &
MBB);
1102unsigned CrossWaveVALUCoexecScanner::getPasses(
const MachineInstr &
MI)
const {
1103 const TargetSchedModel &SchedModel =
TII.getSchedModel();
1113bool CrossWaveVALUCoexecScanner::closeVALUSeq() {
1115 for (
const Candidate &
C : Candidates) {
1116 unsigned NumBlocking = 0;
1117 for (VALUCoexecClass OC :
drop_begin(VALUSeq,
C.Idx)) {
1124 BuildMI(*
C.MI->getParent(),
C.MI,
C.MI->getDebugLoc(),
1125 TII.get(AMDGPU::S_NOP))
1135bool CrossWaveVALUCoexecScanner::scanBlock(MachineBasicBlock &
MBB) {
1141 unsigned MFMAPassesLeft = 0;
1143 std::optional<VALUCoexecClass> PrevXClass;
1147 MachineInstr *ASeqStart =
nullptr;
1148 unsigned ASeqLen = 0;
1149 VALUCoexecClass ASeqXClass = VALUCoexecClass::B;
1151 if (
MI.isMetaInstruction() ||
MI.isBundle())
1153 bool InMFMAShadow = MFMAPassesLeft > 0;
1156 MFMAPassesLeft = std::max(MFMAPassesLeft, getPasses(
MI));
1157 else if (InMFMAShadow)
1158 MFMAPassesLeft -= std::min(MFMAPassesLeft, getPasses(
MI));
1163 ASeqStart =
nullptr;
1168 if (YC != VALUCoexecClass::A ||
MI.isInsideBundle()) {
1169 ASeqStart =
nullptr;
1170 }
else if (PrevXClass) {
1173 ASeqXClass = *PrevXClass;
1175 if (ASeqStart && ++ASeqLen == 2)
1176 Candidates.push_back({ASeqStart, VALUSeq.size() - 2, ASeqXClass});
1177 if (YC != VALUCoexecClass::A)
1206bool SIPreEmitPeephole::optimizeCrossWaveVALUCoexec(
MachineFunction &MF)
const {
1208 if (!
ST.hasCrossWaveVALUCoexecution() || !MLI || MLI->
empty() ||
1216 CrossWaveVALUCoexecScanner Scanner(ST);
1218 SmallPtrSet<const MachineLoop *, 8> GivenUp;
1222 [&](
const MachineLoop *
Sub) { return GivenUp.contains(Sub); })) {
1234 for (MachineBasicBlock *
MBB :
L->blocks())
1245bool SIPreEmitPeephole::run(
MachineFunction &MF, MachineLoopInfo *LoopInfo) {
1247 TII =
ST.getInstrInfo();
1254 for (MachineBasicBlock &
MBB : MF) {
1259 if (TermI !=
MBB.
end()) {
1260 MachineInstr &
MI = *TermI;
1261 switch (
MI.getOpcode()) {
1262 case AMDGPU::S_CBRANCH_VCCZ:
1263 case AMDGPU::S_CBRANCH_VCCNZ:
1266 case AMDGPU::S_CBRANCH_EXECZ:
1272 if (!
ST.hasVGPRIndexMode())
1275 MachineInstr *SetGPRMI =
nullptr;
1276 const unsigned Threshold = 20;
1284 if (
Count == Threshold)
1289 if (
MI.getOpcode() != AMDGPU::S_SET_GPR_IDX_ON)
1298 if (optimizeSetGPR(*SetGPRMI,
MI))
1309 if (!
ST.hasGFX940Insts())
1311 for (MachineBasicBlock &
MBB : MF) {
1314 const TargetSchedModel &SchedModel =
TII->getSchedModel();
1315 SetVector<MachineInstr *> InstrsToUnpack;
1319 const MCSchedClassDesc *SchedClassDesc =
1321 uint16_t NumMFMACycles =
1323 collectUnpackingCandidates(
MI, InstrsToUnpack, NumMFMACycles);
1325 for (MachineInstr *
MI : InstrsToUnpack) {
1326 performF32Unpacking(*
MI);
1328 if (!InstrsToUnpack.empty())
1332 Changed |= optimizeCrossWaveVALUCoexec(MF);
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
AMD GCN specific subclass of TargetSubtarget.
SmallVector< MachineOperand, 4 > Cond
while(!MBB.succ_empty()) MBB.removeSuccessor(MBB.succ_end() - 1)
Register const TargetRegisterInfo * TRI
Promote Memory to Register
OptimizedStructLayoutField Field
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
MachineRegisterInfo & MRI
static VALUCoexecClass getOlderVALUClass(const MachineInstr &MI, const GCNSubtarget &ST)
static bool canCoissueVALUs(VALUCoexecClass Younger, VALUCoexecClass Older)
static constexpr unsigned MinBlockingVALUs
static constexpr unsigned MinYoungerAPct
static VALUCoexecClass getVALUCoexecClass(const MachineInstr &MI, const GCNSubtarget &ST, bool Younger)
static constexpr unsigned MaxLoopInstrs
static std::optional< bool > isCrossWaveVALUCoexecLoop(const MachineLoop &L, const GCNSubtarget &ST)
static unsigned getAllocatedOccupancy(const MachineFunction &MF, const GCNSubtarget &ST)
static constexpr unsigned MinOlderABPct
static bool hasVectorOperandOf64Bits(const MachineInstr &MI)
static VALUCoexecClass getYoungerVALUClass(const MachineInstr &MI, const GCNSubtarget &ST)
This file defines the SmallPtrSet class.
static bool isProfitable(const CGDataOptions &Opts, const StableFunctionMap::StableFunctionEntries &SFS)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
MachineBasicBlock * getBranchDestBlock(const MachineInstr &MI) const override
const AArch64RegisterInfo & getRegisterInfo() const
getRegisterInfo - TargetInstrInfo is a superset of MRegister info.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const override
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static uint32_t getDenominator()
static constexpr BranchProbability getZero()
uint32_t getNumerator() const
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
static unsigned getMaxWMMACoexecutionWaitStates(const GCNSubtarget &ST)
Largest number of intervening VALUs checkWMMACoexecutionHazards() can require between an XDL WMMA and...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
BlockT * getHeader() const
iterator_range< block_iterator > blocks() const
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
SmallVector< LoopT *, 4 > getLoopsInPreorder() const
Return all of the loops in the function in preorder across the loop nests, with siblings in forward p...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Instructions::const_reverse_iterator const_reverse_instr_iterator
LLVM_ABI MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
LLVM_ABI BranchProbability getSuccProbability(const_succ_iterator Succ) const
Return probability of the edge from this block to MBB.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
reverse_instr_iterator instr_rend()
Instructions::iterator instr_iterator
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< iterator > terminators()
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
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.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
BasicBlockListType::const_iterator const_iterator
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
void setFlags(unsigned flags)
const MachineOperand & getOperand(unsigned i) const
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI void setIsRenamable(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
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 MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Wrapper class representing virtual and physical registers.
static bool isSDWA(const MachineInstr &MI)
static bool isDOT(const MachineInstr &MI)
static bool isVALU(const MachineInstr &MI, bool AllowLDSDMA)
static bool isTRANS(const MachineInstr &MI)
static bool isDPP(const MachineInstr &MI)
static bool isMFMA(const MachineInstr &MI)
static bool isVOP3P(const MachineInstr &MI)
static bool modifiesModeRegister(const MachineInstr &MI)
Return true if the instruction modifies the mode register.q.
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
unsigned getOccupancy() const
unsigned getDynamicVGPRBlockSize() const
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
bool insert(const value_type &X)
Insert a new element into the SetVector.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
reference emplace_back(ArgTypes &&... Args)
ProcResIter getWriteProcResEnd(const MCSchedClassDesc *SC) const
LLVM_ABI const MCSchedClassDesc * resolveSchedClass(const MachineInstr *MI) const
Return the MCSchedClassDesc for this instruction.
ProcResIter getWriteProcResBegin(const MCSchedClassDesc *SC) const
LLVM Value Representation.
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI unsigned getTotalNumVGPRs(GPUKind AK, bool IsWave32)
LLVM_READONLY bool hasNamedOperand(uint32_t Opcode, OpName NamedIdx)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< InstrNode * > Instr
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 find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
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.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
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...
char & SIPreEmitPeepholeID
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
@ End
Run the machine verifier once, at the end of the pipeline.
uint16_t ReleaseAtCycle
Cycle at which the resource will be released by an instruction, relatively to the cycle in which the ...