1 //===-- SIOptimizeExecMaskingPreRA.cpp ------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// This pass performs exec mask handling peephole optimizations which needs 11 /// to be done before register allocation to reduce register pressure. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "AMDGPU.h" 16 #include "GCNSubtarget.h" 17 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 18 #include "llvm/CodeGen/LiveIntervals.h" 19 #include "llvm/CodeGen/MachineFunctionPass.h" 20 #include "llvm/InitializePasses.h" 21 22 using namespace llvm; 23 24 #define DEBUG_TYPE "si-optimize-exec-masking-pre-ra" 25 26 namespace { 27 28 class SIOptimizeExecMaskingPreRA : public MachineFunctionPass { 29 private: 30 const SIRegisterInfo *TRI; 31 const SIInstrInfo *TII; 32 MachineRegisterInfo *MRI; 33 LiveIntervals *LIS; 34 35 unsigned AndOpc; 36 unsigned Andn2Opc; 37 unsigned OrSaveExecOpc; 38 unsigned XorTermrOpc; 39 MCRegister CondReg; 40 MCRegister ExecReg; 41 42 bool optimizeVcndVcmpPair(MachineBasicBlock &MBB); 43 bool optimizeElseBranch(MachineBasicBlock &MBB); 44 45 public: 46 static char ID; 47 48 SIOptimizeExecMaskingPreRA() : MachineFunctionPass(ID) { 49 initializeSIOptimizeExecMaskingPreRAPass(*PassRegistry::getPassRegistry()); 50 } 51 52 bool runOnMachineFunction(MachineFunction &MF) override; 53 54 StringRef getPassName() const override { 55 return "SI optimize exec mask operations pre-RA"; 56 } 57 58 void getAnalysisUsage(AnalysisUsage &AU) const override { 59 AU.addRequired<LiveIntervals>(); 60 AU.setPreservesAll(); 61 MachineFunctionPass::getAnalysisUsage(AU); 62 } 63 }; 64 65 } // End anonymous namespace. 66 67 INITIALIZE_PASS_BEGIN(SIOptimizeExecMaskingPreRA, DEBUG_TYPE, 68 "SI optimize exec mask operations pre-RA", false, false) 69 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 70 INITIALIZE_PASS_END(SIOptimizeExecMaskingPreRA, DEBUG_TYPE, 71 "SI optimize exec mask operations pre-RA", false, false) 72 73 char SIOptimizeExecMaskingPreRA::ID = 0; 74 75 char &llvm::SIOptimizeExecMaskingPreRAID = SIOptimizeExecMaskingPreRA::ID; 76 77 FunctionPass *llvm::createSIOptimizeExecMaskingPreRAPass() { 78 return new SIOptimizeExecMaskingPreRA(); 79 } 80 81 // See if there is a def between \p AndIdx and \p SelIdx that needs to live 82 // beyond \p AndIdx. 83 static bool isDefBetween(const LiveRange &LR, SlotIndex AndIdx, 84 SlotIndex SelIdx) { 85 LiveQueryResult AndLRQ = LR.Query(AndIdx); 86 return (!AndLRQ.isKill() && AndLRQ.valueIn() != LR.Query(SelIdx).valueOut()); 87 } 88 89 // FIXME: Why do we bother trying to handle physical registers here? 90 static bool isDefBetween(const SIRegisterInfo &TRI, 91 LiveIntervals *LIS, Register Reg, 92 const MachineInstr &Sel, const MachineInstr &And) { 93 SlotIndex AndIdx = LIS->getInstructionIndex(And).getRegSlot(); 94 SlotIndex SelIdx = LIS->getInstructionIndex(Sel).getRegSlot(); 95 96 if (Reg.isVirtual()) 97 return isDefBetween(LIS->getInterval(Reg), AndIdx, SelIdx); 98 99 for (MCRegUnitIterator UI(Reg.asMCReg(), &TRI); UI.isValid(); ++UI) { 100 if (isDefBetween(LIS->getRegUnit(*UI), AndIdx, SelIdx)) 101 return true; 102 } 103 104 return false; 105 } 106 107 // Optimize sequence 108 // %sel = V_CNDMASK_B32_e64 0, 1, %cc 109 // %cmp = V_CMP_NE_U32 1, %1 110 // $vcc = S_AND_B64 $exec, %cmp 111 // S_CBRANCH_VCC[N]Z 112 // => 113 // $vcc = S_ANDN2_B64 $exec, %cc 114 // S_CBRANCH_VCC[N]Z 115 // 116 // It is the negation pattern inserted by DAGCombiner::visitBRCOND() in the 117 // rebuildSetCC(). We start with S_CBRANCH to avoid exhaustive search, but 118 // only 3 first instructions are really needed. S_AND_B64 with exec is a 119 // required part of the pattern since V_CNDMASK_B32 writes zeroes for inactive 120 // lanes. 121 // 122 // Returns true on success. 123 bool SIOptimizeExecMaskingPreRA::optimizeVcndVcmpPair(MachineBasicBlock &MBB) { 124 auto I = llvm::find_if(MBB.terminators(), [](const MachineInstr &MI) { 125 unsigned Opc = MI.getOpcode(); 126 return Opc == AMDGPU::S_CBRANCH_VCCZ || 127 Opc == AMDGPU::S_CBRANCH_VCCNZ; }); 128 if (I == MBB.terminators().end()) 129 return false; 130 131 auto *And = 132 TRI->findReachingDef(CondReg, AMDGPU::NoSubRegister, *I, *MRI, LIS); 133 if (!And || And->getOpcode() != AndOpc || 134 !And->getOperand(1).isReg() || !And->getOperand(2).isReg()) 135 return false; 136 137 MachineOperand *AndCC = &And->getOperand(1); 138 Register CmpReg = AndCC->getReg(); 139 unsigned CmpSubReg = AndCC->getSubReg(); 140 if (CmpReg == Register(ExecReg)) { 141 AndCC = &And->getOperand(2); 142 CmpReg = AndCC->getReg(); 143 CmpSubReg = AndCC->getSubReg(); 144 } else if (And->getOperand(2).getReg() != Register(ExecReg)) { 145 return false; 146 } 147 148 auto *Cmp = TRI->findReachingDef(CmpReg, CmpSubReg, *And, *MRI, LIS); 149 if (!Cmp || !(Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e32 || 150 Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e64) || 151 Cmp->getParent() != And->getParent()) 152 return false; 153 154 MachineOperand *Op1 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src0); 155 MachineOperand *Op2 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src1); 156 if (Op1->isImm() && Op2->isReg()) 157 std::swap(Op1, Op2); 158 if (!Op1->isReg() || !Op2->isImm() || Op2->getImm() != 1) 159 return false; 160 161 Register SelReg = Op1->getReg(); 162 if (SelReg.isPhysical()) 163 return false; 164 165 auto *Sel = TRI->findReachingDef(SelReg, Op1->getSubReg(), *Cmp, *MRI, LIS); 166 if (!Sel || Sel->getOpcode() != AMDGPU::V_CNDMASK_B32_e64) 167 return false; 168 169 if (TII->hasModifiersSet(*Sel, AMDGPU::OpName::src0_modifiers) || 170 TII->hasModifiersSet(*Sel, AMDGPU::OpName::src1_modifiers)) 171 return false; 172 173 Op1 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src0); 174 Op2 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src1); 175 MachineOperand *CC = TII->getNamedOperand(*Sel, AMDGPU::OpName::src2); 176 if (!Op1->isImm() || !Op2->isImm() || !CC->isReg() || 177 Op1->getImm() != 0 || Op2->getImm() != 1) 178 return false; 179 180 Register CCReg = CC->getReg(); 181 182 // If there was a def between the select and the and, we would need to move it 183 // to fold this. 184 if (isDefBetween(*TRI, LIS, CCReg, *Sel, *And)) 185 return false; 186 187 // TODO: Guard against implicit def operands? 188 LLVM_DEBUG(dbgs() << "Folding sequence:\n\t" << *Sel << '\t' << *Cmp << '\t' 189 << *And); 190 191 MachineInstr *Andn2 = 192 BuildMI(MBB, *And, And->getDebugLoc(), TII->get(Andn2Opc), 193 And->getOperand(0).getReg()) 194 .addReg(ExecReg) 195 .addReg(CCReg, getUndefRegState(CC->isUndef()), CC->getSubReg()); 196 MachineOperand &AndSCC = And->getOperand(3); 197 assert(AndSCC.getReg() == AMDGPU::SCC); 198 MachineOperand &Andn2SCC = Andn2->getOperand(3); 199 assert(Andn2SCC.getReg() == AMDGPU::SCC); 200 Andn2SCC.setIsDead(AndSCC.isDead()); 201 202 SlotIndex AndIdx = LIS->ReplaceMachineInstrInMaps(*And, *Andn2); 203 And->eraseFromParent(); 204 205 LLVM_DEBUG(dbgs() << "=>\n\t" << *Andn2 << '\n'); 206 207 SlotIndex CmpIdx = LIS->getInstructionIndex(*Cmp); 208 SlotIndex SelIdx = LIS->getInstructionIndex(*Sel); 209 210 LiveInterval *CmpLI = 211 CmpReg.isVirtual() ? &LIS->getInterval(CmpReg) : nullptr; 212 LiveInterval *SelLI = 213 SelReg.isVirtual() ? &LIS->getInterval(SelReg) : nullptr; 214 215 // Update live intervals for CCReg before potentially removing CmpReg/SelReg, 216 // and their associated liveness information. 217 if (CCReg.isVirtual()) { 218 // Note: this ignores that SelLI might have multiple internal values 219 // or splits and simply extends the live range to cover all cases 220 // where the result of the v_cndmask_b32 was live (e.g. loops). 221 // This could yield worse register allocation in rare edge cases. 222 SlotIndex EndIdx = AndIdx.getRegSlot(); 223 if (SelLI && SelLI->endIndex() > EndIdx && SelLI->endIndex().isBlock()) 224 EndIdx = SelLI->endIndex(); 225 226 LiveInterval &CCLI = LIS->getInterval(CCReg); 227 auto CCQ = CCLI.Query(SelIdx.getRegSlot()); 228 if (CCQ.valueIn()) { 229 CCLI.addSegment(LiveRange::Segment(SelIdx.getRegSlot(), 230 EndIdx, CCQ.valueIn())); 231 } 232 233 if (CC->getSubReg()) { 234 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(CC->getSubReg()); 235 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator(); 236 CCLI.refineSubRanges( 237 Allocator, Mask, 238 [=](LiveInterval::SubRange &SR) { 239 auto CCQS = SR.Query(SelIdx.getRegSlot()); 240 if (CCQS.valueIn()) { 241 SR.addSegment(LiveRange::Segment( 242 SelIdx.getRegSlot(), EndIdx, CCQS.valueIn())); 243 } 244 }, 245 *LIS->getSlotIndexes(), *TRI); 246 CCLI.removeEmptySubRanges(); 247 248 SmallVector<LiveInterval *> SplitLIs; 249 LIS->splitSeparateComponents(CCLI, SplitLIs); 250 } 251 } else 252 LIS->removeAllRegUnitsForPhysReg(CCReg); 253 254 // Try to remove compare. Cmp value should not used in between of cmp 255 // and s_and_b64 if VCC or just unused if any other register. 256 if ((CmpReg.isVirtual() && CmpLI && CmpLI->Query(AndIdx.getRegSlot()).isKill()) || 257 (CmpReg == Register(CondReg) && 258 std::none_of(std::next(Cmp->getIterator()), Andn2->getIterator(), 259 [&](const MachineInstr &MI) { 260 return MI.readsRegister(CondReg, TRI); 261 }))) { 262 LLVM_DEBUG(dbgs() << "Erasing: " << *Cmp << '\n'); 263 if (CmpLI) 264 LIS->removeVRegDefAt(*CmpLI, CmpIdx.getRegSlot()); 265 LIS->RemoveMachineInstrFromMaps(*Cmp); 266 Cmp->eraseFromParent(); 267 268 // Try to remove v_cndmask_b32. 269 if (SelLI) { 270 // Kill status must be checked before shrinking the live range. 271 bool IsKill = SelLI->Query(CmpIdx.getRegSlot()).isKill(); 272 LIS->shrinkToUses(SelLI); 273 bool IsDead = SelLI->Query(SelIdx.getRegSlot()).isDeadDef(); 274 if (MRI->use_nodbg_empty(SelReg) && (IsKill || IsDead)) { 275 LLVM_DEBUG(dbgs() << "Erasing: " << *Sel << '\n'); 276 277 LIS->removeVRegDefAt(*SelLI, SelIdx.getRegSlot()); 278 LIS->RemoveMachineInstrFromMaps(*Sel); 279 Sel->eraseFromParent(); 280 } 281 } 282 } 283 284 return true; 285 } 286 287 // Optimize sequence 288 // %dst = S_OR_SAVEEXEC %src 289 // ... instructions not modifying exec ... 290 // %tmp = S_AND $exec, %dst 291 // $exec = S_XOR_term $exec, %tmp 292 // => 293 // %dst = S_OR_SAVEEXEC %src 294 // ... instructions not modifying exec ... 295 // $exec = S_XOR_term $exec, %dst 296 // 297 // Clean up potentially unnecessary code added for safety during 298 // control flow lowering. 299 // 300 // Return whether any changes were made to MBB. 301 bool SIOptimizeExecMaskingPreRA::optimizeElseBranch(MachineBasicBlock &MBB) { 302 if (MBB.empty()) 303 return false; 304 305 // Check this is an else block. 306 auto First = MBB.begin(); 307 MachineInstr &SaveExecMI = *First; 308 if (SaveExecMI.getOpcode() != OrSaveExecOpc) 309 return false; 310 311 auto I = llvm::find_if(MBB.terminators(), [this](const MachineInstr &MI) { 312 return MI.getOpcode() == XorTermrOpc; 313 }); 314 if (I == MBB.terminators().end()) 315 return false; 316 317 MachineInstr &XorTermMI = *I; 318 if (XorTermMI.getOperand(1).getReg() != Register(ExecReg)) 319 return false; 320 321 Register SavedExecReg = SaveExecMI.getOperand(0).getReg(); 322 Register DstReg = XorTermMI.getOperand(2).getReg(); 323 324 // Find potentially unnecessary S_AND 325 MachineInstr *AndExecMI = nullptr; 326 I--; 327 while (I != First && !AndExecMI) { 328 if (I->getOpcode() == AndOpc && I->getOperand(0).getReg() == DstReg && 329 I->getOperand(1).getReg() == Register(ExecReg)) 330 AndExecMI = &*I; 331 I--; 332 } 333 if (!AndExecMI) 334 return false; 335 336 // Check for exec modifying instructions. 337 // Note: exec defs do not create live ranges beyond the 338 // instruction so isDefBetween cannot be used. 339 // Instead just check that the def segments are adjacent. 340 SlotIndex StartIdx = LIS->getInstructionIndex(SaveExecMI); 341 SlotIndex EndIdx = LIS->getInstructionIndex(*AndExecMI); 342 for (MCRegUnitIterator UI(ExecReg, TRI); UI.isValid(); ++UI) { 343 LiveRange &RegUnit = LIS->getRegUnit(*UI); 344 if (RegUnit.find(StartIdx) != std::prev(RegUnit.find(EndIdx))) 345 return false; 346 } 347 348 // Remove unnecessary S_AND 349 LIS->removeInterval(SavedExecReg); 350 LIS->removeInterval(DstReg); 351 352 SaveExecMI.getOperand(0).setReg(DstReg); 353 354 LIS->RemoveMachineInstrFromMaps(*AndExecMI); 355 AndExecMI->eraseFromParent(); 356 357 LIS->createAndComputeVirtRegInterval(DstReg); 358 359 return true; 360 } 361 362 bool SIOptimizeExecMaskingPreRA::runOnMachineFunction(MachineFunction &MF) { 363 if (skipFunction(MF.getFunction())) 364 return false; 365 366 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 367 TRI = ST.getRegisterInfo(); 368 TII = ST.getInstrInfo(); 369 MRI = &MF.getRegInfo(); 370 LIS = &getAnalysis<LiveIntervals>(); 371 372 const bool Wave32 = ST.isWave32(); 373 AndOpc = Wave32 ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64; 374 Andn2Opc = Wave32 ? AMDGPU::S_ANDN2_B32 : AMDGPU::S_ANDN2_B64; 375 OrSaveExecOpc = 376 Wave32 ? AMDGPU::S_OR_SAVEEXEC_B32 : AMDGPU::S_OR_SAVEEXEC_B64; 377 XorTermrOpc = Wave32 ? AMDGPU::S_XOR_B32_term : AMDGPU::S_XOR_B64_term; 378 CondReg = MCRegister::from(Wave32 ? AMDGPU::VCC_LO : AMDGPU::VCC); 379 ExecReg = MCRegister::from(Wave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC); 380 381 DenseSet<Register> RecalcRegs({AMDGPU::EXEC_LO, AMDGPU::EXEC_HI}); 382 bool Changed = false; 383 384 for (MachineBasicBlock &MBB : MF) { 385 386 if (optimizeElseBranch(MBB)) { 387 RecalcRegs.insert(AMDGPU::SCC); 388 Changed = true; 389 } 390 391 if (optimizeVcndVcmpPair(MBB)) { 392 RecalcRegs.insert(AMDGPU::VCC_LO); 393 RecalcRegs.insert(AMDGPU::VCC_HI); 394 RecalcRegs.insert(AMDGPU::SCC); 395 Changed = true; 396 } 397 398 // Try to remove unneeded instructions before s_endpgm. 399 if (MBB.succ_empty()) { 400 if (MBB.empty()) 401 continue; 402 403 // Skip this if the endpgm has any implicit uses, otherwise we would need 404 // to be careful to update / remove them. 405 // S_ENDPGM always has a single imm operand that is not used other than to 406 // end up in the encoding 407 MachineInstr &Term = MBB.back(); 408 if (Term.getOpcode() != AMDGPU::S_ENDPGM || Term.getNumOperands() != 1) 409 continue; 410 411 SmallVector<MachineBasicBlock*, 4> Blocks({&MBB}); 412 413 while (!Blocks.empty()) { 414 auto CurBB = Blocks.pop_back_val(); 415 auto I = CurBB->rbegin(), E = CurBB->rend(); 416 if (I != E) { 417 if (I->isUnconditionalBranch() || I->getOpcode() == AMDGPU::S_ENDPGM) 418 ++I; 419 else if (I->isBranch()) 420 continue; 421 } 422 423 while (I != E) { 424 if (I->isDebugInstr()) { 425 I = std::next(I); 426 continue; 427 } 428 429 if (I->mayStore() || I->isBarrier() || I->isCall() || 430 I->hasUnmodeledSideEffects() || I->hasOrderedMemoryRef()) 431 break; 432 433 LLVM_DEBUG(dbgs() 434 << "Removing no effect instruction: " << *I << '\n'); 435 436 for (auto &Op : I->operands()) { 437 if (Op.isReg()) 438 RecalcRegs.insert(Op.getReg()); 439 } 440 441 auto Next = std::next(I); 442 LIS->RemoveMachineInstrFromMaps(*I); 443 I->eraseFromParent(); 444 I = Next; 445 446 Changed = true; 447 } 448 449 if (I != E) 450 continue; 451 452 // Try to ascend predecessors. 453 for (auto *Pred : CurBB->predecessors()) { 454 if (Pred->succ_size() == 1) 455 Blocks.push_back(Pred); 456 } 457 } 458 continue; 459 } 460 461 // If the only user of a logical operation is move to exec, fold it now 462 // to prevent forming of saveexec. I.e.: 463 // 464 // %0:sreg_64 = COPY $exec 465 // %1:sreg_64 = S_AND_B64 %0:sreg_64, %2:sreg_64 466 // => 467 // %1 = S_AND_B64 $exec, %2:sreg_64 468 unsigned ScanThreshold = 10; 469 for (auto I = MBB.rbegin(), E = MBB.rend(); I != E 470 && ScanThreshold--; ++I) { 471 // Continue scanning if this is not a full exec copy 472 if (!(I->isFullCopy() && I->getOperand(1).getReg() == Register(ExecReg))) 473 continue; 474 475 Register SavedExec = I->getOperand(0).getReg(); 476 if (SavedExec.isVirtual() && MRI->hasOneNonDBGUse(SavedExec)) { 477 MachineInstr *SingleExecUser = &*MRI->use_instr_nodbg_begin(SavedExec); 478 int Idx = SingleExecUser->findRegisterUseOperandIdx(SavedExec); 479 assert(Idx != -1); 480 if (SingleExecUser->getParent() == I->getParent() && 481 !SingleExecUser->getOperand(Idx).isImplicit() && 482 TII->isOperandLegal(*SingleExecUser, Idx, &I->getOperand(1))) { 483 LLVM_DEBUG(dbgs() << "Redundant EXEC COPY: " << *I << '\n'); 484 LIS->RemoveMachineInstrFromMaps(*I); 485 I->eraseFromParent(); 486 MRI->replaceRegWith(SavedExec, ExecReg); 487 LIS->removeInterval(SavedExec); 488 Changed = true; 489 } 490 } 491 break; 492 } 493 } 494 495 if (Changed) { 496 for (auto Reg : RecalcRegs) { 497 if (Reg.isVirtual()) { 498 LIS->removeInterval(Reg); 499 if (!MRI->reg_empty(Reg)) 500 LIS->createAndComputeVirtRegInterval(Reg); 501 } else { 502 LIS->removeAllRegUnitsForPhysReg(Reg); 503 } 504 } 505 } 506 507 return Changed; 508 } 509