xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/SIOptimizeExecMaskingPreRA.cpp (revision 753f127f3ace09432b2baeffd71a308760641a62)
10b57cec5SDimitry Andric //===-- SIOptimizeExecMaskingPreRA.cpp ------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric /// \file
105ffd83dbSDimitry Andric /// This pass performs exec mask handling peephole optimizations which needs
115ffd83dbSDimitry Andric /// to be done before register allocation to reduce register pressure.
120b57cec5SDimitry Andric ///
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "AMDGPU.h"
16e8d8bef9SDimitry Andric #include "GCNSubtarget.h"
170b57cec5SDimitry Andric #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
20480093f4SDimitry Andric #include "llvm/InitializePasses.h"
210b57cec5SDimitry Andric 
220b57cec5SDimitry Andric using namespace llvm;
230b57cec5SDimitry Andric 
240b57cec5SDimitry Andric #define DEBUG_TYPE "si-optimize-exec-masking-pre-ra"
250b57cec5SDimitry Andric 
260b57cec5SDimitry Andric namespace {
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric class SIOptimizeExecMaskingPreRA : public MachineFunctionPass {
290b57cec5SDimitry Andric private:
300b57cec5SDimitry Andric   const SIRegisterInfo *TRI;
310b57cec5SDimitry Andric   const SIInstrInfo *TII;
320b57cec5SDimitry Andric   MachineRegisterInfo *MRI;
33e8d8bef9SDimitry Andric   LiveIntervals *LIS;
34e8d8bef9SDimitry Andric 
35e8d8bef9SDimitry Andric   unsigned AndOpc;
36e8d8bef9SDimitry Andric   unsigned Andn2Opc;
37e8d8bef9SDimitry Andric   unsigned OrSaveExecOpc;
38e8d8bef9SDimitry Andric   unsigned XorTermrOpc;
39e8d8bef9SDimitry Andric   MCRegister CondReg;
40e8d8bef9SDimitry Andric   MCRegister ExecReg;
41e8d8bef9SDimitry Andric 
4281ad6265SDimitry Andric   bool optimizeVcndVcmpPair(MachineBasicBlock &MBB);
43e8d8bef9SDimitry Andric   bool optimizeElseBranch(MachineBasicBlock &MBB);
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric public:
460b57cec5SDimitry Andric   static char ID;
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric   SIOptimizeExecMaskingPreRA() : MachineFunctionPass(ID) {
490b57cec5SDimitry Andric     initializeSIOptimizeExecMaskingPreRAPass(*PassRegistry::getPassRegistry());
500b57cec5SDimitry Andric   }
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric   StringRef getPassName() const override {
550b57cec5SDimitry Andric     return "SI optimize exec mask operations pre-RA";
560b57cec5SDimitry Andric   }
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
590b57cec5SDimitry Andric     AU.addRequired<LiveIntervals>();
600b57cec5SDimitry Andric     AU.setPreservesAll();
610b57cec5SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
620b57cec5SDimitry Andric   }
630b57cec5SDimitry Andric };
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric } // End anonymous namespace.
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,
680b57cec5SDimitry Andric                       "SI optimize exec mask operations pre-RA", false, false)
690b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
700b57cec5SDimitry Andric INITIALIZE_PASS_END(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,
710b57cec5SDimitry Andric                     "SI optimize exec mask operations pre-RA", false, false)
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric char SIOptimizeExecMaskingPreRA::ID = 0;
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric char &llvm::SIOptimizeExecMaskingPreRAID = SIOptimizeExecMaskingPreRA::ID;
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric FunctionPass *llvm::createSIOptimizeExecMaskingPreRAPass() {
780b57cec5SDimitry Andric   return new SIOptimizeExecMaskingPreRA();
790b57cec5SDimitry Andric }
800b57cec5SDimitry Andric 
81e8d8bef9SDimitry Andric // See if there is a def between \p AndIdx and \p SelIdx that needs to live
82e8d8bef9SDimitry Andric // beyond \p AndIdx.
83e8d8bef9SDimitry Andric static bool isDefBetween(const LiveRange &LR, SlotIndex AndIdx,
84e8d8bef9SDimitry Andric                          SlotIndex SelIdx) {
85e8d8bef9SDimitry Andric   LiveQueryResult AndLRQ = LR.Query(AndIdx);
86e8d8bef9SDimitry Andric   return (!AndLRQ.isKill() && AndLRQ.valueIn() != LR.Query(SelIdx).valueOut());
87e8d8bef9SDimitry Andric }
880b57cec5SDimitry Andric 
89e8d8bef9SDimitry Andric // FIXME: Why do we bother trying to handle physical registers here?
90e8d8bef9SDimitry Andric static bool isDefBetween(const SIRegisterInfo &TRI,
91e8d8bef9SDimitry Andric                          LiveIntervals *LIS, Register Reg,
92e8d8bef9SDimitry Andric                          const MachineInstr &Sel, const MachineInstr &And) {
9381ad6265SDimitry Andric   SlotIndex AndIdx = LIS->getInstructionIndex(And).getRegSlot();
9481ad6265SDimitry Andric   SlotIndex SelIdx = LIS->getInstructionIndex(Sel).getRegSlot();
95e8d8bef9SDimitry Andric 
96e8d8bef9SDimitry Andric   if (Reg.isVirtual())
97e8d8bef9SDimitry Andric     return isDefBetween(LIS->getInterval(Reg), AndIdx, SelIdx);
98e8d8bef9SDimitry Andric 
99e8d8bef9SDimitry Andric   for (MCRegUnitIterator UI(Reg.asMCReg(), &TRI); UI.isValid(); ++UI) {
100e8d8bef9SDimitry Andric     if (isDefBetween(LIS->getRegUnit(*UI), AndIdx, SelIdx))
1010b57cec5SDimitry Andric       return true;
102e8d8bef9SDimitry Andric   }
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric   return false;
1050b57cec5SDimitry Andric }
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric // Optimize sequence
1080b57cec5SDimitry Andric //    %sel = V_CNDMASK_B32_e64 0, 1, %cc
1090b57cec5SDimitry Andric //    %cmp = V_CMP_NE_U32 1, %1
1100b57cec5SDimitry Andric //    $vcc = S_AND_B64 $exec, %cmp
1110b57cec5SDimitry Andric //    S_CBRANCH_VCC[N]Z
1120b57cec5SDimitry Andric // =>
1130b57cec5SDimitry Andric //    $vcc = S_ANDN2_B64 $exec, %cc
1140b57cec5SDimitry Andric //    S_CBRANCH_VCC[N]Z
1150b57cec5SDimitry Andric //
1160b57cec5SDimitry Andric // It is the negation pattern inserted by DAGCombiner::visitBRCOND() in the
1170b57cec5SDimitry Andric // rebuildSetCC(). We start with S_CBRANCH to avoid exhaustive search, but
1180b57cec5SDimitry Andric // only 3 first instructions are really needed. S_AND_B64 with exec is a
1190b57cec5SDimitry Andric // required part of the pattern since V_CNDMASK_B32 writes zeroes for inactive
1200b57cec5SDimitry Andric // lanes.
1210b57cec5SDimitry Andric //
12281ad6265SDimitry Andric // Returns true on success.
12381ad6265SDimitry Andric bool SIOptimizeExecMaskingPreRA::optimizeVcndVcmpPair(MachineBasicBlock &MBB) {
1240b57cec5SDimitry Andric   auto I = llvm::find_if(MBB.terminators(), [](const MachineInstr &MI) {
1250b57cec5SDimitry Andric                            unsigned Opc = MI.getOpcode();
1260b57cec5SDimitry Andric                            return Opc == AMDGPU::S_CBRANCH_VCCZ ||
1270b57cec5SDimitry Andric                                   Opc == AMDGPU::S_CBRANCH_VCCNZ; });
1280b57cec5SDimitry Andric   if (I == MBB.terminators().end())
12981ad6265SDimitry Andric     return false;
1300b57cec5SDimitry Andric 
131e8d8bef9SDimitry Andric   auto *And =
132e8d8bef9SDimitry Andric       TRI->findReachingDef(CondReg, AMDGPU::NoSubRegister, *I, *MRI, LIS);
1330b57cec5SDimitry Andric   if (!And || And->getOpcode() != AndOpc ||
1340b57cec5SDimitry Andric       !And->getOperand(1).isReg() || !And->getOperand(2).isReg())
13581ad6265SDimitry Andric     return false;
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   MachineOperand *AndCC = &And->getOperand(1);
1388bcb0991SDimitry Andric   Register CmpReg = AndCC->getReg();
1390b57cec5SDimitry Andric   unsigned CmpSubReg = AndCC->getSubReg();
140e8d8bef9SDimitry Andric   if (CmpReg == Register(ExecReg)) {
1410b57cec5SDimitry Andric     AndCC = &And->getOperand(2);
1420b57cec5SDimitry Andric     CmpReg = AndCC->getReg();
1430b57cec5SDimitry Andric     CmpSubReg = AndCC->getSubReg();
144e8d8bef9SDimitry Andric   } else if (And->getOperand(2).getReg() != Register(ExecReg)) {
14581ad6265SDimitry Andric     return false;
1460b57cec5SDimitry Andric   }
1470b57cec5SDimitry Andric 
148e8d8bef9SDimitry Andric   auto *Cmp = TRI->findReachingDef(CmpReg, CmpSubReg, *And, *MRI, LIS);
1490b57cec5SDimitry Andric   if (!Cmp || !(Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e32 ||
1500b57cec5SDimitry Andric                 Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e64) ||
1510b57cec5SDimitry Andric       Cmp->getParent() != And->getParent())
15281ad6265SDimitry Andric     return false;
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   MachineOperand *Op1 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src0);
1550b57cec5SDimitry Andric   MachineOperand *Op2 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src1);
1560b57cec5SDimitry Andric   if (Op1->isImm() && Op2->isReg())
1570b57cec5SDimitry Andric     std::swap(Op1, Op2);
1580b57cec5SDimitry Andric   if (!Op1->isReg() || !Op2->isImm() || Op2->getImm() != 1)
15981ad6265SDimitry Andric     return false;
1600b57cec5SDimitry Andric 
1618bcb0991SDimitry Andric   Register SelReg = Op1->getReg();
162*753f127fSDimitry Andric   if (SelReg.isPhysical())
163*753f127fSDimitry Andric     return false;
164*753f127fSDimitry Andric 
165e8d8bef9SDimitry Andric   auto *Sel = TRI->findReachingDef(SelReg, Op1->getSubReg(), *Cmp, *MRI, LIS);
1660b57cec5SDimitry Andric   if (!Sel || Sel->getOpcode() != AMDGPU::V_CNDMASK_B32_e64)
16781ad6265SDimitry Andric     return false;
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   if (TII->hasModifiersSet(*Sel, AMDGPU::OpName::src0_modifiers) ||
1700b57cec5SDimitry Andric       TII->hasModifiersSet(*Sel, AMDGPU::OpName::src1_modifiers))
17181ad6265SDimitry Andric     return false;
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   Op1 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src0);
1740b57cec5SDimitry Andric   Op2 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src1);
1750b57cec5SDimitry Andric   MachineOperand *CC = TII->getNamedOperand(*Sel, AMDGPU::OpName::src2);
1760b57cec5SDimitry Andric   if (!Op1->isImm() || !Op2->isImm() || !CC->isReg() ||
1770b57cec5SDimitry Andric       Op1->getImm() != 0 || Op2->getImm() != 1)
17881ad6265SDimitry Andric     return false;
179e8d8bef9SDimitry Andric 
180e8d8bef9SDimitry Andric   Register CCReg = CC->getReg();
181e8d8bef9SDimitry Andric 
182e8d8bef9SDimitry Andric   // If there was a def between the select and the and, we would need to move it
183e8d8bef9SDimitry Andric   // to fold this.
184e8d8bef9SDimitry Andric   if (isDefBetween(*TRI, LIS, CCReg, *Sel, *And))
18581ad6265SDimitry Andric     return false;
1860b57cec5SDimitry Andric 
18781ad6265SDimitry Andric   // TODO: Guard against implicit def operands?
1888bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << "Folding sequence:\n\t" << *Sel << '\t' << *Cmp << '\t'
1898bcb0991SDimitry Andric                     << *And);
1900b57cec5SDimitry Andric 
1918bcb0991SDimitry Andric   MachineInstr *Andn2 =
1928bcb0991SDimitry Andric       BuildMI(MBB, *And, And->getDebugLoc(), TII->get(Andn2Opc),
1938bcb0991SDimitry Andric               And->getOperand(0).getReg())
1940b57cec5SDimitry Andric           .addReg(ExecReg)
1958bcb0991SDimitry Andric           .addReg(CCReg, getUndefRegState(CC->isUndef()), CC->getSubReg());
1965ffd83dbSDimitry Andric   MachineOperand &AndSCC = And->getOperand(3);
1975ffd83dbSDimitry Andric   assert(AndSCC.getReg() == AMDGPU::SCC);
1985ffd83dbSDimitry Andric   MachineOperand &Andn2SCC = Andn2->getOperand(3);
1995ffd83dbSDimitry Andric   assert(Andn2SCC.getReg() == AMDGPU::SCC);
2005ffd83dbSDimitry Andric   Andn2SCC.setIsDead(AndSCC.isDead());
20181ad6265SDimitry Andric 
20281ad6265SDimitry Andric   SlotIndex AndIdx = LIS->ReplaceMachineInstrInMaps(*And, *Andn2);
2030b57cec5SDimitry Andric   And->eraseFromParent();
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "=>\n\t" << *Andn2 << '\n');
2060b57cec5SDimitry Andric 
20781ad6265SDimitry Andric   SlotIndex CmpIdx = LIS->getInstructionIndex(*Cmp);
20881ad6265SDimitry Andric   SlotIndex SelIdx = LIS->getInstructionIndex(*Sel);
20981ad6265SDimitry Andric 
21081ad6265SDimitry Andric   LiveInterval *CmpLI =
21181ad6265SDimitry Andric       CmpReg.isVirtual() ? &LIS->getInterval(CmpReg) : nullptr;
21281ad6265SDimitry Andric   LiveInterval *SelLI =
21381ad6265SDimitry Andric       SelReg.isVirtual() ? &LIS->getInterval(SelReg) : nullptr;
21481ad6265SDimitry Andric 
21581ad6265SDimitry Andric   // Update live intervals for CCReg before potentially removing CmpReg/SelReg,
21681ad6265SDimitry Andric   // and their associated liveness information.
21781ad6265SDimitry Andric   if (CCReg.isVirtual()) {
21881ad6265SDimitry Andric     // Note: this ignores that SelLI might have multiple internal values
21981ad6265SDimitry Andric     // or splits and simply extends the live range to cover all cases
22081ad6265SDimitry Andric     // where the result of the v_cndmask_b32 was live (e.g. loops).
22181ad6265SDimitry Andric     // This could yield worse register allocation in rare edge cases.
22281ad6265SDimitry Andric     SlotIndex EndIdx = AndIdx.getRegSlot();
22381ad6265SDimitry Andric     if (SelLI && SelLI->endIndex() > EndIdx && SelLI->endIndex().isBlock())
22481ad6265SDimitry Andric       EndIdx = SelLI->endIndex();
22581ad6265SDimitry Andric 
22681ad6265SDimitry Andric     LiveInterval &CCLI = LIS->getInterval(CCReg);
22781ad6265SDimitry Andric     auto CCQ = CCLI.Query(SelIdx.getRegSlot());
22881ad6265SDimitry Andric     if (CCQ.valueIn()) {
22981ad6265SDimitry Andric       CCLI.addSegment(LiveRange::Segment(SelIdx.getRegSlot(),
23081ad6265SDimitry Andric                                          EndIdx, CCQ.valueIn()));
23181ad6265SDimitry Andric     }
23281ad6265SDimitry Andric 
23381ad6265SDimitry Andric     if (CC->getSubReg()) {
23481ad6265SDimitry Andric       LaneBitmask Mask = TRI->getSubRegIndexLaneMask(CC->getSubReg());
23581ad6265SDimitry Andric       BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
23681ad6265SDimitry Andric       CCLI.refineSubRanges(
23781ad6265SDimitry Andric           Allocator, Mask,
23881ad6265SDimitry Andric           [=](LiveInterval::SubRange &SR) {
23981ad6265SDimitry Andric             auto CCQS = SR.Query(SelIdx.getRegSlot());
24081ad6265SDimitry Andric             if (CCQS.valueIn()) {
24181ad6265SDimitry Andric               SR.addSegment(LiveRange::Segment(
24281ad6265SDimitry Andric                   SelIdx.getRegSlot(), EndIdx, CCQS.valueIn()));
24381ad6265SDimitry Andric             }
24481ad6265SDimitry Andric           },
24581ad6265SDimitry Andric           *LIS->getSlotIndexes(), *TRI);
24681ad6265SDimitry Andric       CCLI.removeEmptySubRanges();
24781ad6265SDimitry Andric 
24881ad6265SDimitry Andric       SmallVector<LiveInterval *> SplitLIs;
24981ad6265SDimitry Andric       LIS->splitSeparateComponents(CCLI, SplitLIs);
25081ad6265SDimitry Andric     }
25181ad6265SDimitry Andric   } else
25281ad6265SDimitry Andric     LIS->removeAllRegUnitsForPhysReg(CCReg);
25381ad6265SDimitry Andric 
2540b57cec5SDimitry Andric   // Try to remove compare. Cmp value should not used in between of cmp
2550b57cec5SDimitry Andric   // and s_and_b64 if VCC or just unused if any other register.
25681ad6265SDimitry Andric   if ((CmpReg.isVirtual() && CmpLI && CmpLI->Query(AndIdx.getRegSlot()).isKill()) ||
257e8d8bef9SDimitry Andric       (CmpReg == Register(CondReg) &&
2580b57cec5SDimitry Andric        std::none_of(std::next(Cmp->getIterator()), Andn2->getIterator(),
2590b57cec5SDimitry Andric                     [&](const MachineInstr &MI) {
2608bcb0991SDimitry Andric                       return MI.readsRegister(CondReg, TRI);
2618bcb0991SDimitry Andric                     }))) {
2620b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Erasing: " << *Cmp << '\n');
26381ad6265SDimitry Andric     if (CmpLI)
26481ad6265SDimitry Andric       LIS->removeVRegDefAt(*CmpLI, CmpIdx.getRegSlot());
2650b57cec5SDimitry Andric     LIS->RemoveMachineInstrFromMaps(*Cmp);
2660b57cec5SDimitry Andric     Cmp->eraseFromParent();
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric     // Try to remove v_cndmask_b32.
26981ad6265SDimitry Andric     if (SelLI) {
270*753f127fSDimitry Andric       // Kill status must be checked before shrinking the live range.
271*753f127fSDimitry Andric       bool IsKill = SelLI->Query(CmpIdx.getRegSlot()).isKill();
272*753f127fSDimitry Andric       LIS->shrinkToUses(SelLI);
273*753f127fSDimitry Andric       bool IsDead = SelLI->Query(SelIdx.getRegSlot()).isDeadDef();
274*753f127fSDimitry Andric       if (MRI->use_nodbg_empty(SelReg) && (IsKill || IsDead)) {
2750b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Erasing: " << *Sel << '\n');
2760b57cec5SDimitry Andric 
27781ad6265SDimitry Andric         LIS->removeVRegDefAt(*SelLI, SelIdx.getRegSlot());
2780b57cec5SDimitry Andric         LIS->RemoveMachineInstrFromMaps(*Sel);
2790b57cec5SDimitry Andric         Sel->eraseFromParent();
2800b57cec5SDimitry Andric       }
2810b57cec5SDimitry Andric     }
28281ad6265SDimitry Andric   }
2830b57cec5SDimitry Andric 
28481ad6265SDimitry Andric   return true;
2850b57cec5SDimitry Andric }
2860b57cec5SDimitry Andric 
287e8d8bef9SDimitry Andric // Optimize sequence
288e8d8bef9SDimitry Andric //    %dst = S_OR_SAVEEXEC %src
289e8d8bef9SDimitry Andric //    ... instructions not modifying exec ...
290e8d8bef9SDimitry Andric //    %tmp = S_AND $exec, %dst
291e8d8bef9SDimitry Andric //    $exec = S_XOR_term $exec, %tmp
292e8d8bef9SDimitry Andric // =>
293e8d8bef9SDimitry Andric //    %dst = S_OR_SAVEEXEC %src
294e8d8bef9SDimitry Andric //    ... instructions not modifying exec ...
295e8d8bef9SDimitry Andric //    $exec = S_XOR_term $exec, %dst
296e8d8bef9SDimitry Andric //
297e8d8bef9SDimitry Andric // Clean up potentially unnecessary code added for safety during
298e8d8bef9SDimitry Andric // control flow lowering.
299e8d8bef9SDimitry Andric //
300e8d8bef9SDimitry Andric // Return whether any changes were made to MBB.
301e8d8bef9SDimitry Andric bool SIOptimizeExecMaskingPreRA::optimizeElseBranch(MachineBasicBlock &MBB) {
302e8d8bef9SDimitry Andric   if (MBB.empty())
303e8d8bef9SDimitry Andric     return false;
304e8d8bef9SDimitry Andric 
305e8d8bef9SDimitry Andric   // Check this is an else block.
306e8d8bef9SDimitry Andric   auto First = MBB.begin();
307e8d8bef9SDimitry Andric   MachineInstr &SaveExecMI = *First;
308e8d8bef9SDimitry Andric   if (SaveExecMI.getOpcode() != OrSaveExecOpc)
309e8d8bef9SDimitry Andric     return false;
310e8d8bef9SDimitry Andric 
311e8d8bef9SDimitry Andric   auto I = llvm::find_if(MBB.terminators(), [this](const MachineInstr &MI) {
312e8d8bef9SDimitry Andric     return MI.getOpcode() == XorTermrOpc;
313e8d8bef9SDimitry Andric   });
314e8d8bef9SDimitry Andric   if (I == MBB.terminators().end())
315e8d8bef9SDimitry Andric     return false;
316e8d8bef9SDimitry Andric 
317e8d8bef9SDimitry Andric   MachineInstr &XorTermMI = *I;
318e8d8bef9SDimitry Andric   if (XorTermMI.getOperand(1).getReg() != Register(ExecReg))
319e8d8bef9SDimitry Andric     return false;
320e8d8bef9SDimitry Andric 
321e8d8bef9SDimitry Andric   Register SavedExecReg = SaveExecMI.getOperand(0).getReg();
322e8d8bef9SDimitry Andric   Register DstReg = XorTermMI.getOperand(2).getReg();
323e8d8bef9SDimitry Andric 
324e8d8bef9SDimitry Andric   // Find potentially unnecessary S_AND
325e8d8bef9SDimitry Andric   MachineInstr *AndExecMI = nullptr;
326e8d8bef9SDimitry Andric   I--;
327e8d8bef9SDimitry Andric   while (I != First && !AndExecMI) {
328e8d8bef9SDimitry Andric     if (I->getOpcode() == AndOpc && I->getOperand(0).getReg() == DstReg &&
329e8d8bef9SDimitry Andric         I->getOperand(1).getReg() == Register(ExecReg))
330e8d8bef9SDimitry Andric       AndExecMI = &*I;
331e8d8bef9SDimitry Andric     I--;
332e8d8bef9SDimitry Andric   }
333e8d8bef9SDimitry Andric   if (!AndExecMI)
334e8d8bef9SDimitry Andric     return false;
335e8d8bef9SDimitry Andric 
336e8d8bef9SDimitry Andric   // Check for exec modifying instructions.
337e8d8bef9SDimitry Andric   // Note: exec defs do not create live ranges beyond the
338e8d8bef9SDimitry Andric   // instruction so isDefBetween cannot be used.
339e8d8bef9SDimitry Andric   // Instead just check that the def segments are adjacent.
340e8d8bef9SDimitry Andric   SlotIndex StartIdx = LIS->getInstructionIndex(SaveExecMI);
341e8d8bef9SDimitry Andric   SlotIndex EndIdx = LIS->getInstructionIndex(*AndExecMI);
342e8d8bef9SDimitry Andric   for (MCRegUnitIterator UI(ExecReg, TRI); UI.isValid(); ++UI) {
343e8d8bef9SDimitry Andric     LiveRange &RegUnit = LIS->getRegUnit(*UI);
344e8d8bef9SDimitry Andric     if (RegUnit.find(StartIdx) != std::prev(RegUnit.find(EndIdx)))
345e8d8bef9SDimitry Andric       return false;
346e8d8bef9SDimitry Andric   }
347e8d8bef9SDimitry Andric 
348e8d8bef9SDimitry Andric   // Remove unnecessary S_AND
349e8d8bef9SDimitry Andric   LIS->removeInterval(SavedExecReg);
350e8d8bef9SDimitry Andric   LIS->removeInterval(DstReg);
351e8d8bef9SDimitry Andric 
352e8d8bef9SDimitry Andric   SaveExecMI.getOperand(0).setReg(DstReg);
353e8d8bef9SDimitry Andric 
354e8d8bef9SDimitry Andric   LIS->RemoveMachineInstrFromMaps(*AndExecMI);
355e8d8bef9SDimitry Andric   AndExecMI->eraseFromParent();
356e8d8bef9SDimitry Andric 
357e8d8bef9SDimitry Andric   LIS->createAndComputeVirtRegInterval(DstReg);
358e8d8bef9SDimitry Andric 
359e8d8bef9SDimitry Andric   return true;
360e8d8bef9SDimitry Andric }
361e8d8bef9SDimitry Andric 
3620b57cec5SDimitry Andric bool SIOptimizeExecMaskingPreRA::runOnMachineFunction(MachineFunction &MF) {
3630b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()))
3640b57cec5SDimitry Andric     return false;
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3670b57cec5SDimitry Andric   TRI = ST.getRegisterInfo();
3680b57cec5SDimitry Andric   TII = ST.getInstrInfo();
3690b57cec5SDimitry Andric   MRI = &MF.getRegInfo();
370e8d8bef9SDimitry Andric   LIS = &getAnalysis<LiveIntervals>();
3710b57cec5SDimitry Andric 
372e8d8bef9SDimitry Andric   const bool Wave32 = ST.isWave32();
373e8d8bef9SDimitry Andric   AndOpc = Wave32 ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
374e8d8bef9SDimitry Andric   Andn2Opc = Wave32 ? AMDGPU::S_ANDN2_B32 : AMDGPU::S_ANDN2_B64;
375e8d8bef9SDimitry Andric   OrSaveExecOpc =
376e8d8bef9SDimitry Andric       Wave32 ? AMDGPU::S_OR_SAVEEXEC_B32 : AMDGPU::S_OR_SAVEEXEC_B64;
377e8d8bef9SDimitry Andric   XorTermrOpc = Wave32 ? AMDGPU::S_XOR_B32_term : AMDGPU::S_XOR_B64_term;
378e8d8bef9SDimitry Andric   CondReg = MCRegister::from(Wave32 ? AMDGPU::VCC_LO : AMDGPU::VCC);
379e8d8bef9SDimitry Andric   ExecReg = MCRegister::from(Wave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC);
380e8d8bef9SDimitry Andric 
381e8d8bef9SDimitry Andric   DenseSet<Register> RecalcRegs({AMDGPU::EXEC_LO, AMDGPU::EXEC_HI});
3820b57cec5SDimitry Andric   bool Changed = false;
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
3850b57cec5SDimitry Andric 
386e8d8bef9SDimitry Andric     if (optimizeElseBranch(MBB)) {
387e8d8bef9SDimitry Andric       RecalcRegs.insert(AMDGPU::SCC);
388e8d8bef9SDimitry Andric       Changed = true;
389e8d8bef9SDimitry Andric     }
390e8d8bef9SDimitry Andric 
39181ad6265SDimitry Andric     if (optimizeVcndVcmpPair(MBB)) {
3920b57cec5SDimitry Andric       RecalcRegs.insert(AMDGPU::VCC_LO);
3930b57cec5SDimitry Andric       RecalcRegs.insert(AMDGPU::VCC_HI);
3940b57cec5SDimitry Andric       RecalcRegs.insert(AMDGPU::SCC);
3950b57cec5SDimitry Andric       Changed = true;
3960b57cec5SDimitry Andric     }
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric     // Try to remove unneeded instructions before s_endpgm.
3990b57cec5SDimitry Andric     if (MBB.succ_empty()) {
4000b57cec5SDimitry Andric       if (MBB.empty())
4010b57cec5SDimitry Andric         continue;
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric       // Skip this if the endpgm has any implicit uses, otherwise we would need
4040b57cec5SDimitry Andric       // to be careful to update / remove them.
4050b57cec5SDimitry Andric       // S_ENDPGM always has a single imm operand that is not used other than to
4060b57cec5SDimitry Andric       // end up in the encoding
4070b57cec5SDimitry Andric       MachineInstr &Term = MBB.back();
4080b57cec5SDimitry Andric       if (Term.getOpcode() != AMDGPU::S_ENDPGM || Term.getNumOperands() != 1)
4090b57cec5SDimitry Andric         continue;
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric       SmallVector<MachineBasicBlock*, 4> Blocks({&MBB});
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric       while (!Blocks.empty()) {
4140b57cec5SDimitry Andric         auto CurBB = Blocks.pop_back_val();
4150b57cec5SDimitry Andric         auto I = CurBB->rbegin(), E = CurBB->rend();
4160b57cec5SDimitry Andric         if (I != E) {
4170b57cec5SDimitry Andric           if (I->isUnconditionalBranch() || I->getOpcode() == AMDGPU::S_ENDPGM)
4180b57cec5SDimitry Andric             ++I;
4190b57cec5SDimitry Andric           else if (I->isBranch())
4200b57cec5SDimitry Andric             continue;
4210b57cec5SDimitry Andric         }
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric         while (I != E) {
4240b57cec5SDimitry Andric           if (I->isDebugInstr()) {
4250b57cec5SDimitry Andric             I = std::next(I);
4260b57cec5SDimitry Andric             continue;
4270b57cec5SDimitry Andric           }
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric           if (I->mayStore() || I->isBarrier() || I->isCall() ||
4300b57cec5SDimitry Andric               I->hasUnmodeledSideEffects() || I->hasOrderedMemoryRef())
4310b57cec5SDimitry Andric             break;
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric           LLVM_DEBUG(dbgs()
4340b57cec5SDimitry Andric                      << "Removing no effect instruction: " << *I << '\n');
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric           for (auto &Op : I->operands()) {
4370b57cec5SDimitry Andric             if (Op.isReg())
4380b57cec5SDimitry Andric               RecalcRegs.insert(Op.getReg());
4390b57cec5SDimitry Andric           }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric           auto Next = std::next(I);
4420b57cec5SDimitry Andric           LIS->RemoveMachineInstrFromMaps(*I);
4430b57cec5SDimitry Andric           I->eraseFromParent();
4440b57cec5SDimitry Andric           I = Next;
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric           Changed = true;
4470b57cec5SDimitry Andric         }
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric         if (I != E)
4500b57cec5SDimitry Andric           continue;
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric         // Try to ascend predecessors.
4530b57cec5SDimitry Andric         for (auto *Pred : CurBB->predecessors()) {
4540b57cec5SDimitry Andric           if (Pred->succ_size() == 1)
4550b57cec5SDimitry Andric             Blocks.push_back(Pred);
4560b57cec5SDimitry Andric         }
4570b57cec5SDimitry Andric       }
4580b57cec5SDimitry Andric       continue;
4590b57cec5SDimitry Andric     }
4600b57cec5SDimitry Andric 
4615ffd83dbSDimitry Andric     // If the only user of a logical operation is move to exec, fold it now
46281ad6265SDimitry Andric     // to prevent forming of saveexec. I.e.:
4635ffd83dbSDimitry Andric     //
4645ffd83dbSDimitry Andric     //    %0:sreg_64 = COPY $exec
4655ffd83dbSDimitry Andric     //    %1:sreg_64 = S_AND_B64 %0:sreg_64, %2:sreg_64
4665ffd83dbSDimitry Andric     // =>
4675ffd83dbSDimitry Andric     //    %1 = S_AND_B64 $exec, %2:sreg_64
4685ffd83dbSDimitry Andric     unsigned ScanThreshold = 10;
4695ffd83dbSDimitry Andric     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E
4705ffd83dbSDimitry Andric          && ScanThreshold--; ++I) {
471e8d8bef9SDimitry Andric       // Continue scanning if this is not a full exec copy
472e8d8bef9SDimitry Andric       if (!(I->isFullCopy() && I->getOperand(1).getReg() == Register(ExecReg)))
4730b57cec5SDimitry Andric         continue;
4740b57cec5SDimitry Andric 
4755ffd83dbSDimitry Andric       Register SavedExec = I->getOperand(0).getReg();
476fe6060f1SDimitry Andric       if (SavedExec.isVirtual() && MRI->hasOneNonDBGUse(SavedExec)) {
477fe6060f1SDimitry Andric         MachineInstr *SingleExecUser = &*MRI->use_instr_nodbg_begin(SavedExec);
478fe6060f1SDimitry Andric         int Idx = SingleExecUser->findRegisterUseOperandIdx(SavedExec);
479fe6060f1SDimitry Andric         assert(Idx != -1);
480fe6060f1SDimitry Andric         if (SingleExecUser->getParent() == I->getParent() &&
481fe6060f1SDimitry Andric             !SingleExecUser->getOperand(Idx).isImplicit() &&
482fe6060f1SDimitry Andric             TII->isOperandLegal(*SingleExecUser, Idx, &I->getOperand(1))) {
4835ffd83dbSDimitry Andric           LLVM_DEBUG(dbgs() << "Redundant EXEC COPY: " << *I << '\n');
4845ffd83dbSDimitry Andric           LIS->RemoveMachineInstrFromMaps(*I);
4855ffd83dbSDimitry Andric           I->eraseFromParent();
486e8d8bef9SDimitry Andric           MRI->replaceRegWith(SavedExec, ExecReg);
4870b57cec5SDimitry Andric           LIS->removeInterval(SavedExec);
4885ffd83dbSDimitry Andric           Changed = true;
4895ffd83dbSDimitry Andric         }
490fe6060f1SDimitry Andric       }
4915ffd83dbSDimitry Andric       break;
4920b57cec5SDimitry Andric     }
4930b57cec5SDimitry Andric   }
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   if (Changed) {
4960b57cec5SDimitry Andric     for (auto Reg : RecalcRegs) {
497e8d8bef9SDimitry Andric       if (Reg.isVirtual()) {
4980b57cec5SDimitry Andric         LIS->removeInterval(Reg);
499e8d8bef9SDimitry Andric         if (!MRI->reg_empty(Reg))
5000b57cec5SDimitry Andric           LIS->createAndComputeVirtRegInterval(Reg);
5010b57cec5SDimitry Andric       } else {
5020b57cec5SDimitry Andric         LIS->removeAllRegUnitsForPhysReg(Reg);
5030b57cec5SDimitry Andric       }
5040b57cec5SDimitry Andric     }
5050b57cec5SDimitry Andric   }
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric   return Changed;
5080b57cec5SDimitry Andric }
509