xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/AMDGPU/SIOptimizeExecMaskingPreRA.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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 {
59*0fca6ea1SDimitry Andric     AU.addRequired<LiveIntervalsWrapperPass>();
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)
69*0fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
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 
9906c3fb27SDimitry Andric   for (MCRegUnit Unit : TRI.regunits(Reg.asMCReg())) {
10006c3fb27SDimitry Andric     if (isDefBetween(LIS->getRegUnit(Unit), 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
10906c3fb27SDimitry Andric //    %cmp = V_CMP_NE_U32 1, %sel
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();
162753f127fSDimitry Andric   if (SelReg.isPhysical())
163753f127fSDimitry Andric     return false;
164753f127fSDimitry 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 
187fcaf7f86SDimitry Andric   // Cannot safely mirror live intervals with PHI nodes, so check for these
188fcaf7f86SDimitry Andric   // before optimization.
189fcaf7f86SDimitry Andric   SlotIndex SelIdx = LIS->getInstructionIndex(*Sel);
190fcaf7f86SDimitry Andric   LiveInterval *SelLI = &LIS->getInterval(SelReg);
191fcaf7f86SDimitry Andric   if (llvm::any_of(SelLI->vnis(),
192fcaf7f86SDimitry Andric                     [](const VNInfo *VNI) {
193fcaf7f86SDimitry Andric                       return VNI->isPHIDef();
194fcaf7f86SDimitry Andric                     }))
195fcaf7f86SDimitry Andric     return false;
196fcaf7f86SDimitry Andric 
19781ad6265SDimitry Andric   // TODO: Guard against implicit def operands?
1988bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << "Folding sequence:\n\t" << *Sel << '\t' << *Cmp << '\t'
1998bcb0991SDimitry Andric                     << *And);
2000b57cec5SDimitry Andric 
2018bcb0991SDimitry Andric   MachineInstr *Andn2 =
2028bcb0991SDimitry Andric       BuildMI(MBB, *And, And->getDebugLoc(), TII->get(Andn2Opc),
2038bcb0991SDimitry Andric               And->getOperand(0).getReg())
2040b57cec5SDimitry Andric           .addReg(ExecReg)
2058bcb0991SDimitry Andric           .addReg(CCReg, getUndefRegState(CC->isUndef()), CC->getSubReg());
2065ffd83dbSDimitry Andric   MachineOperand &AndSCC = And->getOperand(3);
2075ffd83dbSDimitry Andric   assert(AndSCC.getReg() == AMDGPU::SCC);
2085ffd83dbSDimitry Andric   MachineOperand &Andn2SCC = Andn2->getOperand(3);
2095ffd83dbSDimitry Andric   assert(Andn2SCC.getReg() == AMDGPU::SCC);
2105ffd83dbSDimitry Andric   Andn2SCC.setIsDead(AndSCC.isDead());
21181ad6265SDimitry Andric 
21281ad6265SDimitry Andric   SlotIndex AndIdx = LIS->ReplaceMachineInstrInMaps(*And, *Andn2);
2130b57cec5SDimitry Andric   And->eraseFromParent();
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "=>\n\t" << *Andn2 << '\n');
2160b57cec5SDimitry Andric 
21781ad6265SDimitry Andric   // Update live intervals for CCReg before potentially removing CmpReg/SelReg,
21881ad6265SDimitry Andric   // and their associated liveness information.
219fcaf7f86SDimitry Andric   SlotIndex CmpIdx = LIS->getInstructionIndex(*Cmp);
22081ad6265SDimitry Andric   if (CCReg.isVirtual()) {
22181ad6265SDimitry Andric     LiveInterval &CCLI = LIS->getInterval(CCReg);
22281ad6265SDimitry Andric     auto CCQ = CCLI.Query(SelIdx.getRegSlot());
22306c3fb27SDimitry Andric     if (CCQ.valueIn()) {
22406c3fb27SDimitry Andric       LIS->removeInterval(CCReg);
22506c3fb27SDimitry Andric       LIS->createAndComputeVirtRegInterval(CCReg);
22681ad6265SDimitry Andric     }
22781ad6265SDimitry Andric   } else
22881ad6265SDimitry Andric     LIS->removeAllRegUnitsForPhysReg(CCReg);
22981ad6265SDimitry Andric 
2300b57cec5SDimitry Andric   // Try to remove compare. Cmp value should not used in between of cmp
2310b57cec5SDimitry Andric   // and s_and_b64 if VCC or just unused if any other register.
232fcaf7f86SDimitry Andric   LiveInterval *CmpLI = CmpReg.isVirtual() ? &LIS->getInterval(CmpReg) : nullptr;
233fcaf7f86SDimitry Andric   if ((CmpLI && CmpLI->Query(AndIdx.getRegSlot()).isKill()) ||
234e8d8bef9SDimitry Andric       (CmpReg == Register(CondReg) &&
2350b57cec5SDimitry Andric        std::none_of(std::next(Cmp->getIterator()), Andn2->getIterator(),
2360b57cec5SDimitry Andric                     [&](const MachineInstr &MI) {
2378bcb0991SDimitry Andric                       return MI.readsRegister(CondReg, TRI);
2388bcb0991SDimitry Andric                     }))) {
2390b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Erasing: " << *Cmp << '\n');
24081ad6265SDimitry Andric     if (CmpLI)
24181ad6265SDimitry Andric       LIS->removeVRegDefAt(*CmpLI, CmpIdx.getRegSlot());
2420b57cec5SDimitry Andric     LIS->RemoveMachineInstrFromMaps(*Cmp);
2430b57cec5SDimitry Andric     Cmp->eraseFromParent();
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric     // Try to remove v_cndmask_b32.
246753f127fSDimitry Andric     // Kill status must be checked before shrinking the live range.
247753f127fSDimitry Andric     bool IsKill = SelLI->Query(CmpIdx.getRegSlot()).isKill();
248753f127fSDimitry Andric     LIS->shrinkToUses(SelLI);
249753f127fSDimitry Andric     bool IsDead = SelLI->Query(SelIdx.getRegSlot()).isDeadDef();
250753f127fSDimitry Andric     if (MRI->use_nodbg_empty(SelReg) && (IsKill || IsDead)) {
2510b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Erasing: " << *Sel << '\n');
2520b57cec5SDimitry Andric 
25381ad6265SDimitry Andric       LIS->removeVRegDefAt(*SelLI, SelIdx.getRegSlot());
2540b57cec5SDimitry Andric       LIS->RemoveMachineInstrFromMaps(*Sel);
25506c3fb27SDimitry Andric       bool ShrinkSel = Sel->getOperand(0).readsReg();
2560b57cec5SDimitry Andric       Sel->eraseFromParent();
25706c3fb27SDimitry Andric       if (ShrinkSel) {
25806c3fb27SDimitry Andric         // The result of the V_CNDMASK was a subreg def which counted as a read
25906c3fb27SDimitry Andric         // from the other parts of the reg. Shrink their live ranges.
26006c3fb27SDimitry Andric         LIS->shrinkToUses(SelLI);
26106c3fb27SDimitry Andric       }
2620b57cec5SDimitry Andric     }
2630b57cec5SDimitry Andric   }
2640b57cec5SDimitry Andric 
26581ad6265SDimitry Andric   return true;
2660b57cec5SDimitry Andric }
2670b57cec5SDimitry Andric 
268e8d8bef9SDimitry Andric // Optimize sequence
269e8d8bef9SDimitry Andric //    %dst = S_OR_SAVEEXEC %src
270e8d8bef9SDimitry Andric //    ... instructions not modifying exec ...
271e8d8bef9SDimitry Andric //    %tmp = S_AND $exec, %dst
272e8d8bef9SDimitry Andric //    $exec = S_XOR_term $exec, %tmp
273e8d8bef9SDimitry Andric // =>
274e8d8bef9SDimitry Andric //    %dst = S_OR_SAVEEXEC %src
275e8d8bef9SDimitry Andric //    ... instructions not modifying exec ...
276e8d8bef9SDimitry Andric //    $exec = S_XOR_term $exec, %dst
277e8d8bef9SDimitry Andric //
278e8d8bef9SDimitry Andric // Clean up potentially unnecessary code added for safety during
279e8d8bef9SDimitry Andric // control flow lowering.
280e8d8bef9SDimitry Andric //
281e8d8bef9SDimitry Andric // Return whether any changes were made to MBB.
282e8d8bef9SDimitry Andric bool SIOptimizeExecMaskingPreRA::optimizeElseBranch(MachineBasicBlock &MBB) {
283e8d8bef9SDimitry Andric   if (MBB.empty())
284e8d8bef9SDimitry Andric     return false;
285e8d8bef9SDimitry Andric 
286e8d8bef9SDimitry Andric   // Check this is an else block.
287e8d8bef9SDimitry Andric   auto First = MBB.begin();
288e8d8bef9SDimitry Andric   MachineInstr &SaveExecMI = *First;
289e8d8bef9SDimitry Andric   if (SaveExecMI.getOpcode() != OrSaveExecOpc)
290e8d8bef9SDimitry Andric     return false;
291e8d8bef9SDimitry Andric 
292e8d8bef9SDimitry Andric   auto I = llvm::find_if(MBB.terminators(), [this](const MachineInstr &MI) {
293e8d8bef9SDimitry Andric     return MI.getOpcode() == XorTermrOpc;
294e8d8bef9SDimitry Andric   });
295e8d8bef9SDimitry Andric   if (I == MBB.terminators().end())
296e8d8bef9SDimitry Andric     return false;
297e8d8bef9SDimitry Andric 
298e8d8bef9SDimitry Andric   MachineInstr &XorTermMI = *I;
299e8d8bef9SDimitry Andric   if (XorTermMI.getOperand(1).getReg() != Register(ExecReg))
300e8d8bef9SDimitry Andric     return false;
301e8d8bef9SDimitry Andric 
302e8d8bef9SDimitry Andric   Register SavedExecReg = SaveExecMI.getOperand(0).getReg();
303e8d8bef9SDimitry Andric   Register DstReg = XorTermMI.getOperand(2).getReg();
304e8d8bef9SDimitry Andric 
305e8d8bef9SDimitry Andric   // Find potentially unnecessary S_AND
306e8d8bef9SDimitry Andric   MachineInstr *AndExecMI = nullptr;
307e8d8bef9SDimitry Andric   I--;
308e8d8bef9SDimitry Andric   while (I != First && !AndExecMI) {
309e8d8bef9SDimitry Andric     if (I->getOpcode() == AndOpc && I->getOperand(0).getReg() == DstReg &&
310e8d8bef9SDimitry Andric         I->getOperand(1).getReg() == Register(ExecReg))
311e8d8bef9SDimitry Andric       AndExecMI = &*I;
312e8d8bef9SDimitry Andric     I--;
313e8d8bef9SDimitry Andric   }
314e8d8bef9SDimitry Andric   if (!AndExecMI)
315e8d8bef9SDimitry Andric     return false;
316e8d8bef9SDimitry Andric 
317e8d8bef9SDimitry Andric   // Check for exec modifying instructions.
318e8d8bef9SDimitry Andric   // Note: exec defs do not create live ranges beyond the
319e8d8bef9SDimitry Andric   // instruction so isDefBetween cannot be used.
320e8d8bef9SDimitry Andric   // Instead just check that the def segments are adjacent.
321e8d8bef9SDimitry Andric   SlotIndex StartIdx = LIS->getInstructionIndex(SaveExecMI);
322e8d8bef9SDimitry Andric   SlotIndex EndIdx = LIS->getInstructionIndex(*AndExecMI);
32306c3fb27SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(ExecReg)) {
32406c3fb27SDimitry Andric     LiveRange &RegUnit = LIS->getRegUnit(Unit);
325e8d8bef9SDimitry Andric     if (RegUnit.find(StartIdx) != std::prev(RegUnit.find(EndIdx)))
326e8d8bef9SDimitry Andric       return false;
327e8d8bef9SDimitry Andric   }
328e8d8bef9SDimitry Andric 
329e8d8bef9SDimitry Andric   // Remove unnecessary S_AND
330e8d8bef9SDimitry Andric   LIS->removeInterval(SavedExecReg);
331e8d8bef9SDimitry Andric   LIS->removeInterval(DstReg);
332e8d8bef9SDimitry Andric 
333e8d8bef9SDimitry Andric   SaveExecMI.getOperand(0).setReg(DstReg);
334e8d8bef9SDimitry Andric 
335e8d8bef9SDimitry Andric   LIS->RemoveMachineInstrFromMaps(*AndExecMI);
336e8d8bef9SDimitry Andric   AndExecMI->eraseFromParent();
337e8d8bef9SDimitry Andric 
338e8d8bef9SDimitry Andric   LIS->createAndComputeVirtRegInterval(DstReg);
339e8d8bef9SDimitry Andric 
340e8d8bef9SDimitry Andric   return true;
341e8d8bef9SDimitry Andric }
342e8d8bef9SDimitry Andric 
3430b57cec5SDimitry Andric bool SIOptimizeExecMaskingPreRA::runOnMachineFunction(MachineFunction &MF) {
3440b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()))
3450b57cec5SDimitry Andric     return false;
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3480b57cec5SDimitry Andric   TRI = ST.getRegisterInfo();
3490b57cec5SDimitry Andric   TII = ST.getInstrInfo();
3500b57cec5SDimitry Andric   MRI = &MF.getRegInfo();
351*0fca6ea1SDimitry Andric   LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
3520b57cec5SDimitry Andric 
353e8d8bef9SDimitry Andric   const bool Wave32 = ST.isWave32();
354e8d8bef9SDimitry Andric   AndOpc = Wave32 ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
355e8d8bef9SDimitry Andric   Andn2Opc = Wave32 ? AMDGPU::S_ANDN2_B32 : AMDGPU::S_ANDN2_B64;
356e8d8bef9SDimitry Andric   OrSaveExecOpc =
357e8d8bef9SDimitry Andric       Wave32 ? AMDGPU::S_OR_SAVEEXEC_B32 : AMDGPU::S_OR_SAVEEXEC_B64;
358e8d8bef9SDimitry Andric   XorTermrOpc = Wave32 ? AMDGPU::S_XOR_B32_term : AMDGPU::S_XOR_B64_term;
359e8d8bef9SDimitry Andric   CondReg = MCRegister::from(Wave32 ? AMDGPU::VCC_LO : AMDGPU::VCC);
360e8d8bef9SDimitry Andric   ExecReg = MCRegister::from(Wave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC);
361e8d8bef9SDimitry Andric 
362e8d8bef9SDimitry Andric   DenseSet<Register> RecalcRegs({AMDGPU::EXEC_LO, AMDGPU::EXEC_HI});
3630b57cec5SDimitry Andric   bool Changed = false;
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
3660b57cec5SDimitry Andric 
367e8d8bef9SDimitry Andric     if (optimizeElseBranch(MBB)) {
368e8d8bef9SDimitry Andric       RecalcRegs.insert(AMDGPU::SCC);
369e8d8bef9SDimitry Andric       Changed = true;
370e8d8bef9SDimitry Andric     }
371e8d8bef9SDimitry Andric 
37281ad6265SDimitry Andric     if (optimizeVcndVcmpPair(MBB)) {
3730b57cec5SDimitry Andric       RecalcRegs.insert(AMDGPU::VCC_LO);
3740b57cec5SDimitry Andric       RecalcRegs.insert(AMDGPU::VCC_HI);
3750b57cec5SDimitry Andric       RecalcRegs.insert(AMDGPU::SCC);
3760b57cec5SDimitry Andric       Changed = true;
3770b57cec5SDimitry Andric     }
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric     // Try to remove unneeded instructions before s_endpgm.
3800b57cec5SDimitry Andric     if (MBB.succ_empty()) {
3810b57cec5SDimitry Andric       if (MBB.empty())
3820b57cec5SDimitry Andric         continue;
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric       // Skip this if the endpgm has any implicit uses, otherwise we would need
3850b57cec5SDimitry Andric       // to be careful to update / remove them.
3860b57cec5SDimitry Andric       // S_ENDPGM always has a single imm operand that is not used other than to
3870b57cec5SDimitry Andric       // end up in the encoding
3880b57cec5SDimitry Andric       MachineInstr &Term = MBB.back();
3890b57cec5SDimitry Andric       if (Term.getOpcode() != AMDGPU::S_ENDPGM || Term.getNumOperands() != 1)
3900b57cec5SDimitry Andric         continue;
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric       SmallVector<MachineBasicBlock*, 4> Blocks({&MBB});
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric       while (!Blocks.empty()) {
3950b57cec5SDimitry Andric         auto CurBB = Blocks.pop_back_val();
3960b57cec5SDimitry Andric         auto I = CurBB->rbegin(), E = CurBB->rend();
3970b57cec5SDimitry Andric         if (I != E) {
3980b57cec5SDimitry Andric           if (I->isUnconditionalBranch() || I->getOpcode() == AMDGPU::S_ENDPGM)
3990b57cec5SDimitry Andric             ++I;
4000b57cec5SDimitry Andric           else if (I->isBranch())
4010b57cec5SDimitry Andric             continue;
4020b57cec5SDimitry Andric         }
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric         while (I != E) {
4050b57cec5SDimitry Andric           if (I->isDebugInstr()) {
4060b57cec5SDimitry Andric             I = std::next(I);
4070b57cec5SDimitry Andric             continue;
4080b57cec5SDimitry Andric           }
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric           if (I->mayStore() || I->isBarrier() || I->isCall() ||
4110b57cec5SDimitry Andric               I->hasUnmodeledSideEffects() || I->hasOrderedMemoryRef())
4120b57cec5SDimitry Andric             break;
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric           LLVM_DEBUG(dbgs()
4150b57cec5SDimitry Andric                      << "Removing no effect instruction: " << *I << '\n');
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric           for (auto &Op : I->operands()) {
4180b57cec5SDimitry Andric             if (Op.isReg())
4190b57cec5SDimitry Andric               RecalcRegs.insert(Op.getReg());
4200b57cec5SDimitry Andric           }
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric           auto Next = std::next(I);
4230b57cec5SDimitry Andric           LIS->RemoveMachineInstrFromMaps(*I);
4240b57cec5SDimitry Andric           I->eraseFromParent();
4250b57cec5SDimitry Andric           I = Next;
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric           Changed = true;
4280b57cec5SDimitry Andric         }
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric         if (I != E)
4310b57cec5SDimitry Andric           continue;
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric         // Try to ascend predecessors.
4340b57cec5SDimitry Andric         for (auto *Pred : CurBB->predecessors()) {
4350b57cec5SDimitry Andric           if (Pred->succ_size() == 1)
4360b57cec5SDimitry Andric             Blocks.push_back(Pred);
4370b57cec5SDimitry Andric         }
4380b57cec5SDimitry Andric       }
4390b57cec5SDimitry Andric       continue;
4400b57cec5SDimitry Andric     }
4410b57cec5SDimitry Andric 
4425ffd83dbSDimitry Andric     // If the only user of a logical operation is move to exec, fold it now
44381ad6265SDimitry Andric     // to prevent forming of saveexec. I.e.:
4445ffd83dbSDimitry Andric     //
4455ffd83dbSDimitry Andric     //    %0:sreg_64 = COPY $exec
4465ffd83dbSDimitry Andric     //    %1:sreg_64 = S_AND_B64 %0:sreg_64, %2:sreg_64
4475ffd83dbSDimitry Andric     // =>
4485ffd83dbSDimitry Andric     //    %1 = S_AND_B64 $exec, %2:sreg_64
4495ffd83dbSDimitry Andric     unsigned ScanThreshold = 10;
4505ffd83dbSDimitry Andric     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E
4515ffd83dbSDimitry Andric          && ScanThreshold--; ++I) {
452e8d8bef9SDimitry Andric       // Continue scanning if this is not a full exec copy
453e8d8bef9SDimitry Andric       if (!(I->isFullCopy() && I->getOperand(1).getReg() == Register(ExecReg)))
4540b57cec5SDimitry Andric         continue;
4550b57cec5SDimitry Andric 
4565ffd83dbSDimitry Andric       Register SavedExec = I->getOperand(0).getReg();
457fe6060f1SDimitry Andric       if (SavedExec.isVirtual() && MRI->hasOneNonDBGUse(SavedExec)) {
458fe6060f1SDimitry Andric         MachineInstr *SingleExecUser = &*MRI->use_instr_nodbg_begin(SavedExec);
459*0fca6ea1SDimitry Andric         int Idx = SingleExecUser->findRegisterUseOperandIdx(SavedExec,
460*0fca6ea1SDimitry Andric                                                             /*TRI=*/nullptr);
461fe6060f1SDimitry Andric         assert(Idx != -1);
462fe6060f1SDimitry Andric         if (SingleExecUser->getParent() == I->getParent() &&
463fe6060f1SDimitry Andric             !SingleExecUser->getOperand(Idx).isImplicit() &&
464fe6060f1SDimitry Andric             TII->isOperandLegal(*SingleExecUser, Idx, &I->getOperand(1))) {
4655ffd83dbSDimitry Andric           LLVM_DEBUG(dbgs() << "Redundant EXEC COPY: " << *I << '\n');
4665ffd83dbSDimitry Andric           LIS->RemoveMachineInstrFromMaps(*I);
4675ffd83dbSDimitry Andric           I->eraseFromParent();
468e8d8bef9SDimitry Andric           MRI->replaceRegWith(SavedExec, ExecReg);
4690b57cec5SDimitry Andric           LIS->removeInterval(SavedExec);
4705ffd83dbSDimitry Andric           Changed = true;
4715ffd83dbSDimitry Andric         }
472fe6060f1SDimitry Andric       }
4735ffd83dbSDimitry Andric       break;
4740b57cec5SDimitry Andric     }
4750b57cec5SDimitry Andric   }
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   if (Changed) {
4780b57cec5SDimitry Andric     for (auto Reg : RecalcRegs) {
479e8d8bef9SDimitry Andric       if (Reg.isVirtual()) {
4800b57cec5SDimitry Andric         LIS->removeInterval(Reg);
481e8d8bef9SDimitry Andric         if (!MRI->reg_empty(Reg))
4820b57cec5SDimitry Andric           LIS->createAndComputeVirtRegInterval(Reg);
4830b57cec5SDimitry Andric       } else {
4840b57cec5SDimitry Andric         LIS->removeAllRegUnitsForPhysReg(Reg);
4850b57cec5SDimitry Andric       }
4860b57cec5SDimitry Andric     }
4870b57cec5SDimitry Andric   }
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric   return Changed;
4900b57cec5SDimitry Andric }
491