87#define DEBUG_TYPE "si-wqm"
96 StateStrict = StateStrictWWM | StateStrictWQM,
103 explicit PrintState(
int State) : State(State) {}
109 static const std::pair<char, const char *> Mapping[] = {
110 std::pair(StateWQM,
"WQM"), std::pair(StateStrictWWM,
"StrictWWM"),
111 std::pair(StateStrictWQM,
"StrictWQM"), std::pair(StateExact,
"Exact")};
112 char State = PS.State;
113 for (
auto M : Mapping) {
114 if (State & M.first) {
131 char MarkedStates = 0;
138 char InitialState = 0;
139 bool NeedsLowering =
false;
151class SIWholeQuadMode {
190 std::vector<WorkItem> &Worklist);
193 std::vector<WorkItem> &Worklist);
195 std::vector<WorkItem> &Worklist);
197 std::vector<WorkItem> &Worklist);
198 char scanInstructions(
MachineFunction &MF, std::vector<WorkItem> &Worklist,
200 void propagateInstruction(
MachineInstr &
MI, std::vector<WorkItem> &Worklist);
209 bool fixStrictLiveness();
222 Register SaveOrig,
char StrictStateNeeded);
225 char NonStrictState,
char CurrentStrictState);
234 bool lowerLiveMaskQueries();
235 bool lowerCopyInstrs();
236 bool lowerKillInstrs(
bool IsWQM);
250 StringRef getPassName()
const override {
return "SI Whole Quad Mode"; }
268char SIWholeQuadModeLegacy::ID = 0;
282 for (
const auto &BII : Blocks) {
285 <<
" InNeeds = " << PrintState(BII.second.InNeeds)
286 <<
", Needs = " << PrintState(BII.second.Needs)
287 <<
", OutNeeds = " << PrintState(BII.second.OutNeeds) <<
"\n\n";
290 auto III = Instructions.find(&
MI);
291 if (III != Instructions.end()) {
292 dbgs() <<
" " <<
MI <<
" Needs = " << PrintState(III->second.Needs)
293 <<
", OutNeeds = " << PrintState(III->second.OutNeeds) <<
'\n';
301 std::vector<WorkItem> &Worklist) {
302 InstrInfo &
II = Instructions[&
MI];
304 assert(!(Flag & StateExact) && Flag != 0);
307 II.MarkedStates |= Flag;
313 Flag &=
~II.Disabled;
317 if ((
II.Needs & Flag) == Flag)
322 Worklist.emplace_back(&
MI);
326void SIWholeQuadMode::markDefs(
const MachineInstr &
UseMI,
LiveRange &LR,
327 VirtRegOrUnit VRegOrUnit,
unsigned SubReg,
328 char Flag, std::vector<WorkItem> &Worklist) {
338 const LaneBitmask UseLanes =
339 SubReg ?
TRI->getSubRegIndexLaneMask(SubReg)
350 LaneBitmask DefinedLanes;
352 PhiEntry(
const VNInfo *Phi,
unsigned PredIdx, LaneBitmask DefinedLanes)
353 :
Phi(
Phi), PredIdx(PredIdx), DefinedLanes(DefinedLanes) {}
355 using VisitKey = std::pair<const VNInfo *, LaneBitmask>;
357 SmallSet<VisitKey, 4> Visited;
358 LaneBitmask DefinedLanes;
359 unsigned NextPredIdx = 0;
361 const VNInfo *NextValue =
nullptr;
362 const VisitKey
Key(
Value, DefinedLanes);
369 if (
Value->isPHIDef()) {
372 assert(
MBB &&
"Phi-def has no defining MBB");
375 unsigned Idx = NextPredIdx;
378 for (; PI != PE && !NextValue; ++PI, ++
Idx) {
380 if (!Visited.
count(VisitKey(VN, DefinedLanes)))
390 assert(
MI &&
"Def has no defining instruction");
395 for (
const MachineOperand &
Op :
MI->all_defs()) {
400 LaneBitmask OpLanes =
402 :
TRI->getSubRegIndexLaneMask(
Op.getSubReg());
403 LaneBitmask Overlap = (UseLanes & OpLanes);
406 HasDef |= Overlap.
any();
409 DefinedLanes |= OpLanes;
413 if ((DefinedLanes & UseLanes) != UseLanes) {
416 if (
const VNInfo *VN = LRQ.
valueIn()) {
417 if (!Visited.
count(VisitKey(VN, DefinedLanes)))
424 markInstruction(*
MI, Flag, Worklist);
427 markInstruction(*
MI, Flag, Worklist);
431 if (!NextValue && !PhiStack.
empty()) {
434 NextValue =
Entry.Phi;
435 NextPredIdx =
Entry.PredIdx;
436 DefinedLanes =
Entry.DefinedLanes;
444void SIWholeQuadMode::markOperand(
const MachineInstr &
MI,
445 const MachineOperand &
Op,
char Flag,
446 std::vector<WorkItem> &Worklist) {
453 case AMDGPU::EXEC_LO:
463 markDefs(
MI, LR, VirtRegOrUnit(
Reg),
Op.getSubReg(), Flag, Worklist);
472 markDefs(
MI, LR, VirtRegOrUnit(Unit), AMDGPU::NoSubRegister, Flag,
479void SIWholeQuadMode::markInstructionUses(
const MachineInstr &
MI,
char Flag,
480 std::vector<WorkItem> &Worklist) {
481 LLVM_DEBUG(
dbgs() <<
"markInstructionUses " << PrintState(Flag) <<
": "
484 for (
const MachineOperand &Use :
MI.all_uses())
485 markOperand(
MI, Use, Flag, Worklist);
490char SIWholeQuadMode::scanInstructions(
493 char GlobalFlags = 0;
495 SmallVector<MachineInstr *, 4> SoftWQMInstrs;
496 bool HasImplicitDerivatives =
503 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
504 for (MachineBasicBlock *
MBB : RPOT) {
505 BlockInfo &BBI = Blocks[
MBB];
507 for (MachineInstr &
MI : *
MBB) {
508 InstrInfo &III = Instructions[&
MI];
509 unsigned Opcode =
MI.getOpcode();
512 if (
TII->isWQM(Opcode)) {
517 if (ST->hasExtendedImageInsts() && HasImplicitDerivatives) {
521 markInstructionUses(
MI, StateWQM, Worklist);
522 GlobalFlags |= StateWQM;
524 }
else if (Opcode == AMDGPU::WQM) {
528 LowerToCopyInstrs.insert(&
MI);
529 }
else if (Opcode == AMDGPU::SOFT_WQM) {
530 LowerToCopyInstrs.insert(&
MI);
532 }
else if (Opcode == AMDGPU::STRICT_WWM) {
536 markInstructionUses(
MI, StateStrictWWM, Worklist);
537 GlobalFlags |= StateStrictWWM;
539 }
else if (Opcode == AMDGPU::STRICT_WQM ||
540 TII->isDualSourceBlendEXP(
MI)) {
544 markInstructionUses(
MI, StateStrictWQM, Worklist);
545 GlobalFlags |= StateStrictWQM;
547 if (Opcode == AMDGPU::STRICT_WQM) {
553 BBI.Needs |= StateExact;
554 if (!(BBI.InNeeds & StateExact)) {
555 BBI.InNeeds |= StateExact;
556 Worklist.emplace_back(
MBB);
558 GlobalFlags |= StateExact;
559 III.Disabled = StateWQM | StateStrict;
561 }
else if (Opcode == AMDGPU::LDS_PARAM_LOAD ||
562 Opcode == AMDGPU::DS_PARAM_LOAD ||
563 Opcode == AMDGPU::LDS_DIRECT_LOAD ||
564 Opcode == AMDGPU::DS_DIRECT_LOAD) {
567 III.Needs |= StateStrictWQM;
568 GlobalFlags |= StateStrictWQM;
569 }
else if (Opcode == AMDGPU::V_SET_INACTIVE_B32) {
571 III.Disabled = StateStrict;
572 MachineOperand &Inactive =
MI.getOperand(4);
573 if (Inactive.
isReg()) {
574 if (Inactive.
isUndef() &&
MI.getOperand(3).getImm() == 0)
575 LowerToCopyInstrs.insert(&
MI);
577 markOperand(
MI, Inactive, StateStrictWWM, Worklist);
580 BBI.NeedsLowering =
true;
581 }
else if (
TII->isDisableWQM(
MI)) {
582 BBI.Needs |= StateExact;
583 if (!(BBI.InNeeds & StateExact)) {
584 BBI.InNeeds |= StateExact;
585 Worklist.emplace_back(
MBB);
587 GlobalFlags |= StateExact;
588 III.Disabled = StateWQM | StateStrict;
589 }
else if (Opcode == AMDGPU::SI_PS_LIVE ||
590 Opcode == AMDGPU::SI_LIVE_MASK) {
592 }
else if (Opcode == AMDGPU::SI_KILL_I1_TERMINATOR ||
593 Opcode == AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR ||
594 Opcode == AMDGPU::SI_DEMOTE_I1) {
596 BBI.NeedsLowering =
true;
597 }
else if (Opcode == AMDGPU::SI_INIT_EXEC ||
598 Opcode == AMDGPU::SI_INIT_EXEC_FROM_INPUT ||
599 Opcode == AMDGPU::SI_INIT_WHOLE_WAVE) {
601 }
else if (WQMOutputs) {
606 for (
const MachineOperand &MO :
MI.defs()) {
609 TRI->hasVectorRegisters(
TRI->getPhysRegBaseClass(
Reg))) {
616 if (
TII->hasUnwantedEffectsWhenEXECEmpty(
MI)) {
617 for (
auto &
Op :
MI.uses()) {
620 if (!
TRI->isVectorRegister(*
MRI,
Op.getReg()))
629 markInstruction(
MI, Flags, Worklist);
630 GlobalFlags |=
Flags;
639 if (GlobalFlags & StateWQM) {
640 for (MachineInstr *
MI : SetInactiveInstrs)
641 markInstruction(*
MI, StateWQM, Worklist);
642 for (MachineInstr *
MI : SoftWQMInstrs)
643 markInstruction(*
MI, StateWQM, Worklist);
649void SIWholeQuadMode::propagateInstruction(MachineInstr &
MI,
650 std::vector<WorkItem>& Worklist) {
652 InstrInfo
II = Instructions[&
MI];
653 BlockInfo &BI = Blocks[
MBB];
657 if ((
II.OutNeeds & StateWQM) && !(
II.Disabled & StateWQM) &&
658 (
MI.isTerminator() || (
TII->usesVM_CNT(
MI) &&
MI.mayStore()))) {
659 Instructions[&
MI].Needs = StateWQM;
664 if (
II.Needs & StateWQM) {
665 BI.Needs |= StateWQM;
666 if (!(BI.InNeeds & StateWQM)) {
667 BI.InNeeds |= StateWQM;
668 Worklist.emplace_back(
MBB);
673 if (MachineInstr *PrevMI =
MI.getPrevNode()) {
674 char InNeeds = (
II.Needs & ~StateStrict) |
II.OutNeeds;
675 if (!PrevMI->isPHI()) {
676 InstrInfo &PrevII = Instructions[PrevMI];
677 if ((PrevII.OutNeeds | InNeeds) != PrevII.OutNeeds) {
678 PrevII.OutNeeds |= InNeeds;
679 Worklist.emplace_back(PrevMI);
688 markInstructionUses(
MI,
II.Needs, Worklist);
692 if (
II.Needs & StateStrictWWM)
693 BI.Needs |= StateStrictWWM;
694 if (
II.Needs & StateStrictWQM)
695 BI.Needs |= StateStrictWQM;
698void SIWholeQuadMode::propagateBlock(MachineBasicBlock &
MBB,
699 std::vector<WorkItem>& Worklist) {
700 BlockInfo BI = Blocks[&
MBB];
705 InstrInfo &LastII = Instructions[LastMI];
706 if ((LastII.OutNeeds | BI.OutNeeds) != LastII.OutNeeds) {
707 LastII.OutNeeds |= BI.OutNeeds;
708 Worklist.emplace_back(LastMI);
714 BlockInfo &PredBI = Blocks[
Pred];
715 if ((PredBI.OutNeeds | BI.InNeeds) == PredBI.OutNeeds)
718 PredBI.OutNeeds |= BI.InNeeds;
719 PredBI.InNeeds |= BI.InNeeds;
720 Worklist.emplace_back(
Pred);
725 BlockInfo &SuccBI = Blocks[Succ];
726 if ((SuccBI.InNeeds | BI.OutNeeds) == SuccBI.InNeeds)
729 SuccBI.InNeeds |= BI.OutNeeds;
730 Worklist.emplace_back(Succ);
735 std::vector<WorkItem> Worklist;
737 char GlobalFlags = scanInstructions(MF, Worklist, ExeczSideEffectInstrs);
739 while (!Worklist.empty()) {
740 WorkItem WI = Worklist.back();
744 propagateInstruction(*WI.MI, Worklist);
746 propagateBlock(*WI.MBB, Worklist);
748 if (Worklist.empty()) {
754 for (
auto *
MI : ExeczSideEffectInstrs) {
755 InstrInfo
II = Instructions[
MI];
756 if (
II.OutNeeds & StateWQM)
757 markInstructionUses(*
MI, StateWQM, Worklist);
761 ExeczSideEffectInstrs.clear();
769SIWholeQuadMode::getOperandLaneMask(
const MachineOperand &MO)
const {
771 return TRI->getSubRegIndexLaneMask(SubReg);
777bool SIWholeQuadMode::dropImplicitDefs(
const MachineOperand &Def,
780 if (!
llvm::all_of(ImplicitDefs, [&](
const MachineInstr *ImplicitDef) {
788 for (MachineInstr *ImplicitDef : ImplicitDefs) {
801bool SIWholeQuadMode::isolateStrictSubRegDef(MachineOperand &Def) {
802 MachineInstr &
MI = *
Def.getParent();
804 const unsigned SubReg =
Def.getSubReg();
805 const LaneBitmask DefLanes = getOperandLaneMask(Def);
808 assert(NewRC &&
"cannot get sub-register class for SubReg");
815 (getOperandLaneMask(MO) & DefLanes).
none())
826 const bool IsUndef =
Def.isUndef();
829 Def.setIsUndef(
false);
830 for (MachineOperand *MO : StrictUses) {
840 [&](
const MachineInstr &
I) { return StateTransition.contains(&I); });
841 assert(
I !=
MBB.
end() &&
"strict def without a region exit");
856bool SIWholeQuadMode::fixStrictDefLiveness(MachineOperand &Def) {
861 const LaneBitmask DefLanes = getOperandLaneMask(Def);
863 bool HasRealNonStrictDefs =
false;
864 bool HasOverlappingNonStrictDefs =
false;
872 if (
DefMI.isImplicitDef())
875 HasRealNonStrictDefs =
true;
876 HasOverlappingNonStrictDefs |= (getOperandLaneMask(MO) & DefLanes).
any();
879 if (
Def.getSubReg()) {
881 if (!HasOverlappingNonStrictDefs)
882 return isolateStrictSubRegDef(Def);
885 if (!HasRealNonStrictDefs)
886 return dropImplicitDefs(Def, ImplicitDefs);
891bool SIWholeQuadMode::fixStrictLiveness() {
893 for (MachineOperand *Def : StrictDefs)
894 Changed |= fixStrictDefLiveness(*Def);
899SIWholeQuadMode::saveSCC(MachineBasicBlock &
MBB,
906 MachineInstr *Restore =
917void SIWholeQuadMode::splitBlock(MachineInstr *TermMI) {
918 MachineBasicBlock *BB = TermMI->
getParent();
922 MachineBasicBlock *SplitBB =
923 BB->
splitAt(*TermMI,
true, LIS);
927 unsigned NewOpcode = 0;
929 case AMDGPU::S_AND_B32:
930 NewOpcode = AMDGPU::S_AND_B32_term;
932 case AMDGPU::S_AND_B64:
933 NewOpcode = AMDGPU::S_AND_B64_term;
935 case AMDGPU::S_MOV_B32:
936 NewOpcode = AMDGPU::S_MOV_B32_term;
938 case AMDGPU::S_MOV_B64:
939 NewOpcode = AMDGPU::S_MOV_B64_term;
941 case AMDGPU::S_ANDN2_B32:
942 NewOpcode = AMDGPU::S_ANDN2_B32_term;
944 case AMDGPU::S_ANDN2_B64:
945 NewOpcode = AMDGPU::S_ANDN2_B64_term;
959 for (MachineBasicBlock *Succ : SplitBB->
successors()) {
960 DTUpdates.
push_back({DomTreeT::Insert, SplitBB, Succ});
961 DTUpdates.
push_back({DomTreeT::Delete, BB, Succ});
963 DTUpdates.
push_back({DomTreeT::Insert, BB, SplitBB});
970MachineInstr *SIWholeQuadMode::lowerKillF32(MachineInstr &
MI) {
985 switch (
MI.getOperand(2).getImm()) {
987 Opcode = AMDGPU::V_CMP_LG_F32_e64;
990 Opcode = AMDGPU::V_CMP_GE_F32_e64;
993 Opcode = AMDGPU::V_CMP_GT_F32_e64;
996 Opcode = AMDGPU::V_CMP_LE_F32_e64;
999 Opcode = AMDGPU::V_CMP_LT_F32_e64;
1002 Opcode = AMDGPU::V_CMP_EQ_F32_e64;
1005 Opcode = AMDGPU::V_CMP_O_F32_e64;
1008 Opcode = AMDGPU::V_CMP_U_F32_e64;
1012 Opcode = AMDGPU::V_CMP_NEQ_F32_e64;
1016 Opcode = AMDGPU::V_CMP_NLT_F32_e64;
1020 Opcode = AMDGPU::V_CMP_NLE_F32_e64;
1024 Opcode = AMDGPU::V_CMP_NGT_F32_e64;
1028 Opcode = AMDGPU::V_CMP_NGE_F32_e64;
1032 Opcode = AMDGPU::V_CMP_NLG_F32_e64;
1041 MachineInstr *VcmpMI;
1042 const MachineOperand &Op0 =
MI.getOperand(0);
1043 const MachineOperand &Op1 =
MI.getOperand(1);
1059 MachineInstr *MaskUpdateMI =
1066 MachineInstr *EarlyTermMI =
1069 MachineInstr *ExecMaskMI =
1090MachineInstr *SIWholeQuadMode::lowerKillI1(MachineInstr &
MI,
bool IsWQM) {
1096 MachineInstr *MaskUpdateMI =
nullptr;
1098 const bool IsDemote = IsWQM && (
MI.getOpcode() == AMDGPU::SI_DEMOTE_I1);
1099 const MachineOperand &
Op =
MI.getOperand(0);
1100 int64_t KillVal =
MI.getOperand(1).getImm();
1101 MachineInstr *ComputeKilledMaskMI =
nullptr;
1107 if (
Op.getImm() == KillVal) {
1114 bool IsLastTerminator = std::next(
MI.getIterator()) ==
MBB.
end();
1115 if (!IsLastTerminator) {
1148 MachineInstr *EarlyTermMI =
1153 MachineInstr *NewTerm;
1154 MachineInstr *WQMMaskMI =
nullptr;
1171 }
else if (!IsWQM) {
1191 if (ComputeKilledMaskMI)
1214void SIWholeQuadMode::lowerBlock(MachineBasicBlock &
MBB, BlockInfo &BI) {
1215 if (!BI.NeedsLowering)
1220 SmallVector<MachineInstr *, 4> SplitPoints;
1222 char State = BI.InitialState;
1226 if ((State & StateStrict) && !
MI.isMetaInstruction()) {
1228 for (MachineOperand &MO :
MI.defs()) {
1231 StrictDefs.push_back(&MO);
1234 auto MIState = StateTransition.find(&
MI);
1235 if (MIState != StateTransition.end())
1236 State = MIState->second;
1238 MachineInstr *SplitPoint =
nullptr;
1239 switch (
MI.getOpcode()) {
1240 case AMDGPU::SI_DEMOTE_I1:
1241 case AMDGPU::SI_KILL_I1_TERMINATOR:
1242 SplitPoint = lowerKillI1(
MI, State == StateWQM);
1244 case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
1245 SplitPoint = lowerKillF32(
MI);
1247 case AMDGPU::ENTER_STRICT_WWM:
1248 ActiveLanesReg =
MI.getOperand(0).getReg();
1250 case AMDGPU::EXIT_STRICT_WWM:
1253 case AMDGPU::V_SET_INACTIVE_B32:
1254 if (ActiveLanesReg) {
1255 LiveInterval &LI = LIS->
getInterval(
MI.getOperand(5).getReg());
1257 MI.getOperand(5).setReg(ActiveLanesReg);
1260 assert(State == StateExact || State == StateWQM);
1271 for (MachineInstr *
MI : SplitPoints)
1291 SlotIndex FirstIdx = FirstNonDbg != MBBE
1296 SlotIndex
Idx = PreferLast ? LastIdx : FirstIdx;
1297 const LiveRange::Segment *S;
1306 if (
Next < FirstIdx)
1311 assert(EndMI &&
"Segment does not end on valid instruction");
1335 bool IsExecDef =
false;
1336 for (
const MachineOperand &MO :
MBBI->all_defs()) {
1338 MO.
getReg() == AMDGPU::EXEC_LO || MO.
getReg() == AMDGPU::EXEC;
1352void SIWholeQuadMode::toExact(MachineBasicBlock &
MBB,
1357 bool IsTerminator = Before ==
MBB.
end();
1358 if (!IsTerminator) {
1360 if (FirstTerm !=
MBB.
end()) {
1363 IsTerminator = BeforeIdx > FirstTermIdx;
1386 StateTransition[
MI] = StateExact;
1389void SIWholeQuadMode::toWQM(MachineBasicBlock &
MBB,
1405 StateTransition[
MI] = StateWQM;
1408void SIWholeQuadMode::toStrictMode(MachineBasicBlock &
MBB,
1410 Register SaveOrig,
char StrictStateNeeded) {
1413 assert(StrictStateNeeded == StateStrictWWM ||
1414 StrictStateNeeded == StateStrictWQM);
1418 if (StrictStateNeeded == StateStrictWWM) {
1428 StateTransition[
MI] = StrictStateNeeded;
1431void SIWholeQuadMode::fromStrictMode(MachineBasicBlock &
MBB,
1433 Register SavedOrig,
char NonStrictState,
1434 char CurrentStrictState) {
1438 assert(CurrentStrictState == StateStrictWWM ||
1439 CurrentStrictState == StateStrictWQM);
1443 if (CurrentStrictState == StateStrictWWM) {
1453 StateTransition[
MI] = NonStrictState;
1456void SIWholeQuadMode::processBlock(MachineBasicBlock &
MBB, BlockInfo &BI,
1460 if (!IsEntry && BI.Needs == StateWQM && BI.OutNeeds != StateExact) {
1461 BI.InitialState = StateWQM;
1470 bool WQMFromExec = IsEntry;
1471 char State = (IsEntry || !(BI.InNeeds & StateWQM)) ? StateExact : StateWQM;
1472 char NonStrictState = 0;
1478 if (
II != IE &&
II->getOpcode() == AMDGPU::COPY &&
1479 II->getOperand(1).getReg() == LMC.
ExecReg)
1494 BI.InitialState = State;
1496 for (
unsigned Idx = 0;; ++
Idx) {
1498 char Needs = StateExact | StateWQM;
1504 if (FirstStrict == IE)
1508 if (IsEntry && Idx == 0 && (BI.InNeeds & StateWQM))
1514 MachineInstr &
MI = *
II;
1516 if (
MI.isTerminator() ||
TII->mayReadEXEC(*
MRI,
MI)) {
1517 auto III = Instructions.find(&
MI);
1518 if (III != Instructions.end()) {
1519 if (III->second.Needs & StateStrictWWM)
1520 Needs = StateStrictWWM;
1521 else if (III->second.Needs & StateStrictWQM)
1522 Needs = StateStrictWQM;
1523 else if (III->second.Needs & StateWQM)
1526 Needs &= ~III->second.Disabled;
1527 OutNeeds = III->second.OutNeeds;
1532 Needs = StateExact | StateWQM | StateStrict;
1536 if (
MI.isBranch() && OutNeeds == StateExact)
1542 if (BI.OutNeeds & StateWQM)
1544 else if (BI.OutNeeds == StateExact)
1547 Needs = StateWQM | StateExact;
1551 if (!(Needs & State)) {
1553 if (State == StateStrictWWM || Needs == StateStrictWWM ||
1554 State == StateStrictWQM || Needs == StateStrictWQM) {
1556 First = FirstStrict;
1563 bool SaveSCC =
false;
1566 case StateStrictWWM:
1567 case StateStrictWQM:
1571 SaveSCC = (Needs & StateStrict) || ((Needs & StateWQM) && WQMFromExec);
1575 SaveSCC = !(Needs & StateWQM);
1581 char StartState = State & StateStrict ? NonStrictState : State;
1583 StartState == StateWQM && (Needs & StateExact) && !(Needs & StateWQM);
1584 bool ExactToWQM = StartState == StateExact && (Needs & StateWQM) &&
1585 !(Needs & StateExact);
1586 bool PreferLast = Needs == StateWQM;
1591 if ((WQMToExact && (OutNeeds & StateWQM)) || ExactToWQM) {
1593 if (
TII->hasUnwantedEffectsWhenEXECEmpty(*
I)) {
1594 PreferLast = WQMToExact;
1600 prepareInsertion(
MBB,
First,
II, PreferLast, SaveSCC);
1602 if (State & StateStrict) {
1603 assert(State == StateStrictWWM || State == StateStrictWQM);
1604 assert(SavedNonStrictReg);
1605 fromStrictMode(
MBB, Before, SavedNonStrictReg, NonStrictState, State);
1608 SavedNonStrictReg = 0;
1609 State = NonStrictState;
1612 if (Needs & StateStrict) {
1613 NonStrictState = State;
1614 assert(Needs == StateStrictWWM || Needs == StateStrictWQM);
1615 assert(!SavedNonStrictReg);
1618 toStrictMode(
MBB, Before, SavedNonStrictReg, Needs);
1620 BI.NeedsLowering =
true;
1623 if (!WQMFromExec && (OutNeeds & StateWQM)) {
1628 toExact(
MBB, Before, SavedWQMReg);
1630 }
else if (ExactToWQM) {
1631 assert(WQMFromExec == (SavedWQMReg == 0));
1633 toWQM(
MBB, Before, SavedWQMReg);
1649 if (Needs != (StateExact | StateWQM | StateStrict)) {
1650 if (Needs != (StateExact | StateWQM))
1661 assert(!SavedNonStrictReg);
1664bool SIWholeQuadMode::lowerLiveMaskQueries() {
1665 for (MachineInstr *
MI : LiveMaskQueries) {
1669 MachineInstr *
Copy =
1674 MI->eraseFromParent();
1676 return !LiveMaskQueries.empty();
1679bool SIWholeQuadMode::lowerCopyInstrs() {
1680 for (MachineInstr *
MI : LowerToMovInstrs) {
1681 assert(
MI->getNumExplicitOperands() == 2);
1686 TRI->getRegClassForOperandReg(*
MRI,
MI->getOperand(0));
1687 if (
TRI->isVGPRClass(regClass)) {
1688 const unsigned MovOp =
TII->getMovOpcode(regClass);
1689 MI->setDesc(
TII->get(MovOp));
1693 assert(
any_of(
MI->implicit_operands(), [](
const MachineOperand &MO) {
1694 return MO.isUse() && MO.getReg() == AMDGPU::EXEC;
1700 if (
MI->getOperand(0).isEarlyClobber()) {
1702 MI->getOperand(0).setIsEarlyClobber(
false);
1705 int Index =
MI->findRegisterUseOperandIdx(AMDGPU::EXEC,
nullptr);
1706 while (Index >= 0) {
1707 MI->removeOperand(Index);
1708 Index =
MI->findRegisterUseOperandIdx(AMDGPU::EXEC,
nullptr);
1710 MI->setDesc(
TII->get(AMDGPU::COPY));
1714 for (MachineInstr *
MI : LowerToCopyInstrs) {
1717 if (
MI->getOpcode() == AMDGPU::V_SET_INACTIVE_B32) {
1718 assert(
MI->getNumExplicitOperands() == 6);
1720 LiveInterval *RecomputeLI =
nullptr;
1721 if (
MI->getOperand(4).isReg())
1722 RecomputeLI = &LIS->
getInterval(
MI->getOperand(4).getReg());
1724 MI->removeOperand(5);
1725 MI->removeOperand(4);
1726 MI->removeOperand(3);
1727 MI->removeOperand(1);
1732 assert(
MI->getNumExplicitOperands() == 2);
1735 unsigned CopyOp =
MI->getOperand(1).isReg()
1736 ? (unsigned)AMDGPU::COPY
1737 :
TII->getMovOpcode(
TRI->getRegClassForOperandReg(
1738 *
MRI,
MI->getOperand(0)));
1739 MI->setDesc(
TII->get(CopyOp));
1742 return !LowerToCopyInstrs.empty() || !LowerToMovInstrs.empty();
1745bool SIWholeQuadMode::lowerKillInstrs(
bool IsWQM) {
1746 for (MachineInstr *
MI : KillInstrs) {
1747 MachineInstr *SplitPoint =
nullptr;
1748 switch (
MI->getOpcode()) {
1749 case AMDGPU::SI_DEMOTE_I1:
1750 case AMDGPU::SI_KILL_I1_TERMINATOR:
1751 SplitPoint = lowerKillI1(*
MI, IsWQM);
1753 case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
1754 SplitPoint = lowerKillF32(*
MI);
1760 return !KillInstrs.empty();
1763void SIWholeQuadMode::lowerInitExec(MachineInstr &
MI) {
1766 if (
MI.getOpcode() == AMDGPU::SI_INIT_WHOLE_WAVE) {
1768 "init whole wave not in entry block");
1782 MI.eraseFromParent();
1791 if (
MI.getOpcode() == AMDGPU::SI_INIT_EXEC) {
1795 .
addImm(
MI.getOperand(0).getImm());
1800 MI.eraseFromParent();
1811 Register InputReg =
MI.getOperand(0).getReg();
1812 MachineInstr *FirstMI = &*
MBB->
begin();
1817 if (DefInstr != FirstMI) {
1836 auto BfeMI =
BuildMI(*
MBB, FirstMI,
DL,
TII->get(AMDGPU::S_BFE_U32), CountReg)
1838 .
addImm((
MI.getOperand(1).getImm() & Mask) | 0x70000)
1843 auto CmpMI =
BuildMI(*
MBB, FirstMI,
DL,
TII->get(AMDGPU::S_CMP_EQ_U32))
1850 MI.eraseFromParent();
1855 MI.eraseFromParent();
1870SIWholeQuadMode::lowerInitExecInstrs(MachineBasicBlock &Entry,
bool &
Changed) {
1873 for (MachineInstr *
MI : InitExecInstrs) {
1877 if (
MI->getParent() == &Entry)
1889 <<
" ------------- \n");
1892 Instructions.clear();
1894 LiveMaskQueries.clear();
1895 LowerToCopyInstrs.clear();
1896 LowerToMovInstrs.clear();
1898 InitExecInstrs.clear();
1899 SetInactiveInstrs.
clear();
1900 StateTransition.clear();
1901 StrictInstrs.
clear();
1913 const bool HasLiveMaskQueries = !LiveMaskQueries.empty();
1914 const bool HasWaveModes = GlobalFlags & ~StateExact;
1915 const bool HasKills = !KillInstrs.empty();
1916 const bool UsesWQM = GlobalFlags & StateWQM;
1917 if (HasKills || UsesWQM || (HasWaveModes && HasLiveMaskQueries)) {
1928 for (MachineInstr *
MI : SetInactiveInstrs) {
1929 if (LowerToCopyInstrs.contains(
MI))
1931 auto &
Info = Instructions[
MI];
1932 if (
Info.MarkedStates & StateStrict) {
1933 Info.Needs |= StateStrictWWM;
1934 Info.Disabled &= ~StateStrictWWM;
1935 Blocks[
MI->getParent()].Needs |= StateStrictWWM;
1938 LowerToCopyInstrs.insert(
MI);
1944 Changed |= lowerLiveMaskQueries();
1947 if (!HasWaveModes) {
1949 Changed |= lowerKillInstrs(
false);
1950 }
else if (GlobalFlags == StateWQM) {
1957 lowerKillInstrs(
true);
1961 if (GlobalFlags & StateWQM)
1962 Blocks[&
Entry].InNeeds |= StateWQM;
1964 for (
auto &BII : Blocks)
1965 processBlock(*BII.first, BII.second, BII.first == &Entry);
1967 for (
auto &BII : Blocks)
1968 lowerBlock(*BII.first, BII.second);
1969 fixStrictLiveness();
1974 if (LiveMaskReg != LMC.
ExecReg)
1983 if (!KillInstrs.empty() || !InitExecInstrs.empty())
1989bool SIWholeQuadModeLegacy::runOnMachineFunction(
MachineFunction &MF) {
1990 LiveIntervals *LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
1991 MachineDominatorTree *MDT =
1992 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1994 getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
1995 MachinePostDominatorTree *PDT =
1996 PDTWrapper ? &PDTWrapper->getPostDomTree() :
nullptr;
1997 SIWholeQuadMode Impl(MF, LIS, MDT, PDT);
1998 return Impl.run(MF);
2010 SIWholeQuadMode Impl(MF, LIS, MDT, PDT);
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
const AArch64InstrInfo & TII
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static void analyzeFunction(Function &Fn, const DataLayout &Layout, FunctionVarLocsBuilder *FnVarLocs)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
AMD GCN specific subclass of TargetSubtarget.
Register const TargetRegisterInfo * TRI
Promote Memory to Register
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
MachineRegisterInfo & MRI
static void splitBlock(MachineBasicBlock &MBB, MachineInstr &MI, MachineDominatorTree *MDT, MachineLoopInfo *MLI)
SI Optimize VGPR LiveRange
static bool processBlock(MachineBasicBlock &MBB, const SystemZInstrInfo *TII, const TargetRegisterInfo *TRI)
unsigned getWavefrontSize() const
const unsigned AndSaveExecTermOpc
const unsigned AndTermOpc
static const LaneMaskConstants & get(const GCNSubtarget &ST)
const unsigned OrSaveExecOpc
const unsigned AndSaveExecOpc
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
void removeAllRegUnitsForPhysReg(MCRegister Reg)
Remove associated live ranges for the register units associated with Reg.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LLVM_ABI void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
LiveRange & getRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit.
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr, LaneBitmask SubRangeMask=LaneBitmask::getAll())
After removing some uses of a register, shrink its live range to just the remaining uses.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
This class represents the liveness of a register, stack slot, etc.
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarily including Idx,...
static constexpr MCRegister from(unsigned Val)
Check-convert the provided unsigned value to an MCRegister.
An RAII based helper class to modify MachineFunctionProperties when running pass.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
succ_iterator succ_begin()
MachineInstr * remove(MachineInstr *I)
Remove the unbundled instruction from the instruction list without deleting it.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
unsigned succ_size() const
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
pred_iterator pred_begin()
LLVM_ABI MachineBasicBlock * splitAt(MachineInstr &SplitInst, bool UpdateLiveIns=true, LiveIntervals *LIS=nullptr)
Split a basic block into 2 pieces at SplitPoint.
instr_iterator instr_end()
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
reverse_iterator rbegin()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
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.
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void dump() const
dump - Print the current MachineFunction to cerr, useful for debugger use.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & front() const
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
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 & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
LLVM_ABI MachineInstr * removeFromParent()
Unlink 'this' from the containing basic block, and return it without deleting it.
const MachineBasicBlock * getParent() const
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
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.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
iterator_range< def_iterator > def_operands(Register Reg) const
bool hasOneDef(Register RegNo) const
Return true if there is exactly one operand defining the specified register.
LLVM_ABI LaneBitmask getMaxLaneMaskForVReg(Register Reg) const
Returns a mask covering all bits that can appear in lane masks of subregisters of the virtual registe...
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
This class implements a map that also provides access to all stored values in a deterministic order.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Wrapper class representing virtual and physical registers.
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
static bool hasVGPRs(const TargetRegisterClass *RC)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Wrapper class representing a virtual register or register unit.
constexpr bool isVirtualReg() const
constexpr Register asVirtualReg() const
self_iterator getIterator()
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char WavefrontSize[]
Key for Kernel::CodeProps::Metadata::mWavefrontSize.
LLVM_READONLY int32_t getVOPe32(uint32_t Opcode)
constexpr bool any(E Val)
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.
NodeAddr< DefNode * > Def
NodeAddr< PhiNode * > Phi
This is an optimization pass for GlobalISel generic memory operations.
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of 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< 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
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
DominatorTreeBase< T, false > DomTreeBase
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...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
@ Disabled
Don't do any conversion of .debug_str_offsets tables.
constexpr RegState getUndefRegState(bool B)
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 Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
WorkItem(const BasicBlock *BB, int St)
static constexpr LaneBitmask getAll()
constexpr bool any() const
static constexpr LaneBitmask getNone()