| 1 | //===-- AMDGPUAtomicOptimizer.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 optimizes atomic operations by using a single lane of a wavefront |
| 11 | /// to perform the atomic operation, thus reducing contention on that memory |
| 12 | /// location. |
| 13 | /// Atomic optimizer uses following strategies to compute scan and reduced |
| 14 | /// values |
| 15 | /// 1. DPP - |
| 16 | /// This is the most efficient implementation for scan. DPP uses Whole Wave |
| 17 | /// Mode (WWM) |
| 18 | /// 2. Iterative - |
| 19 | // An alternative implementation iterates over all active lanes |
| 20 | /// of Wavefront using llvm.cttz and performs scan using readlane & writelane |
| 21 | /// intrinsics |
| 22 | //===----------------------------------------------------------------------===// |
| 23 | |
| 24 | #include "AMDGPU.h" |
| 25 | #include "GCNSubtarget.h" |
| 26 | #include "llvm/Analysis/DomTreeUpdater.h" |
| 27 | #include "llvm/Analysis/UniformityAnalysis.h" |
| 28 | #include "llvm/CodeGen/TargetPassConfig.h" |
| 29 | #include "llvm/IR/IRBuilder.h" |
| 30 | #include "llvm/IR/InstVisitor.h" |
| 31 | #include "llvm/IR/IntrinsicsAMDGPU.h" |
| 32 | #include "llvm/InitializePasses.h" |
| 33 | #include "llvm/Target/TargetMachine.h" |
| 34 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 35 | |
| 36 | #define DEBUG_TYPE "amdgpu-atomic-optimizer" |
| 37 | |
| 38 | using namespace llvm; |
| 39 | using namespace llvm::AMDGPU; |
| 40 | |
| 41 | namespace { |
| 42 | |
| 43 | struct ReplacementInfo { |
| 44 | Instruction *I; |
| 45 | AtomicRMWInst::BinOp Op; |
| 46 | unsigned ValIdx; |
| 47 | bool ValDivergent; |
| 48 | bool IsLDS; |
| 49 | }; |
| 50 | |
| 51 | class AMDGPUAtomicOptimizer : public FunctionPass { |
| 52 | public: |
| 53 | static char ID; |
| 54 | ScanOptions ScanImpl; |
| 55 | AMDGPUAtomicOptimizer(ScanOptions ScanImpl) |
| 56 | : FunctionPass(ID), ScanImpl(ScanImpl) {} |
| 57 | |
| 58 | bool runOnFunction(Function &F) override; |
| 59 | |
| 60 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 61 | AU.addPreserved<DominatorTreeWrapperPass>(); |
| 62 | AU.addRequired<UniformityInfoWrapperPass>(); |
| 63 | AU.addRequired<TargetPassConfig>(); |
| 64 | } |
| 65 | }; |
| 66 | |
| 67 | class AMDGPUAtomicOptimizerImpl |
| 68 | : public InstVisitor<AMDGPUAtomicOptimizerImpl> { |
| 69 | private: |
| 70 | Function &F; |
| 71 | SmallVector<ReplacementInfo, 8> ToReplace; |
| 72 | const UniformityInfo &UA; |
| 73 | const DataLayout &DL; |
| 74 | DomTreeUpdater &DTU; |
| 75 | const GCNSubtarget &ST; |
| 76 | bool IsPixelShader; |
| 77 | ScanOptions ScanImpl; |
| 78 | |
| 79 | Value *buildReduction(IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *V, |
| 80 | Value *const Identity) const; |
| 81 | Value *buildScan(IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *V, |
| 82 | Value *const Identity) const; |
| 83 | Value *buildShiftRight(IRBuilder<> &B, Value *V, Value *const Identity) const; |
| 84 | |
| 85 | std::pair<Value *, Value *> |
| 86 | buildScanIteratively(IRBuilder<> &B, AtomicRMWInst::BinOp Op, |
| 87 | Value *const Identity, Value *V, Instruction &I, |
| 88 | BasicBlock *ComputeLoop, BasicBlock *ComputeEnd) const; |
| 89 | |
| 90 | void optimizeAtomic(Instruction &I, AtomicRMWInst::BinOp Op, unsigned ValIdx, |
| 91 | bool ValDivergent, bool IsLDS) const; |
| 92 | |
| 93 | public: |
| 94 | AMDGPUAtomicOptimizerImpl() = delete; |
| 95 | |
| 96 | AMDGPUAtomicOptimizerImpl(Function &F, const UniformityInfo &UA, |
| 97 | DomTreeUpdater &DTU, const GCNSubtarget &ST, |
| 98 | ScanOptions ScanImpl) |
| 99 | : F(F), UA(UA), DL(F.getDataLayout()), DTU(DTU), ST(ST), |
| 100 | IsPixelShader(F.getCallingConv() == CallingConv::AMDGPU_PS), |
| 101 | ScanImpl(ScanImpl) {} |
| 102 | |
| 103 | bool run(); |
| 104 | |
| 105 | void visitAtomicRMWInst(AtomicRMWInst &I); |
| 106 | void visitIntrinsicInst(IntrinsicInst &I); |
| 107 | }; |
| 108 | |
| 109 | } // namespace |
| 110 | |
| 111 | char AMDGPUAtomicOptimizer::ID = 0; |
| 112 | |
| 113 | char &llvm::AMDGPUAtomicOptimizerID = AMDGPUAtomicOptimizer::ID; |
| 114 | |
| 115 | bool AMDGPUAtomicOptimizer::runOnFunction(Function &F) { |
| 116 | if (skipFunction(F)) { |
| 117 | return false; |
| 118 | } |
| 119 | |
| 120 | const UniformityInfo &UA = |
| 121 | getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo(); |
| 122 | |
| 123 | DominatorTreeWrapperPass *DTW = |
| 124 | getAnalysisIfAvailable<DominatorTreeWrapperPass>(); |
| 125 | DomTreeUpdater DTU(DTW ? &DTW->getDomTree() : nullptr, |
| 126 | DomTreeUpdater::UpdateStrategy::Lazy); |
| 127 | |
| 128 | const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>(); |
| 129 | const TargetMachine &TM = TPC.getTM<TargetMachine>(); |
| 130 | const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F); |
| 131 | |
| 132 | return AMDGPUAtomicOptimizerImpl(F, UA, DTU, ST, ScanImpl).run(); |
| 133 | } |
| 134 | |
| 135 | PreservedAnalyses AMDGPUAtomicOptimizerPass::run(Function &F, |
| 136 | FunctionAnalysisManager &AM) { |
| 137 | const auto &UA = AM.getResult<UniformityInfoAnalysis>(IR&: F); |
| 138 | |
| 139 | DomTreeUpdater DTU(&AM.getResult<DominatorTreeAnalysis>(IR&: F), |
| 140 | DomTreeUpdater::UpdateStrategy::Lazy); |
| 141 | const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F); |
| 142 | |
| 143 | bool IsChanged = AMDGPUAtomicOptimizerImpl(F, UA, DTU, ST, ScanImpl).run(); |
| 144 | |
| 145 | if (!IsChanged) { |
| 146 | return PreservedAnalyses::all(); |
| 147 | } |
| 148 | |
| 149 | PreservedAnalyses PA; |
| 150 | PA.preserve<DominatorTreeAnalysis>(); |
| 151 | return PA; |
| 152 | } |
| 153 | |
| 154 | bool AMDGPUAtomicOptimizerImpl::run() { |
| 155 | // Scan option None disables the Pass |
| 156 | if (ScanImpl == ScanOptions::None) |
| 157 | return false; |
| 158 | if (ST.isSingleLaneExecution(Kernel: F)) |
| 159 | return false; |
| 160 | |
| 161 | visit(F); |
| 162 | if (ToReplace.empty()) |
| 163 | return false; |
| 164 | |
| 165 | for (auto &[I, Op, ValIdx, ValDivergent, IsLDS] : ToReplace) |
| 166 | optimizeAtomic(I&: *I, Op, ValIdx, ValDivergent, IsLDS); |
| 167 | ToReplace.clear(); |
| 168 | return true; |
| 169 | } |
| 170 | |
| 171 | static bool isLegalCrossLaneType(Type *Ty) { |
| 172 | switch (Ty->getTypeID()) { |
| 173 | case Type::FloatTyID: |
| 174 | case Type::DoubleTyID: |
| 175 | return true; |
| 176 | case Type::IntegerTyID: { |
| 177 | unsigned Size = Ty->getIntegerBitWidth(); |
| 178 | return (Size == 32 || Size == 64); |
| 179 | } |
| 180 | default: |
| 181 | return false; |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | void AMDGPUAtomicOptimizerImpl::visitAtomicRMWInst(AtomicRMWInst &I) { |
| 186 | // Early exit for unhandled address space atomic instructions. |
| 187 | switch (I.getPointerAddressSpace()) { |
| 188 | default: |
| 189 | return; |
| 190 | case AMDGPUAS::GLOBAL_ADDRESS: |
| 191 | case AMDGPUAS::LOCAL_ADDRESS: |
| 192 | break; |
| 193 | } |
| 194 | |
| 195 | AtomicRMWInst::BinOp Op = I.getOperation(); |
| 196 | |
| 197 | switch (Op) { |
| 198 | default: |
| 199 | return; |
| 200 | case AtomicRMWInst::Add: |
| 201 | case AtomicRMWInst::Sub: |
| 202 | case AtomicRMWInst::And: |
| 203 | case AtomicRMWInst::Or: |
| 204 | case AtomicRMWInst::Xor: |
| 205 | case AtomicRMWInst::Max: |
| 206 | case AtomicRMWInst::Min: |
| 207 | case AtomicRMWInst::UMax: |
| 208 | case AtomicRMWInst::UMin: |
| 209 | case AtomicRMWInst::FAdd: |
| 210 | case AtomicRMWInst::FSub: |
| 211 | case AtomicRMWInst::FMax: |
| 212 | case AtomicRMWInst::FMin: |
| 213 | break; |
| 214 | } |
| 215 | |
| 216 | // Only 32 and 64 bit floating point atomic ops are supported. |
| 217 | if (AtomicRMWInst::isFPOperation(Op) && |
| 218 | !(I.getType()->isFloatTy() || I.getType()->isDoubleTy())) { |
| 219 | return; |
| 220 | } |
| 221 | |
| 222 | const unsigned PtrIdx = 0; |
| 223 | const unsigned ValIdx = 1; |
| 224 | |
| 225 | // If the pointer operand is divergent, then each lane is doing an atomic |
| 226 | // operation on a different address, and we cannot optimize that. |
| 227 | if (UA.isDivergentAtUse(U: I.getOperandUse(i: PtrIdx))) { |
| 228 | return; |
| 229 | } |
| 230 | |
| 231 | bool ValDivergent = UA.isDivergentAtUse(U: I.getOperandUse(i: ValIdx)); |
| 232 | |
| 233 | // If the value operand is divergent, each lane is contributing a different |
| 234 | // value to the atomic calculation. We can only optimize divergent values if |
| 235 | // we have DPP available on our subtarget (for DPP strategy), and the atomic |
| 236 | // operation is 32 or 64 bits. |
| 237 | if (ValDivergent) { |
| 238 | if (ScanImpl == ScanOptions::DPP && !ST.hasDPP()) |
| 239 | return; |
| 240 | |
| 241 | if (!isLegalCrossLaneType(Ty: I.getType())) |
| 242 | return; |
| 243 | } |
| 244 | |
| 245 | const bool IsLDS = I.getPointerAddressSpace() == AMDGPUAS::LOCAL_ADDRESS; |
| 246 | |
| 247 | // If we get here, we can optimize the atomic using a single wavefront-wide |
| 248 | // atomic operation to do the calculation for the entire wavefront, so |
| 249 | // remember the instruction so we can come back to it. |
| 250 | ToReplace.push_back(Elt: {.I: &I, .Op: Op, .ValIdx: ValIdx, .ValDivergent: ValDivergent, .IsLDS: IsLDS}); |
| 251 | } |
| 252 | |
| 253 | void AMDGPUAtomicOptimizerImpl::visitIntrinsicInst(IntrinsicInst &I) { |
| 254 | AtomicRMWInst::BinOp Op; |
| 255 | |
| 256 | switch (I.getIntrinsicID()) { |
| 257 | default: |
| 258 | return; |
| 259 | case Intrinsic::amdgcn_struct_buffer_atomic_add: |
| 260 | case Intrinsic::amdgcn_struct_ptr_buffer_atomic_add: |
| 261 | case Intrinsic::amdgcn_raw_buffer_atomic_add: |
| 262 | case Intrinsic::amdgcn_raw_ptr_buffer_atomic_add: |
| 263 | Op = AtomicRMWInst::Add; |
| 264 | break; |
| 265 | case Intrinsic::amdgcn_struct_buffer_atomic_sub: |
| 266 | case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub: |
| 267 | case Intrinsic::amdgcn_raw_buffer_atomic_sub: |
| 268 | case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub: |
| 269 | Op = AtomicRMWInst::Sub; |
| 270 | break; |
| 271 | case Intrinsic::amdgcn_struct_buffer_atomic_and: |
| 272 | case Intrinsic::amdgcn_struct_ptr_buffer_atomic_and: |
| 273 | case Intrinsic::amdgcn_raw_buffer_atomic_and: |
| 274 | case Intrinsic::amdgcn_raw_ptr_buffer_atomic_and: |
| 275 | Op = AtomicRMWInst::And; |
| 276 | break; |
| 277 | case Intrinsic::amdgcn_struct_buffer_atomic_or: |
| 278 | case Intrinsic::amdgcn_struct_ptr_buffer_atomic_or: |
| 279 | case Intrinsic::amdgcn_raw_buffer_atomic_or: |
| 280 | case Intrinsic::amdgcn_raw_ptr_buffer_atomic_or: |
| 281 | Op = AtomicRMWInst::Or; |
| 282 | break; |
| 283 | case Intrinsic::amdgcn_struct_buffer_atomic_xor: |
| 284 | case Intrinsic::amdgcn_struct_ptr_buffer_atomic_xor: |
| 285 | case Intrinsic::amdgcn_raw_buffer_atomic_xor: |
| 286 | case Intrinsic::amdgcn_raw_ptr_buffer_atomic_xor: |
| 287 | Op = AtomicRMWInst::Xor; |
| 288 | break; |
| 289 | case Intrinsic::amdgcn_struct_buffer_atomic_smin: |
| 290 | case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smin: |
| 291 | case Intrinsic::amdgcn_raw_buffer_atomic_smin: |
| 292 | case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smin: |
| 293 | Op = AtomicRMWInst::Min; |
| 294 | break; |
| 295 | case Intrinsic::amdgcn_struct_buffer_atomic_umin: |
| 296 | case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umin: |
| 297 | case Intrinsic::amdgcn_raw_buffer_atomic_umin: |
| 298 | case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umin: |
| 299 | Op = AtomicRMWInst::UMin; |
| 300 | break; |
| 301 | case Intrinsic::amdgcn_struct_buffer_atomic_smax: |
| 302 | case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smax: |
| 303 | case Intrinsic::amdgcn_raw_buffer_atomic_smax: |
| 304 | case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smax: |
| 305 | Op = AtomicRMWInst::Max; |
| 306 | break; |
| 307 | case Intrinsic::amdgcn_struct_buffer_atomic_umax: |
| 308 | case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umax: |
| 309 | case Intrinsic::amdgcn_raw_buffer_atomic_umax: |
| 310 | case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umax: |
| 311 | Op = AtomicRMWInst::UMax; |
| 312 | break; |
| 313 | } |
| 314 | |
| 315 | const unsigned ValIdx = 0; |
| 316 | |
| 317 | const bool ValDivergent = UA.isDivergentAtUse(U: I.getOperandUse(i: ValIdx)); |
| 318 | |
| 319 | // If the value operand is divergent, each lane is contributing a different |
| 320 | // value to the atomic calculation. We can only optimize divergent values if |
| 321 | // we have DPP available on our subtarget (for DPP strategy), and the atomic |
| 322 | // operation is 32 or 64 bits. |
| 323 | if (ValDivergent) { |
| 324 | if (ScanImpl == ScanOptions::DPP && !ST.hasDPP()) |
| 325 | return; |
| 326 | |
| 327 | if (!isLegalCrossLaneType(Ty: I.getType())) |
| 328 | return; |
| 329 | } |
| 330 | |
| 331 | // If any of the other arguments to the intrinsic are divergent, we can't |
| 332 | // optimize the operation. |
| 333 | for (unsigned Idx = 1; Idx < I.getNumOperands(); Idx++) { |
| 334 | if (UA.isDivergentAtUse(U: I.getOperandUse(i: Idx))) |
| 335 | return; |
| 336 | } |
| 337 | |
| 338 | // If we get here, we can optimize the atomic using a single wavefront-wide |
| 339 | // atomic operation to do the calculation for the entire wavefront, so |
| 340 | // remember the instruction so we can come back to it. |
| 341 | // Buffer atomics are never LDS. |
| 342 | ToReplace.push_back(Elt: {.I: &I, .Op: Op, .ValIdx: ValIdx, .ValDivergent: ValDivergent, /*IsLDS=*/false}); |
| 343 | } |
| 344 | |
| 345 | // Use the builder to create the non-atomic counterpart of the specified |
| 346 | // atomicrmw binary op. |
| 347 | static Value *buildNonAtomicBinOp(IRBuilder<> &B, AtomicRMWInst::BinOp Op, |
| 348 | Value *LHS, Value *RHS) { |
| 349 | CmpInst::Predicate Pred; |
| 350 | |
| 351 | switch (Op) { |
| 352 | default: |
| 353 | llvm_unreachable("Unhandled atomic op" ); |
| 354 | case AtomicRMWInst::Add: |
| 355 | return B.CreateBinOp(Opc: Instruction::Add, LHS, RHS); |
| 356 | case AtomicRMWInst::FAdd: |
| 357 | return B.CreateFAdd(L: LHS, R: RHS); |
| 358 | case AtomicRMWInst::Sub: |
| 359 | return B.CreateBinOp(Opc: Instruction::Sub, LHS, RHS); |
| 360 | case AtomicRMWInst::FSub: |
| 361 | return B.CreateFSub(L: LHS, R: RHS); |
| 362 | case AtomicRMWInst::And: |
| 363 | return B.CreateBinOp(Opc: Instruction::And, LHS, RHS); |
| 364 | case AtomicRMWInst::Or: |
| 365 | return B.CreateBinOp(Opc: Instruction::Or, LHS, RHS); |
| 366 | case AtomicRMWInst::Xor: |
| 367 | return B.CreateBinOp(Opc: Instruction::Xor, LHS, RHS); |
| 368 | |
| 369 | case AtomicRMWInst::Max: |
| 370 | Pred = CmpInst::ICMP_SGT; |
| 371 | break; |
| 372 | case AtomicRMWInst::Min: |
| 373 | Pred = CmpInst::ICMP_SLT; |
| 374 | break; |
| 375 | case AtomicRMWInst::UMax: |
| 376 | Pred = CmpInst::ICMP_UGT; |
| 377 | break; |
| 378 | case AtomicRMWInst::UMin: |
| 379 | Pred = CmpInst::ICMP_ULT; |
| 380 | break; |
| 381 | case AtomicRMWInst::FMax: |
| 382 | return B.CreateMaxNum(LHS, RHS); |
| 383 | case AtomicRMWInst::FMin: |
| 384 | return B.CreateMinNum(LHS, RHS); |
| 385 | } |
| 386 | Value *Cond = B.CreateICmp(P: Pred, LHS, RHS); |
| 387 | return B.CreateSelect(C: Cond, True: LHS, False: RHS); |
| 388 | } |
| 389 | |
| 390 | // Use the builder to create a reduction of V across the wavefront, with all |
| 391 | // lanes active, returning the same result in all lanes. |
| 392 | Value *AMDGPUAtomicOptimizerImpl::buildReduction(IRBuilder<> &B, |
| 393 | AtomicRMWInst::BinOp Op, |
| 394 | Value *V, |
| 395 | Value *const Identity) const { |
| 396 | Type *AtomicTy = V->getType(); |
| 397 | Module *M = B.GetInsertBlock()->getModule(); |
| 398 | |
| 399 | // Reduce within each row of 16 lanes. |
| 400 | for (unsigned Idx = 0; Idx < 4; Idx++) { |
| 401 | V = buildNonAtomicBinOp( |
| 402 | B, Op, LHS: V, |
| 403 | RHS: B.CreateIntrinsic(ID: Intrinsic::amdgcn_update_dpp, OverloadTypes: AtomicTy, |
| 404 | Args: {Identity, V, B.getInt32(C: DPP::ROW_XMASK0 | 1 << Idx), |
| 405 | B.getInt32(C: 0xf), B.getInt32(C: 0xf), B.getFalse()})); |
| 406 | } |
| 407 | |
| 408 | // Reduce within each pair of rows (i.e. 32 lanes). |
| 409 | assert(ST.hasPermlane16Insts()); |
| 410 | Value *Permlanex16Call = |
| 411 | B.CreateIntrinsic(RetTy: AtomicTy, ID: Intrinsic::amdgcn_permlanex16, |
| 412 | Args: {PoisonValue::get(T: AtomicTy), V, B.getInt32(C: 0), |
| 413 | B.getInt32(C: 0), B.getFalse(), B.getFalse()}); |
| 414 | V = buildNonAtomicBinOp(B, Op, LHS: V, RHS: Permlanex16Call); |
| 415 | if (ST.isWave32()) { |
| 416 | return V; |
| 417 | } |
| 418 | |
| 419 | if (ST.hasPermLane64()) { |
| 420 | // Reduce across the upper and lower 32 lanes. |
| 421 | Value *Permlane64Call = |
| 422 | B.CreateIntrinsic(RetTy: AtomicTy, ID: Intrinsic::amdgcn_permlane64, Args: V); |
| 423 | return buildNonAtomicBinOp(B, Op, LHS: V, RHS: Permlane64Call); |
| 424 | } |
| 425 | |
| 426 | // Pick an arbitrary lane from 0..31 and an arbitrary lane from 32..63 and |
| 427 | // combine them with a scalar operation. |
| 428 | Function *ReadLane = Intrinsic::getOrInsertDeclaration( |
| 429 | M, id: Intrinsic::amdgcn_readlane, OverloadTys: AtomicTy); |
| 430 | Value *Lane0 = B.CreateCall(Callee: ReadLane, Args: {V, B.getInt32(C: 0)}); |
| 431 | Value *Lane32 = B.CreateCall(Callee: ReadLane, Args: {V, B.getInt32(C: 32)}); |
| 432 | return buildNonAtomicBinOp(B, Op, LHS: Lane0, RHS: Lane32); |
| 433 | } |
| 434 | |
| 435 | // Use the builder to create an inclusive scan of V across the wavefront, with |
| 436 | // all lanes active. |
| 437 | Value *AMDGPUAtomicOptimizerImpl::buildScan(IRBuilder<> &B, |
| 438 | AtomicRMWInst::BinOp Op, Value *V, |
| 439 | Value *Identity) const { |
| 440 | Type *AtomicTy = V->getType(); |
| 441 | Module *M = B.GetInsertBlock()->getModule(); |
| 442 | Function *UpdateDPP = Intrinsic::getOrInsertDeclaration( |
| 443 | M, id: Intrinsic::amdgcn_update_dpp, OverloadTys: AtomicTy); |
| 444 | |
| 445 | for (unsigned Idx = 0; Idx < 4; Idx++) { |
| 446 | V = buildNonAtomicBinOp( |
| 447 | B, Op, LHS: V, |
| 448 | RHS: B.CreateCall(Callee: UpdateDPP, |
| 449 | Args: {Identity, V, B.getInt32(C: DPP::ROW_SHR0 | 1 << Idx), |
| 450 | B.getInt32(C: 0xf), B.getInt32(C: 0xf), B.getFalse()})); |
| 451 | } |
| 452 | if (ST.hasDPPBroadcasts()) { |
| 453 | // GFX9 has DPP row broadcast operations. |
| 454 | V = buildNonAtomicBinOp( |
| 455 | B, Op, LHS: V, |
| 456 | RHS: B.CreateCall(Callee: UpdateDPP, |
| 457 | Args: {Identity, V, B.getInt32(C: DPP::BCAST15), B.getInt32(C: 0xa), |
| 458 | B.getInt32(C: 0xf), B.getFalse()})); |
| 459 | V = buildNonAtomicBinOp( |
| 460 | B, Op, LHS: V, |
| 461 | RHS: B.CreateCall(Callee: UpdateDPP, |
| 462 | Args: {Identity, V, B.getInt32(C: DPP::BCAST31), B.getInt32(C: 0xc), |
| 463 | B.getInt32(C: 0xf), B.getFalse()})); |
| 464 | } else { |
| 465 | // On GFX10 all DPP operations are confined to a single row. To get cross- |
| 466 | // row operations we have to use permlane or readlane. |
| 467 | |
| 468 | // Combine lane 15 into lanes 16..31 (and, for wave 64, lane 47 into lanes |
| 469 | // 48..63). |
| 470 | assert(ST.hasPermlane16Insts()); |
| 471 | Value *PermX = |
| 472 | B.CreateIntrinsic(RetTy: AtomicTy, ID: Intrinsic::amdgcn_permlanex16, |
| 473 | Args: {PoisonValue::get(T: AtomicTy), V, B.getInt32(C: -1), |
| 474 | B.getInt32(C: -1), B.getFalse(), B.getFalse()}); |
| 475 | |
| 476 | Value *UpdateDPPCall = B.CreateCall( |
| 477 | Callee: UpdateDPP, Args: {Identity, PermX, B.getInt32(C: DPP::QUAD_PERM_ID), |
| 478 | B.getInt32(C: 0xa), B.getInt32(C: 0xf), B.getFalse()}); |
| 479 | V = buildNonAtomicBinOp(B, Op, LHS: V, RHS: UpdateDPPCall); |
| 480 | |
| 481 | if (!ST.isWave32()) { |
| 482 | // Combine lane 31 into lanes 32..63. |
| 483 | Value *const Lane31 = B.CreateIntrinsic( |
| 484 | RetTy: AtomicTy, ID: Intrinsic::amdgcn_readlane, Args: {V, B.getInt32(C: 31)}); |
| 485 | |
| 486 | Value *UpdateDPPCall = B.CreateCall( |
| 487 | Callee: UpdateDPP, Args: {Identity, Lane31, B.getInt32(C: DPP::QUAD_PERM_ID), |
| 488 | B.getInt32(C: 0xc), B.getInt32(C: 0xf), B.getFalse()}); |
| 489 | |
| 490 | V = buildNonAtomicBinOp(B, Op, LHS: V, RHS: UpdateDPPCall); |
| 491 | } |
| 492 | } |
| 493 | return V; |
| 494 | } |
| 495 | |
| 496 | // Use the builder to create a shift right of V across the wavefront, with all |
| 497 | // lanes active, to turn an inclusive scan into an exclusive scan. |
| 498 | Value *AMDGPUAtomicOptimizerImpl::buildShiftRight(IRBuilder<> &B, Value *V, |
| 499 | Value *Identity) const { |
| 500 | Type *AtomicTy = V->getType(); |
| 501 | Module *M = B.GetInsertBlock()->getModule(); |
| 502 | Function *UpdateDPP = Intrinsic::getOrInsertDeclaration( |
| 503 | M, id: Intrinsic::amdgcn_update_dpp, OverloadTys: AtomicTy); |
| 504 | if (ST.hasDPPWavefrontShifts()) { |
| 505 | // GFX9 has DPP wavefront shift operations. |
| 506 | V = B.CreateCall(Callee: UpdateDPP, |
| 507 | Args: {Identity, V, B.getInt32(C: DPP::WAVE_SHR1), B.getInt32(C: 0xf), |
| 508 | B.getInt32(C: 0xf), B.getFalse()}); |
| 509 | } else { |
| 510 | Function *ReadLane = Intrinsic::getOrInsertDeclaration( |
| 511 | M, id: Intrinsic::amdgcn_readlane, OverloadTys: AtomicTy); |
| 512 | Function *WriteLane = Intrinsic::getOrInsertDeclaration( |
| 513 | M, id: Intrinsic::amdgcn_writelane, OverloadTys: AtomicTy); |
| 514 | |
| 515 | // On GFX10 all DPP operations are confined to a single row. To get cross- |
| 516 | // row operations we have to use permlane or readlane. |
| 517 | Value *Old = V; |
| 518 | V = B.CreateCall(Callee: UpdateDPP, |
| 519 | Args: {Identity, V, B.getInt32(C: DPP::ROW_SHR0 + 1), |
| 520 | B.getInt32(C: 0xf), B.getInt32(C: 0xf), B.getFalse()}); |
| 521 | |
| 522 | // Copy the old lane 15 to the new lane 16. |
| 523 | V = B.CreateCall(Callee: WriteLane, Args: {B.CreateCall(Callee: ReadLane, Args: {Old, B.getInt32(C: 15)}), |
| 524 | B.getInt32(C: 16), V}); |
| 525 | |
| 526 | if (!ST.isWave32()) { |
| 527 | // Copy the old lane 31 to the new lane 32. |
| 528 | V = B.CreateCall( |
| 529 | Callee: WriteLane, |
| 530 | Args: {B.CreateCall(Callee: ReadLane, Args: {Old, B.getInt32(C: 31)}), B.getInt32(C: 32), V}); |
| 531 | |
| 532 | // Copy the old lane 47 to the new lane 48. |
| 533 | V = B.CreateCall( |
| 534 | Callee: WriteLane, |
| 535 | Args: {B.CreateCall(Callee: ReadLane, Args: {Old, B.getInt32(C: 47)}), B.getInt32(C: 48), V}); |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | return V; |
| 540 | } |
| 541 | |
| 542 | // Use the builder to create an exclusive scan and compute the final reduced |
| 543 | // value using an iterative approach. This provides an alternative |
| 544 | // implementation to DPP which uses WMM for scan computations. This API iterate |
| 545 | // over active lanes to read, compute and update the value using |
| 546 | // readlane and writelane intrinsics. |
| 547 | std::pair<Value *, Value *> AMDGPUAtomicOptimizerImpl::buildScanIteratively( |
| 548 | IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *const Identity, Value *V, |
| 549 | Instruction &I, BasicBlock *ComputeLoop, BasicBlock *ComputeEnd) const { |
| 550 | auto *Ty = I.getType(); |
| 551 | auto *WaveTy = B.getIntNTy(N: ST.getWavefrontSize()); |
| 552 | auto *EntryBB = I.getParent(); |
| 553 | auto NeedResult = !I.use_empty(); |
| 554 | |
| 555 | auto *Ballot = |
| 556 | B.CreateIntrinsic(ID: Intrinsic::amdgcn_ballot, OverloadTypes: WaveTy, Args: B.getTrue()); |
| 557 | |
| 558 | // Start inserting instructions for ComputeLoop block |
| 559 | B.SetInsertPoint(ComputeLoop); |
| 560 | // Phi nodes for Accumulator, Scan results destination, and Active Lanes |
| 561 | auto *Accumulator = B.CreatePHI(Ty, NumReservedValues: 2, Name: "Accumulator" ); |
| 562 | Accumulator->addIncoming(V: Identity, BB: EntryBB); |
| 563 | PHINode *OldValuePhi = nullptr; |
| 564 | if (NeedResult) { |
| 565 | OldValuePhi = B.CreatePHI(Ty, NumReservedValues: 2, Name: "OldValuePhi" ); |
| 566 | OldValuePhi->addIncoming(V: PoisonValue::get(T: Ty), BB: EntryBB); |
| 567 | } |
| 568 | auto *ActiveBits = B.CreatePHI(Ty: WaveTy, NumReservedValues: 2, Name: "ActiveBits" ); |
| 569 | ActiveBits->addIncoming(V: Ballot, BB: EntryBB); |
| 570 | |
| 571 | // Use llvm.cttz intrinsic to find the lowest remaining active lane. |
| 572 | auto *FF1 = |
| 573 | B.CreateIntrinsic(ID: Intrinsic::cttz, OverloadTypes: WaveTy, Args: {ActiveBits, B.getTrue()}); |
| 574 | |
| 575 | auto *LaneIdxInt = B.CreateTrunc(V: FF1, DestTy: B.getInt32Ty()); |
| 576 | |
| 577 | // Get the value required for atomic operation |
| 578 | Value *LaneValue = B.CreateIntrinsic(RetTy: V->getType(), ID: Intrinsic::amdgcn_readlane, |
| 579 | Args: {V, LaneIdxInt}); |
| 580 | |
| 581 | // Perform writelane if intermediate scan results are required later in the |
| 582 | // kernel computations |
| 583 | Value *OldValue = nullptr; |
| 584 | if (NeedResult) { |
| 585 | OldValue = B.CreateIntrinsic(RetTy: V->getType(), ID: Intrinsic::amdgcn_writelane, |
| 586 | Args: {Accumulator, LaneIdxInt, OldValuePhi}); |
| 587 | OldValuePhi->addIncoming(V: OldValue, BB: ComputeLoop); |
| 588 | } |
| 589 | |
| 590 | // Accumulate the results |
| 591 | auto *NewAccumulator = buildNonAtomicBinOp(B, Op, LHS: Accumulator, RHS: LaneValue); |
| 592 | Accumulator->addIncoming(V: NewAccumulator, BB: ComputeLoop); |
| 593 | |
| 594 | // Set bit to zero of current active lane so that for next iteration llvm.cttz |
| 595 | // return the next active lane |
| 596 | auto *Mask = B.CreateShl(LHS: ConstantInt::get(Ty: WaveTy, V: 1), RHS: FF1); |
| 597 | |
| 598 | auto *InverseMask = B.CreateXor(LHS: Mask, RHS: ConstantInt::getAllOnesValue(Ty: WaveTy)); |
| 599 | auto *NewActiveBits = B.CreateAnd(LHS: ActiveBits, RHS: InverseMask); |
| 600 | ActiveBits->addIncoming(V: NewActiveBits, BB: ComputeLoop); |
| 601 | |
| 602 | // Branch out of the loop when all lanes are processed. |
| 603 | auto *IsEnd = B.CreateICmpEQ(LHS: NewActiveBits, RHS: ConstantInt::get(Ty: WaveTy, V: 0)); |
| 604 | B.CreateCondBr(Cond: IsEnd, True: ComputeEnd, False: ComputeLoop); |
| 605 | |
| 606 | B.SetInsertPoint(ComputeEnd); |
| 607 | |
| 608 | return {OldValue, NewAccumulator}; |
| 609 | } |
| 610 | |
| 611 | static Constant *getIdentityValueForAtomicOp(Type *const Ty, |
| 612 | AtomicRMWInst::BinOp Op) { |
| 613 | LLVMContext &C = Ty->getContext(); |
| 614 | const unsigned BitWidth = Ty->getPrimitiveSizeInBits(); |
| 615 | switch (Op) { |
| 616 | default: |
| 617 | llvm_unreachable("Unhandled atomic op" ); |
| 618 | case AtomicRMWInst::Add: |
| 619 | case AtomicRMWInst::Sub: |
| 620 | case AtomicRMWInst::Or: |
| 621 | case AtomicRMWInst::Xor: |
| 622 | case AtomicRMWInst::UMax: |
| 623 | return ConstantInt::get(Context&: C, V: APInt::getMinValue(numBits: BitWidth)); |
| 624 | case AtomicRMWInst::And: |
| 625 | case AtomicRMWInst::UMin: |
| 626 | return ConstantInt::get(Context&: C, V: APInt::getMaxValue(numBits: BitWidth)); |
| 627 | case AtomicRMWInst::Max: |
| 628 | return ConstantInt::get(Context&: C, V: APInt::getSignedMinValue(numBits: BitWidth)); |
| 629 | case AtomicRMWInst::Min: |
| 630 | return ConstantInt::get(Context&: C, V: APInt::getSignedMaxValue(numBits: BitWidth)); |
| 631 | case AtomicRMWInst::FAdd: |
| 632 | return ConstantFP::get(Context&: C, V: APFloat::getZero(Sem: Ty->getFltSemantics(), Negative: true)); |
| 633 | case AtomicRMWInst::FSub: |
| 634 | return ConstantFP::get(Context&: C, V: APFloat::getZero(Sem: Ty->getFltSemantics(), Negative: false)); |
| 635 | case AtomicRMWInst::FMin: |
| 636 | case AtomicRMWInst::FMax: |
| 637 | // FIXME: atomicrmw fmax/fmin behave like llvm.maxnum/minnum so NaN is the |
| 638 | // closest thing they have to an identity, but it still does not preserve |
| 639 | // the difference between quiet and signaling NaNs or NaNs with different |
| 640 | // payloads. |
| 641 | return ConstantFP::get(Context&: C, V: APFloat::getNaN(Sem: Ty->getFltSemantics())); |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | static Value *buildMul(IRBuilder<> &B, Value *LHS, Value *RHS) { |
| 646 | const ConstantInt *CI = dyn_cast<ConstantInt>(Val: LHS); |
| 647 | return (CI && CI->isOne()) ? RHS : B.CreateMul(LHS, RHS); |
| 648 | } |
| 649 | |
| 650 | void AMDGPUAtomicOptimizerImpl::optimizeAtomic(Instruction &I, |
| 651 | AtomicRMWInst::BinOp Op, |
| 652 | unsigned ValIdx, |
| 653 | bool ValDivergent, |
| 654 | bool IsLDS) const { |
| 655 | // Don't generate a DPP scan if !amdgpu.expected.active.lane hint indicates |
| 656 | // insufficient lanes to offset fixed overhead. |
| 657 | |
| 658 | // FIXME: The threshold was tuned empirically on gfx11 and gfx12. The DPP scan |
| 659 | // overhead differs across subtargets, so the break-even point may differ too; |
| 660 | // this may need to become subtarget-dependent. |
| 661 | if (IsLDS && ValDivergent && ScanImpl == ScanOptions::DPP) { |
| 662 | if (MDNode *MD = I.getMetadata(Kind: "amdgpu.expected.active.lanes" )) { |
| 663 | auto *CI = mdconst::extract<ConstantInt>(MD: MD->getOperand(I: 0)); |
| 664 | constexpr unsigned ActiveLanesThreshold = 5; |
| 665 | if (CI->getValue().ule(RHS: ActiveLanesThreshold)) |
| 666 | return; |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | // Start building just before the instruction. |
| 671 | IRBuilder<> B(&I); |
| 672 | |
| 673 | if (AtomicRMWInst::isFPOperation(Op)) { |
| 674 | B.setIsFPConstrained(I.getFunction()->hasFnAttribute(Kind: Attribute::StrictFP)); |
| 675 | } |
| 676 | |
| 677 | // If we are in a pixel shader, because of how we have to mask out helper |
| 678 | // lane invocations, we need to record the entry and exit BB's. |
| 679 | BasicBlock *PixelEntryBB = nullptr; |
| 680 | BasicBlock *PixelExitBB = nullptr; |
| 681 | |
| 682 | // If we're optimizing an atomic within a pixel shader, we need to wrap the |
| 683 | // entire atomic operation in a helper-lane check. We do not want any helper |
| 684 | // lanes that are around only for the purposes of derivatives to take part |
| 685 | // in any cross-lane communication, and we use a branch on whether the lane is |
| 686 | // live to do this. |
| 687 | if (IsPixelShader) { |
| 688 | // Record I's original position as the entry block. |
| 689 | PixelEntryBB = I.getParent(); |
| 690 | |
| 691 | Value *const Cond = B.CreateIntrinsic(ID: Intrinsic::amdgcn_ps_live, Args: {}); |
| 692 | Instruction *const NonHelperTerminator = |
| 693 | SplitBlockAndInsertIfThen(Cond, SplitBefore: &I, Unreachable: false, BranchWeights: nullptr, DTU: &DTU, LI: nullptr); |
| 694 | |
| 695 | // Record I's new position as the exit block. |
| 696 | PixelExitBB = I.getParent(); |
| 697 | |
| 698 | I.moveBefore(InsertPos: NonHelperTerminator->getIterator()); |
| 699 | B.SetInsertPoint(&I); |
| 700 | } |
| 701 | |
| 702 | Type *const Ty = I.getType(); |
| 703 | Type *Int32Ty = B.getInt32Ty(); |
| 704 | bool isAtomicFloatingPointTy = Ty->isFloatingPointTy(); |
| 705 | [[maybe_unused]] const unsigned TyBitWidth = DL.getTypeSizeInBits(Ty); |
| 706 | |
| 707 | // This is the value in the atomic operation we need to combine in order to |
| 708 | // reduce the number of atomic operations. |
| 709 | Value *V = I.getOperand(i: ValIdx); |
| 710 | |
| 711 | // We need to know how many lanes are active within the wavefront, and we do |
| 712 | // this by doing a ballot of active lanes. |
| 713 | Type *const WaveTy = B.getIntNTy(N: ST.getWavefrontSize()); |
| 714 | CallInst *const Ballot = B.CreateIntrinsicWithoutFolding( |
| 715 | ID: Intrinsic::amdgcn_ballot, OverloadTypes: WaveTy, Args: B.getTrue()); |
| 716 | |
| 717 | // We need to know how many lanes are active within the wavefront that are |
| 718 | // below us. If we counted each lane linearly starting from 0, a lane is |
| 719 | // below us only if its associated index was less than ours. We do this by |
| 720 | // using the mbcnt intrinsic. |
| 721 | Value *Mbcnt; |
| 722 | if (ST.isWave32()) { |
| 723 | Mbcnt = |
| 724 | B.CreateIntrinsic(ID: Intrinsic::amdgcn_mbcnt_lo, Args: {Ballot, B.getInt32(C: 0)}); |
| 725 | } else { |
| 726 | Value *const = B.CreateTrunc(V: Ballot, DestTy: Int32Ty); |
| 727 | Value *const = B.CreateTrunc(V: B.CreateLShr(LHS: Ballot, RHS: 32), DestTy: Int32Ty); |
| 728 | Mbcnt = B.CreateIntrinsic(ID: Intrinsic::amdgcn_mbcnt_lo, |
| 729 | Args: {ExtractLo, B.getInt32(C: 0)}); |
| 730 | Mbcnt = B.CreateIntrinsic(ID: Intrinsic::amdgcn_mbcnt_hi, Args: {ExtractHi, Mbcnt}); |
| 731 | } |
| 732 | |
| 733 | Function *F = I.getFunction(); |
| 734 | LLVMContext &C = F->getContext(); |
| 735 | |
| 736 | // For atomic sub, perform scan with add operation and allow one lane to |
| 737 | // subtract the reduced value later. |
| 738 | AtomicRMWInst::BinOp ScanOp = Op; |
| 739 | if (Op == AtomicRMWInst::Sub) { |
| 740 | ScanOp = AtomicRMWInst::Add; |
| 741 | } else if (Op == AtomicRMWInst::FSub) { |
| 742 | ScanOp = AtomicRMWInst::FAdd; |
| 743 | } |
| 744 | Value *Identity = getIdentityValueForAtomicOp(Ty, Op: ScanOp); |
| 745 | |
| 746 | Value *ExclScan = nullptr; |
| 747 | Value *NewV = nullptr; |
| 748 | |
| 749 | const bool NeedResult = !I.use_empty(); |
| 750 | |
| 751 | BasicBlock *ComputeLoop = nullptr; |
| 752 | BasicBlock *ComputeEnd = nullptr; |
| 753 | // If we have a divergent value in each lane, we need to combine the value |
| 754 | // using DPP. |
| 755 | if (ValDivergent) { |
| 756 | if (ScanImpl == ScanOptions::DPP) { |
| 757 | // First we need to set all inactive invocations to the identity value, so |
| 758 | // that they can correctly contribute to the final result. |
| 759 | NewV = |
| 760 | B.CreateIntrinsic(ID: Intrinsic::amdgcn_set_inactive, OverloadTypes: Ty, Args: {V, Identity}); |
| 761 | if (!NeedResult && ST.hasPermlane16Insts()) { |
| 762 | // On GFX10 the permlanex16 instruction helps us build a reduction |
| 763 | // without too many readlanes and writelanes, which are generally bad |
| 764 | // for performance. |
| 765 | NewV = buildReduction(B, Op: ScanOp, V: NewV, Identity); |
| 766 | } else { |
| 767 | NewV = buildScan(B, Op: ScanOp, V: NewV, Identity); |
| 768 | if (NeedResult) |
| 769 | ExclScan = buildShiftRight(B, V: NewV, Identity); |
| 770 | // Read the value from the last lane, which has accumulated the values |
| 771 | // of each active lane in the wavefront. This will be our new value |
| 772 | // which we will provide to the atomic operation. |
| 773 | Value *const LastLaneIdx = B.getInt32(C: ST.getWavefrontSize() - 1); |
| 774 | NewV = B.CreateIntrinsic(RetTy: Ty, ID: Intrinsic::amdgcn_readlane, |
| 775 | Args: {NewV, LastLaneIdx}); |
| 776 | } |
| 777 | // Finally mark the readlanes in the WWM section. |
| 778 | NewV = B.CreateIntrinsic(ID: Intrinsic::amdgcn_strict_wwm, OverloadTypes: Ty, Args: NewV); |
| 779 | } else if (ScanImpl == ScanOptions::Iterative) { |
| 780 | // Alternative implementation for scan |
| 781 | ComputeLoop = BasicBlock::Create(Context&: C, Name: "ComputeLoop" , Parent: F); |
| 782 | ComputeEnd = BasicBlock::Create(Context&: C, Name: "ComputeEnd" , Parent: F); |
| 783 | std::tie(args&: ExclScan, args&: NewV) = buildScanIteratively(B, Op: ScanOp, Identity, V, I, |
| 784 | ComputeLoop, ComputeEnd); |
| 785 | } else { |
| 786 | llvm_unreachable("Atomic Optimzer is disabled for None strategy" ); |
| 787 | } |
| 788 | } else { |
| 789 | switch (Op) { |
| 790 | default: |
| 791 | llvm_unreachable("Unhandled atomic op" ); |
| 792 | |
| 793 | case AtomicRMWInst::Add: |
| 794 | case AtomicRMWInst::Sub: { |
| 795 | // The new value we will be contributing to the atomic operation is the |
| 796 | // old value times the number of active lanes. |
| 797 | Value *const Ctpop = B.CreateIntCast( |
| 798 | V: B.CreateUnaryIntrinsic(ID: Intrinsic::ctpop, Op: Ballot), DestTy: Ty, isSigned: false); |
| 799 | NewV = buildMul(B, LHS: V, RHS: Ctpop); |
| 800 | break; |
| 801 | } |
| 802 | case AtomicRMWInst::FAdd: |
| 803 | case AtomicRMWInst::FSub: { |
| 804 | Value *const Ctpop = B.CreateIntCast( |
| 805 | V: B.CreateUnaryIntrinsic(ID: Intrinsic::ctpop, Op: Ballot), DestTy: Int32Ty, isSigned: false); |
| 806 | Value *const CtpopFP = B.CreateUIToFP(V: Ctpop, DestTy: Ty); |
| 807 | NewV = B.CreateFMul(L: V, R: CtpopFP); |
| 808 | break; |
| 809 | } |
| 810 | case AtomicRMWInst::And: |
| 811 | case AtomicRMWInst::Or: |
| 812 | case AtomicRMWInst::Max: |
| 813 | case AtomicRMWInst::Min: |
| 814 | case AtomicRMWInst::UMax: |
| 815 | case AtomicRMWInst::UMin: |
| 816 | case AtomicRMWInst::FMin: |
| 817 | case AtomicRMWInst::FMax: |
| 818 | // These operations with a uniform value are idempotent: doing the atomic |
| 819 | // operation multiple times has the same effect as doing it once. |
| 820 | NewV = V; |
| 821 | break; |
| 822 | |
| 823 | case AtomicRMWInst::Xor: |
| 824 | // The new value we will be contributing to the atomic operation is the |
| 825 | // old value times the parity of the number of active lanes. |
| 826 | Value *const Ctpop = B.CreateIntCast( |
| 827 | V: B.CreateUnaryIntrinsic(ID: Intrinsic::ctpop, Op: Ballot), DestTy: Ty, isSigned: false); |
| 828 | NewV = buildMul(B, LHS: V, RHS: B.CreateAnd(LHS: Ctpop, RHS: 1)); |
| 829 | break; |
| 830 | } |
| 831 | } |
| 832 | |
| 833 | // We only want a single lane to enter our new control flow, and we do this |
| 834 | // by checking if there are any active lanes below us. Only one lane will |
| 835 | // have 0 active lanes below us, so that will be the only one to progress. |
| 836 | Value *const Cond = B.CreateICmpEQ(LHS: Mbcnt, RHS: B.getInt32(C: 0)); |
| 837 | |
| 838 | // Store I's original basic block before we split the block. |
| 839 | BasicBlock *const OriginalBB = I.getParent(); |
| 840 | |
| 841 | // We need to introduce some new control flow to force a single lane to be |
| 842 | // active. We do this by splitting I's basic block at I, and introducing the |
| 843 | // new block such that: |
| 844 | // entry --> single_lane -\ |
| 845 | // \------------------> exit |
| 846 | Instruction *const SingleLaneTerminator = |
| 847 | SplitBlockAndInsertIfThen(Cond, SplitBefore: &I, Unreachable: false, BranchWeights: nullptr, DTU: &DTU, LI: nullptr); |
| 848 | |
| 849 | // At this point, we have split the I's block to allow one lane in wavefront |
| 850 | // to update the precomputed reduced value. Also, completed the codegen for |
| 851 | // new control flow i.e. iterative loop which perform reduction and scan using |
| 852 | // ComputeLoop and ComputeEnd. |
| 853 | // For the new control flow, we need to move branch instruction i.e. |
| 854 | // terminator created during SplitBlockAndInsertIfThen from I's block to |
| 855 | // ComputeEnd block. We also need to set up predecessor to next block when |
| 856 | // single lane done updating the final reduced value. |
| 857 | BasicBlock *Predecessor = nullptr; |
| 858 | if (ValDivergent && ScanImpl == ScanOptions::Iterative) { |
| 859 | // Move terminator from I's block to ComputeEnd block. |
| 860 | // |
| 861 | // OriginalBB is known to have a branch as terminator because |
| 862 | // SplitBlockAndInsertIfThen will have inserted one. |
| 863 | CondBrInst *Terminator = cast<CondBrInst>(Val: OriginalBB->getTerminator()); |
| 864 | B.SetInsertPoint(ComputeEnd); |
| 865 | Terminator->removeFromParent(); |
| 866 | B.Insert(I: Terminator); |
| 867 | |
| 868 | // Branch to ComputeLoop Block unconditionally from the I's block for |
| 869 | // iterative approach. |
| 870 | B.SetInsertPoint(OriginalBB); |
| 871 | B.CreateBr(Dest: ComputeLoop); |
| 872 | |
| 873 | // Update the dominator tree for new control flow. |
| 874 | SmallVector<DominatorTree::UpdateType, 6> DomTreeUpdates( |
| 875 | {{DominatorTree::Insert, OriginalBB, ComputeLoop}, |
| 876 | {DominatorTree::Insert, ComputeLoop, ComputeEnd}}); |
| 877 | |
| 878 | // We're moving the terminator from EntryBB to ComputeEnd, make sure we move |
| 879 | // the DT edges as well. |
| 880 | for (auto *Succ : Terminator->successors()) { |
| 881 | DomTreeUpdates.push_back(Elt: {DominatorTree::Insert, ComputeEnd, Succ}); |
| 882 | DomTreeUpdates.push_back(Elt: {DominatorTree::Delete, OriginalBB, Succ}); |
| 883 | } |
| 884 | |
| 885 | DTU.applyUpdates(Updates: DomTreeUpdates); |
| 886 | |
| 887 | Predecessor = ComputeEnd; |
| 888 | } else { |
| 889 | Predecessor = OriginalBB; |
| 890 | } |
| 891 | // Move the IR builder into single_lane next. |
| 892 | B.SetInsertPoint(SingleLaneTerminator); |
| 893 | |
| 894 | // Clone the original atomic operation into single lane, replacing the |
| 895 | // original value with our newly created one. |
| 896 | Instruction *const NewI = I.clone(); |
| 897 | B.Insert(I: NewI); |
| 898 | NewI->setOperand(i: ValIdx, Val: NewV); |
| 899 | |
| 900 | // Move the IR builder into exit next, and start inserting just before the |
| 901 | // original instruction. |
| 902 | B.SetInsertPoint(&I); |
| 903 | |
| 904 | if (NeedResult) { |
| 905 | // Create a PHI node to get our new atomic result into the exit block. |
| 906 | PHINode *const PHI = B.CreatePHI(Ty, NumReservedValues: 2); |
| 907 | PHI->addIncoming(V: PoisonValue::get(T: Ty), BB: Predecessor); |
| 908 | PHI->addIncoming(V: NewI, BB: SingleLaneTerminator->getParent()); |
| 909 | |
| 910 | // We need to broadcast the value who was the lowest active lane (the first |
| 911 | // lane) to all other lanes in the wavefront. |
| 912 | |
| 913 | Value *ReadlaneVal = PHI; |
| 914 | if (TyBitWidth < 32) |
| 915 | ReadlaneVal = B.CreateZExt(V: PHI, DestTy: B.getInt32Ty()); |
| 916 | |
| 917 | Value *BroadcastI = B.CreateIntrinsic( |
| 918 | RetTy: ReadlaneVal->getType(), ID: Intrinsic::amdgcn_readfirstlane, Args: ReadlaneVal); |
| 919 | if (TyBitWidth < 32) |
| 920 | BroadcastI = B.CreateTrunc(V: BroadcastI, DestTy: Ty); |
| 921 | |
| 922 | // Now that we have the result of our single atomic operation, we need to |
| 923 | // get our individual lane's slice into the result. We use the lane offset |
| 924 | // we previously calculated combined with the atomic result value we got |
| 925 | // from the first lane, to get our lane's index into the atomic result. |
| 926 | Value *LaneOffset = nullptr; |
| 927 | if (ValDivergent) { |
| 928 | if (ScanImpl == ScanOptions::DPP) { |
| 929 | LaneOffset = |
| 930 | B.CreateIntrinsic(ID: Intrinsic::amdgcn_strict_wwm, OverloadTypes: Ty, Args: ExclScan); |
| 931 | } else if (ScanImpl == ScanOptions::Iterative) { |
| 932 | LaneOffset = ExclScan; |
| 933 | } else { |
| 934 | llvm_unreachable("Atomic Optimzer is disabled for None strategy" ); |
| 935 | } |
| 936 | } else { |
| 937 | Mbcnt = isAtomicFloatingPointTy ? B.CreateUIToFP(V: Mbcnt, DestTy: Ty) |
| 938 | : B.CreateIntCast(V: Mbcnt, DestTy: Ty, isSigned: false); |
| 939 | switch (Op) { |
| 940 | default: |
| 941 | llvm_unreachable("Unhandled atomic op" ); |
| 942 | case AtomicRMWInst::Add: |
| 943 | case AtomicRMWInst::Sub: |
| 944 | LaneOffset = buildMul(B, LHS: V, RHS: Mbcnt); |
| 945 | break; |
| 946 | case AtomicRMWInst::And: |
| 947 | case AtomicRMWInst::Or: |
| 948 | case AtomicRMWInst::Max: |
| 949 | case AtomicRMWInst::Min: |
| 950 | case AtomicRMWInst::UMax: |
| 951 | case AtomicRMWInst::UMin: |
| 952 | case AtomicRMWInst::FMin: |
| 953 | case AtomicRMWInst::FMax: |
| 954 | LaneOffset = B.CreateSelect(C: Cond, True: Identity, False: V); |
| 955 | break; |
| 956 | case AtomicRMWInst::Xor: |
| 957 | LaneOffset = buildMul(B, LHS: V, RHS: B.CreateAnd(LHS: Mbcnt, RHS: 1)); |
| 958 | break; |
| 959 | case AtomicRMWInst::FAdd: |
| 960 | case AtomicRMWInst::FSub: { |
| 961 | LaneOffset = B.CreateFMul(L: V, R: Mbcnt); |
| 962 | break; |
| 963 | } |
| 964 | } |
| 965 | } |
| 966 | Value *Result = buildNonAtomicBinOp(B, Op, LHS: BroadcastI, RHS: LaneOffset); |
| 967 | if (isAtomicFloatingPointTy) { |
| 968 | // For fadd/fsub the first active lane of LaneOffset should be the |
| 969 | // identity (-0.0 for fadd or +0.0 for fsub) but the value we calculated |
| 970 | // is V * +0.0 which might have the wrong sign or might be nan (if V is |
| 971 | // inf or nan). |
| 972 | // |
| 973 | // For all floating point ops if the in-memory value was a nan then the |
| 974 | // binop we just built might have quieted it or changed its payload. |
| 975 | // |
| 976 | // Correct all these problems by using BroadcastI as the result in the |
| 977 | // first active lane. |
| 978 | Result = B.CreateSelect(C: Cond, True: BroadcastI, False: Result); |
| 979 | } |
| 980 | |
| 981 | if (IsPixelShader) { |
| 982 | // Need a final PHI to reconverge to above the helper lane branch mask. |
| 983 | B.SetInsertPoint(TheBB: PixelExitBB, IP: PixelExitBB->getFirstNonPHIIt()); |
| 984 | |
| 985 | PHINode *const PHI = B.CreatePHI(Ty, NumReservedValues: 2); |
| 986 | PHI->addIncoming(V: PoisonValue::get(T: Ty), BB: PixelEntryBB); |
| 987 | PHI->addIncoming(V: Result, BB: I.getParent()); |
| 988 | I.replaceAllUsesWith(V: PHI); |
| 989 | } else { |
| 990 | // Replace the original atomic instruction with the new one. |
| 991 | I.replaceAllUsesWith(V: Result); |
| 992 | } |
| 993 | } |
| 994 | |
| 995 | // And delete the original. |
| 996 | I.eraseFromParent(); |
| 997 | } |
| 998 | |
| 999 | INITIALIZE_PASS_BEGIN(AMDGPUAtomicOptimizer, DEBUG_TYPE, |
| 1000 | "AMDGPU atomic optimizations" , false, false) |
| 1001 | INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass) |
| 1002 | INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) |
| 1003 | INITIALIZE_PASS_END(AMDGPUAtomicOptimizer, DEBUG_TYPE, |
| 1004 | "AMDGPU atomic optimizations" , false, false) |
| 1005 | |
| 1006 | FunctionPass *llvm::createAMDGPUAtomicOptimizerPass(ScanOptions ScanStrategy) { |
| 1007 | return new AMDGPUAtomicOptimizer(ScanStrategy); |
| 1008 | } |
| 1009 | |