LLVM 24.0.0git
AMDGPUAtomicOptimizer.cpp
Go to the documentation of this file.
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"
29#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InstVisitor.h"
31#include "llvm/IR/IntrinsicsAMDGPU.h"
35
36#define DEBUG_TYPE "amdgpu-atomic-optimizer"
37
38using namespace llvm;
39using namespace llvm::AMDGPU;
40
41namespace {
42
43struct ReplacementInfo {
46 unsigned ValIdx;
47 bool ValDivergent;
48 bool IsLDS;
49};
50
51class AMDGPUAtomicOptimizer : public FunctionPass {
52public:
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 {
64 }
65};
66
67class AMDGPUAtomicOptimizerImpl
68 : public InstVisitor<AMDGPUAtomicOptimizerImpl> {
69private:
70 Function &F;
72 const UniformityInfo &UA;
73 const DataLayout &DL;
74 DomTreeUpdater &DTU;
75 const GCNSubtarget &ST;
76 bool IsPixelShader;
77 ScanOptions ScanImpl;
78
80 Value *const Identity) const;
81 Value *buildShiftRight(IRBuilder<> &B, Value *V, Value *const Identity) const;
82
83 std::pair<Value *, Value *>
84 buildScanIteratively(IRBuilder<> &B, AtomicRMWInst::BinOp Op,
85 Value *const Identity, Value *V, Instruction &I,
86 BasicBlock *ComputeLoop, BasicBlock *ComputeEnd) const;
87
88 void optimizeAtomic(Instruction &I, AtomicRMWInst::BinOp Op, unsigned ValIdx,
89 bool ValDivergent, bool IsLDS) const;
90
91public:
92 AMDGPUAtomicOptimizerImpl() = delete;
93
94 AMDGPUAtomicOptimizerImpl(Function &F, const UniformityInfo &UA,
95 DomTreeUpdater &DTU, const GCNSubtarget &ST,
96 ScanOptions ScanImpl)
97 : F(F), UA(UA), DL(F.getDataLayout()), DTU(DTU), ST(ST),
98 IsPixelShader(F.getCallingConv() == CallingConv::AMDGPU_PS),
99 ScanImpl(ScanImpl) {}
100
101 bool run();
102
103 void visitAtomicRMWInst(AtomicRMWInst &I);
104 void visitIntrinsicInst(IntrinsicInst &I);
105};
106
107} // namespace
108
109char AMDGPUAtomicOptimizer::ID = 0;
110
111char &llvm::AMDGPUAtomicOptimizerID = AMDGPUAtomicOptimizer::ID;
112
113bool AMDGPUAtomicOptimizer::runOnFunction(Function &F) {
114 if (skipFunction(F)) {
115 return false;
116 }
117
118 const UniformityInfo &UA =
119 getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
120
122 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
123 DomTreeUpdater DTU(DTW ? &DTW->getDomTree() : nullptr,
124 DomTreeUpdater::UpdateStrategy::Lazy);
125
126 const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
127 const TargetMachine &TM = TPC.getTM<TargetMachine>();
128 const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
129
130 return AMDGPUAtomicOptimizerImpl(F, UA, DTU, ST, ScanImpl).run();
131}
132
135 const auto &UA = AM.getResult<UniformityInfoAnalysis>(F);
136
138 DomTreeUpdater::UpdateStrategy::Lazy);
139 const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
140
141 bool IsChanged = AMDGPUAtomicOptimizerImpl(F, UA, DTU, ST, ScanImpl).run();
142
143 if (!IsChanged) {
144 return PreservedAnalyses::all();
145 }
146
149 return PA;
150}
151
152bool AMDGPUAtomicOptimizerImpl::run() {
153 // Scan option None disables the Pass
154 if (ScanImpl == ScanOptions::None)
155 return false;
156 if (ST.isSingleLaneExecution(F))
157 return false;
158
159 visit(F);
160 if (ToReplace.empty())
161 return false;
162
163 for (auto &[I, Op, ValIdx, ValDivergent, IsLDS] : ToReplace)
164 optimizeAtomic(*I, Op, ValIdx, ValDivergent, IsLDS);
165 ToReplace.clear();
166 return true;
167}
168
169static bool isLegalCrossLaneType(Type *Ty) {
170 switch (Ty->getTypeID()) {
171 case Type::FloatTyID:
172 case Type::DoubleTyID:
173 return true;
174 case Type::IntegerTyID: {
175 unsigned Size = Ty->getIntegerBitWidth();
176 return (Size == 32 || Size == 64);
177 }
178 default:
179 return false;
180 }
181}
182
183void AMDGPUAtomicOptimizerImpl::visitAtomicRMWInst(AtomicRMWInst &I) {
184 if (I.getType()->isVectorTy() || I.isVolatile())
185 return;
186
187 // Early exit for unhandled address space atomic instructions.
188 switch (I.getPointerAddressSpace()) {
189 default:
190 return;
193 break;
194 }
195
196 AtomicRMWInst::BinOp Op = I.getOperation();
197
198 switch (Op) {
199 default:
200 return;
214 break;
215 }
216
217 // Only 32 and 64 bit floating point atomic ops are supported.
219 !(I.getType()->isFloatTy() || I.getType()->isDoubleTy())) {
220 return;
221 }
222
223 const unsigned PtrIdx = 0;
224 const unsigned ValIdx = 1;
225
226 // If the pointer operand is divergent, then each lane is doing an atomic
227 // operation on a different address, and we cannot optimize that.
228 if (UA.isDivergentAtUse(I.getOperandUse(PtrIdx))) {
229 return;
230 }
231
232 bool ValDivergent = UA.isDivergentAtUse(I.getOperandUse(ValIdx));
233
234 // If the value operand is divergent, each lane is contributing a different
235 // value to the atomic calculation. We can only optimize divergent values if
236 // we have DPP available on our subtarget (for DPP strategy), and the atomic
237 // operation is 32 or 64 bits.
238 if (ValDivergent) {
239 if (ScanImpl == ScanOptions::DPP && !ST.hasDPP())
240 return;
241
242 if (!isLegalCrossLaneType(I.getType()))
243 return;
244 }
245
246 const bool IsLDS = I.getPointerAddressSpace() == AMDGPUAS::LOCAL_ADDRESS;
247
248 // The iterative scan runs once per active lane and costs more than the
249 // hardware serialization of a native LDS atomic.
250 if (IsLDS && ValDivergent && ScanImpl == ScanOptions::Iterative &&
252 TargetLowering::AtomicExpansionKind::None)
253 return;
254
255 // If we get here, we can optimize the atomic using a single wavefront-wide
256 // atomic operation to do the calculation for the entire wavefront, so
257 // remember the instruction so we can come back to it.
258 ToReplace.push_back({&I, Op, ValIdx, ValDivergent, IsLDS});
259}
260
261void AMDGPUAtomicOptimizerImpl::visitIntrinsicInst(IntrinsicInst &I) {
262 if (I.getType()->isVectorTy())
263 return;
264
266
267 switch (I.getIntrinsicID()) {
268 default:
269 return;
270 case Intrinsic::amdgcn_struct_buffer_atomic_add:
271 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_add:
272 case Intrinsic::amdgcn_raw_buffer_atomic_add:
273 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_add:
275 break;
276 case Intrinsic::amdgcn_struct_buffer_atomic_sub:
277 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub:
278 case Intrinsic::amdgcn_raw_buffer_atomic_sub:
279 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub:
281 break;
282 case Intrinsic::amdgcn_struct_buffer_atomic_and:
283 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_and:
284 case Intrinsic::amdgcn_raw_buffer_atomic_and:
285 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_and:
287 break;
288 case Intrinsic::amdgcn_struct_buffer_atomic_or:
289 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_or:
290 case Intrinsic::amdgcn_raw_buffer_atomic_or:
291 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_or:
293 break;
294 case Intrinsic::amdgcn_struct_buffer_atomic_xor:
295 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_xor:
296 case Intrinsic::amdgcn_raw_buffer_atomic_xor:
297 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_xor:
299 break;
300 case Intrinsic::amdgcn_struct_buffer_atomic_smin:
301 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smin:
302 case Intrinsic::amdgcn_raw_buffer_atomic_smin:
303 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smin:
305 break;
306 case Intrinsic::amdgcn_struct_buffer_atomic_umin:
307 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umin:
308 case Intrinsic::amdgcn_raw_buffer_atomic_umin:
309 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umin:
311 break;
312 case Intrinsic::amdgcn_struct_buffer_atomic_smax:
313 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smax:
314 case Intrinsic::amdgcn_raw_buffer_atomic_smax:
315 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smax:
317 break;
318 case Intrinsic::amdgcn_struct_buffer_atomic_umax:
319 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umax:
320 case Intrinsic::amdgcn_raw_buffer_atomic_umax:
321 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umax:
323 break;
324 }
325
326 auto *Aux = cast<ConstantInt>(I.getArgOperand(I.arg_size() - 1));
327 if (Aux->getZExtValue() & AMDGPU::CPol::VOLATILE)
328 return;
329
330 const unsigned ValIdx = 0;
331
332 const bool ValDivergent = UA.isDivergentAtUse(I.getOperandUse(ValIdx));
333
334 // If the value operand is divergent, each lane is contributing a different
335 // value to the atomic calculation. We can only optimize divergent values if
336 // we have DPP available on our subtarget (for DPP strategy), and the atomic
337 // operation is 32 or 64 bits.
338 if (ValDivergent) {
339 if (ScanImpl == ScanOptions::DPP && !ST.hasDPP())
340 return;
341
342 if (!isLegalCrossLaneType(I.getType()))
343 return;
344 }
345
346 // If any of the other arguments to the intrinsic are divergent, we can't
347 // optimize the operation.
348 for (unsigned Idx = 1; Idx < I.getNumOperands(); Idx++) {
349 if (UA.isDivergentAtUse(I.getOperandUse(Idx)))
350 return;
351 }
352
353 // If we get here, we can optimize the atomic using a single wavefront-wide
354 // atomic operation to do the calculation for the entire wavefront, so
355 // remember the instruction so we can come back to it.
356 // Buffer atomics are never LDS.
357 ToReplace.push_back({&I, Op, ValIdx, ValDivergent, /*IsLDS=*/false});
358}
359
360// Use the builder to create the non-atomic counterpart of the specified
361// atomicrmw binary op.
363 Value *LHS, Value *RHS) {
365
366 switch (Op) {
367 default:
368 llvm_unreachable("Unhandled atomic op");
370 return B.CreateBinOp(Instruction::Add, LHS, RHS);
372 return B.CreateFAdd(LHS, RHS);
374 return B.CreateBinOp(Instruction::Sub, LHS, RHS);
376 return B.CreateFSub(LHS, RHS);
378 return B.CreateBinOp(Instruction::And, LHS, RHS);
380 return B.CreateBinOp(Instruction::Or, LHS, RHS);
382 return B.CreateBinOp(Instruction::Xor, LHS, RHS);
383
385 Pred = CmpInst::ICMP_SGT;
386 break;
388 Pred = CmpInst::ICMP_SLT;
389 break;
391 Pred = CmpInst::ICMP_UGT;
392 break;
394 Pred = CmpInst::ICMP_ULT;
395 break;
397 return B.CreateMaxNum(LHS, RHS);
399 return B.CreateMinNum(LHS, RHS);
400 }
401 Value *Cond = B.CreateICmp(Pred, LHS, RHS);
402 return B.CreateSelect(Cond, LHS, RHS);
403}
404
405// Use the builder to create an inclusive scan of V across the wavefront, with
406// all lanes active.
407Value *AMDGPUAtomicOptimizerImpl::buildScan(IRBuilder<> &B,
409 Value *Identity) const {
410 Type *AtomicTy = V->getType();
411 Module *M = B.getModule();
413 M, Intrinsic::amdgcn_update_dpp, AtomicTy);
414
415 for (unsigned Idx = 0; Idx < 4; Idx++) {
417 B, Op, V,
418 B.CreateCall(UpdateDPP,
419 {Identity, V, B.getInt32(DPP::ROW_SHR0 | 1 << Idx),
420 B.getInt32(0xf), B.getInt32(0xf), B.getFalse()}));
421 }
422 if (ST.hasDPPBroadcasts()) {
423 // GFX9 has DPP row broadcast operations.
425 B, Op, V,
426 B.CreateCall(UpdateDPP,
427 {Identity, V, B.getInt32(DPP::BCAST15), B.getInt32(0xa),
428 B.getInt32(0xf), B.getFalse()}));
430 B, Op, V,
431 B.CreateCall(UpdateDPP,
432 {Identity, V, B.getInt32(DPP::BCAST31), B.getInt32(0xc),
433 B.getInt32(0xf), B.getFalse()}));
434 } else {
435 // On GFX10 all DPP operations are confined to a single row. To get cross-
436 // row operations we have to use permlane or readlane.
437
438 // Combine lane 15 into lanes 16..31 (and, for wave 64, lane 47 into lanes
439 // 48..63).
440 assert(ST.hasPermlane16Insts());
441 Value *PermX =
442 B.CreateIntrinsic(AtomicTy, Intrinsic::amdgcn_permlanex16,
443 {PoisonValue::get(AtomicTy), V, B.getInt32(-1),
444 B.getInt32(-1), B.getFalse(), B.getFalse()});
445
446 Value *UpdateDPPCall = B.CreateCall(
447 UpdateDPP, {Identity, PermX, B.getInt32(DPP::QUAD_PERM_ID),
448 B.getInt32(0xa), B.getInt32(0xf), B.getFalse()});
449 V = buildNonAtomicBinOp(B, Op, V, UpdateDPPCall);
450
451 if (!ST.isWave32()) {
452 // Combine lane 31 into lanes 32..63.
453 Value *const Lane31 = B.CreateIntrinsic(
454 AtomicTy, Intrinsic::amdgcn_readlane, {V, B.getInt32(31)});
455
456 Value *UpdateDPPCall = B.CreateCall(
457 UpdateDPP, {Identity, Lane31, B.getInt32(DPP::QUAD_PERM_ID),
458 B.getInt32(0xc), B.getInt32(0xf), B.getFalse()});
459
460 V = buildNonAtomicBinOp(B, Op, V, UpdateDPPCall);
461 }
462 }
463 return V;
464}
465
466// Use the builder to create a shift right of V across the wavefront, with all
467// lanes active, to turn an inclusive scan into an exclusive scan.
468Value *AMDGPUAtomicOptimizerImpl::buildShiftRight(IRBuilder<> &B, Value *V,
469 Value *Identity) const {
470 Type *AtomicTy = V->getType();
471 Module *M = B.getModule();
473 M, Intrinsic::amdgcn_update_dpp, AtomicTy);
474 if (ST.hasDPPWavefrontShifts()) {
475 // GFX9 has DPP wavefront shift operations.
476 V = B.CreateCall(UpdateDPP,
477 {Identity, V, B.getInt32(DPP::WAVE_SHR1), B.getInt32(0xf),
478 B.getInt32(0xf), B.getFalse()});
479 } else {
481 M, Intrinsic::amdgcn_readlane, AtomicTy);
483 M, Intrinsic::amdgcn_writelane, AtomicTy);
484
485 // On GFX10 all DPP operations are confined to a single row. To get cross-
486 // row operations we have to use permlane or readlane.
487 Value *Old = V;
488 V = B.CreateCall(UpdateDPP,
489 {Identity, V, B.getInt32(DPP::ROW_SHR0 + 1),
490 B.getInt32(0xf), B.getInt32(0xf), B.getFalse()});
491
492 // Copy the old lane 15 to the new lane 16.
493 V = B.CreateCall(WriteLane, {B.CreateCall(ReadLane, {Old, B.getInt32(15)}),
494 B.getInt32(16), V});
495
496 if (!ST.isWave32()) {
497 // Copy the old lane 31 to the new lane 32.
498 V = B.CreateCall(
499 WriteLane,
500 {B.CreateCall(ReadLane, {Old, B.getInt32(31)}), B.getInt32(32), V});
501
502 // Copy the old lane 47 to the new lane 48.
503 V = B.CreateCall(
504 WriteLane,
505 {B.CreateCall(ReadLane, {Old, B.getInt32(47)}), B.getInt32(48), V});
506 }
507 }
508
509 return V;
510}
511
512// Use the builder to create an exclusive scan and compute the final reduced
513// value using an iterative approach. This provides an alternative
514// implementation to DPP which uses WMM for scan computations. This API iterate
515// over active lanes to read, compute and update the value using
516// readlane and writelane intrinsics.
517std::pair<Value *, Value *> AMDGPUAtomicOptimizerImpl::buildScanIteratively(
518 IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *const Identity, Value *V,
519 Instruction &I, BasicBlock *ComputeLoop, BasicBlock *ComputeEnd) const {
520 auto *Ty = I.getType();
521 auto *WaveTy = B.getIntNTy(ST.getWavefrontSize());
522 auto *EntryBB = I.getParent();
523
524 auto *Ballot =
525 B.CreateIntrinsic(Intrinsic::amdgcn_ballot, WaveTy, B.getTrue());
526
527 // Start inserting instructions for ComputeLoop block
528 B.SetInsertPoint(ComputeLoop);
529 // Phi nodes for Accumulator, Scan results destination, and Active Lanes
530 auto *Accumulator = B.CreatePHI(Ty, 2, "Accumulator");
531 Accumulator->addIncoming(Identity, EntryBB);
532 auto *OldValuePhi = B.CreatePHI(Ty, 2, "OldValuePhi");
533 OldValuePhi->addIncoming(PoisonValue::get(Ty), EntryBB);
534 auto *ActiveBits = B.CreatePHI(WaveTy, 2, "ActiveBits");
535 ActiveBits->addIncoming(Ballot, EntryBB);
536
537 // Use llvm.cttz intrinsic to find the lowest remaining active lane.
538 auto *FF1 =
539 B.CreateIntrinsic(Intrinsic::cttz, WaveTy, {ActiveBits, B.getTrue()});
540
541 auto *LaneIdxInt = B.CreateTrunc(FF1, B.getInt32Ty());
542
543 // Get the value required for atomic operation
544 Value *LaneValue = B.CreateIntrinsic(V->getType(), Intrinsic::amdgcn_readlane,
545 {V, LaneIdxInt});
546
547 // Perform writelane because intermediate scan results are required later in
548 // the kernel computations
549 Value *OldValue = B.CreateIntrinsic(V->getType(), Intrinsic::amdgcn_writelane,
550 {Accumulator, LaneIdxInt, OldValuePhi});
551 OldValuePhi->addIncoming(OldValue, ComputeLoop);
552
553 // Accumulate the results
554 auto *NewAccumulator = buildNonAtomicBinOp(B, Op, Accumulator, LaneValue);
555 Accumulator->addIncoming(NewAccumulator, ComputeLoop);
556
557 // Set bit to zero of current active lane so that for next iteration llvm.cttz
558 // return the next active lane
559 auto *Mask = B.CreateShl(ConstantInt::get(WaveTy, 1), FF1);
560
561 auto *InverseMask = B.CreateXor(Mask, ConstantInt::getAllOnesValue(WaveTy));
562 auto *NewActiveBits = B.CreateAnd(ActiveBits, InverseMask);
563 ActiveBits->addIncoming(NewActiveBits, ComputeLoop);
564
565 // Branch out of the loop when all lanes are processed.
566 auto *IsEnd = B.CreateICmpEQ(NewActiveBits, ConstantInt::get(WaveTy, 0));
567 B.CreateCondBr(IsEnd, ComputeEnd, ComputeLoop);
568
569 B.SetInsertPoint(ComputeEnd);
570
571 return {OldValue, NewAccumulator};
572}
573
576 LLVMContext &C = Ty->getContext();
577 const unsigned BitWidth = Ty->getPrimitiveSizeInBits();
578 switch (Op) {
579 default:
580 llvm_unreachable("Unhandled atomic op");
586 return ConstantInt::get(C, APInt::getMinValue(BitWidth));
589 return ConstantInt::get(C, APInt::getMaxValue(BitWidth));
591 return ConstantInt::get(C, APInt::getSignedMinValue(BitWidth));
593 return ConstantInt::get(C, APInt::getSignedMaxValue(BitWidth));
595 return ConstantFP::get(C, APFloat::getZero(Ty->getFltSemantics(), true));
597 return ConstantFP::get(C, APFloat::getZero(Ty->getFltSemantics(), false));
600 // FIXME: atomicrmw fmax/fmin behave like llvm.maxnum/minnum so NaN is the
601 // closest thing they have to an identity, but it still does not preserve
602 // the difference between quiet and signaling NaNs or NaNs with different
603 // payloads.
604 return ConstantFP::get(C, APFloat::getNaN(Ty->getFltSemantics()));
605 }
606}
607
609 switch (Op) {
610 default:
612 "Atomic Op yet to be ported to use Wave Reduction intrinsics.");
615 return Intrinsic::amdgcn_wave_reduce_add;
618 return Intrinsic::amdgcn_wave_reduce_fadd;
620 return Intrinsic::amdgcn_wave_reduce_and;
622 return Intrinsic::amdgcn_wave_reduce_or;
624 return Intrinsic::amdgcn_wave_reduce_xor;
626 return Intrinsic::amdgcn_wave_reduce_umax;
628 return Intrinsic::amdgcn_wave_reduce_max;
630 return Intrinsic::amdgcn_wave_reduce_fmax;
632 return Intrinsic::amdgcn_wave_reduce_umin;
634 return Intrinsic::amdgcn_wave_reduce_min;
636 return Intrinsic::amdgcn_wave_reduce_fmin;
637 }
638}
639
642 return (CI && CI->isOne()) ? RHS : B.CreateMul(LHS, RHS);
643}
644
645void AMDGPUAtomicOptimizerImpl::optimizeAtomic(Instruction &I,
647 unsigned ValIdx,
648 bool ValDivergent,
649 bool IsLDS) const {
650 // Don't generate a DPP scan if !amdgpu.expected.active.lane hint indicates
651 // insufficient lanes to offset fixed overhead.
652
653 // FIXME: The threshold was tuned empirically on gfx11 and gfx12. The DPP scan
654 // overhead differs across subtargets, so the break-even point may differ too;
655 // this may need to become subtarget-dependent.
656 if (IsLDS && ValDivergent && ScanImpl == ScanOptions::DPP) {
657 if (MDNode *MD = I.getMetadata("amdgpu.expected.active.lanes")) {
658 auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
659 constexpr unsigned ActiveLanesThreshold = 5;
660 if (CI->getValue().ule(ActiveLanesThreshold))
661 return;
662 }
663 }
664
665 // Start building just before the instruction.
666 IRBuilder<> B(&I);
667
669 B.setIsFPConstrained(I.getFunction()->hasFnAttribute(Attribute::StrictFP));
670 }
671
672 // If we are in a pixel shader, because of how we have to mask out helper
673 // lane invocations, we need to record the entry and exit BB's.
674 BasicBlock *PixelEntryBB = nullptr;
675 BasicBlock *PixelExitBB = nullptr;
676
677 // If we're optimizing an atomic within a pixel shader, we need to wrap the
678 // entire atomic operation in a helper-lane check. We do not want any helper
679 // lanes that are around only for the purposes of derivatives to take part
680 // in any cross-lane communication, and we use a branch on whether the lane is
681 // live to do this.
682 if (IsPixelShader) {
683 // Record I's original position as the entry block.
684 PixelEntryBB = I.getParent();
685
686 Value *const Cond = B.CreateIntrinsic(Intrinsic::amdgcn_ps_live, {});
687 Instruction *const NonHelperTerminator =
688 SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, &DTU, nullptr);
689
690 // Record I's new position as the exit block.
691 PixelExitBB = I.getParent();
692
693 I.moveBefore(NonHelperTerminator->getIterator());
694 B.SetInsertPoint(&I);
695 }
696
697 Type *const Ty = I.getType();
698 Type *Int32Ty = B.getInt32Ty();
699 bool isAtomicFloatingPointTy = Ty->isFloatingPointTy();
700 [[maybe_unused]] const unsigned TyBitWidth = DL.getTypeSizeInBits(Ty);
701
702 // This is the value in the atomic operation we need to combine in order to
703 // reduce the number of atomic operations.
704 Value *V = I.getOperand(ValIdx);
705
706 // We need to know how many lanes are active within the wavefront, and we do
707 // this by doing a ballot of active lanes.
708 Type *const WaveTy = B.getIntNTy(ST.getWavefrontSize());
709 CallInst *const Ballot = B.CreateIntrinsicWithoutFolding(
710 Intrinsic::amdgcn_ballot, WaveTy, B.getTrue());
711
712 // We need to know how many lanes are active within the wavefront that are
713 // below us. If we counted each lane linearly starting from 0, a lane is
714 // below us only if its associated index was less than ours. We do this by
715 // using the mbcnt intrinsic.
716 Value *Mbcnt;
717 if (ST.isWave32()) {
718 Mbcnt =
719 B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_lo, {Ballot, B.getInt32(0)});
720 } else {
721 Value *const ExtractLo = B.CreateTrunc(Ballot, Int32Ty);
722 Value *const ExtractHi = B.CreateTrunc(B.CreateLShr(Ballot, 32), Int32Ty);
723 Mbcnt = B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_lo,
724 {ExtractLo, B.getInt32(0)});
725 Mbcnt = B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_hi, {ExtractHi, Mbcnt});
726 }
727
728 Function *F = I.getFunction();
729 LLVMContext &C = F->getContext();
730 const bool NeedResult = !I.use_empty();
731 const bool UseWaveReductionIntrinsic = !ValDivergent || !NeedResult;
732
733 // For atomic sub, perform scan with add operation and allow one lane to
734 // subtract the reduced value later.
735 AtomicRMWInst::BinOp ScanOp = Op;
736 if (Op == AtomicRMWInst::Sub) {
737 ScanOp = AtomicRMWInst::Add;
738 } else if (Op == AtomicRMWInst::FSub) {
739 ScanOp = AtomicRMWInst::FAdd;
740 }
741 Value *Identity = getIdentityValueForAtomicOp(Ty, ScanOp);
742
743 Value *ExclScan = nullptr;
744 Value *NewV = nullptr;
745
746 BasicBlock *ComputeLoop = nullptr;
747 BasicBlock *ComputeEnd = nullptr;
748 if (UseWaveReductionIntrinsic) {
749 // Build reductions with wave-reduce intrinsics.
750 unsigned Strategy = ScanImpl == ScanOptions::DPP ? 2 : 1;
751 Intrinsic::ID WaveRedIntrinsic = getWaveReductionIntrinsic(Op);
752 NewV = B.CreateIntrinsic(WaveRedIntrinsic, Ty, {V, B.getInt32(Strategy)});
753 } else {
754 // If we have a divergent value in each lane, we need to combine the value
755 // using DPP.
756 assert(ValDivergent && NeedResult);
757 if (ScanImpl == ScanOptions::DPP) {
758 // First we need to set all inactive invocations to the identity value,
759 // so that they can correctly contribute to the final result.
760 NewV =
761 B.CreateIntrinsic(Intrinsic::amdgcn_set_inactive, Ty, {V, Identity});
762 NewV = buildScan(B, ScanOp, NewV, Identity);
763 ExclScan = buildShiftRight(B, NewV, Identity);
764 // Read the value from the last lane, which has accumulated the values
765 // of each active lane in the wavefront. This will be our new value
766 // which we will provide to the atomic operation.
767 Value *const LastLaneIdx = B.getInt32(ST.getWavefrontSize() - 1);
768 NewV = B.CreateIntrinsic(Ty, Intrinsic::amdgcn_readlane,
769 {NewV, LastLaneIdx});
770 // Finally mark the readlanes in the WWM section.
771 NewV = B.CreateIntrinsic(Intrinsic::amdgcn_strict_wwm, Ty, NewV);
772 } else if (ScanImpl == ScanOptions::Iterative) {
773 // Alternative implementation for scan
774 ComputeLoop = BasicBlock::Create(C, "ComputeLoop", F);
775 ComputeEnd = BasicBlock::Create(C, "ComputeEnd", F);
776 std::tie(ExclScan, NewV) = buildScanIteratively(B, ScanOp, Identity, V, I,
777 ComputeLoop, ComputeEnd);
778 } else {
779 llvm_unreachable("Atomic Optimzer is disabled for None strategy");
780 }
781 }
782
783 // We only want a single lane to enter our new control flow, and we do this
784 // by checking if there are any active lanes below us. Only one lane will
785 // have 0 active lanes below us, so that will be the only one to progress.
786 Value *const Cond = B.CreateICmpEQ(Mbcnt, B.getInt32(0));
787
788 // Store I's original basic block before we split the block.
789 BasicBlock *const OriginalBB = I.getParent();
790
791 // We need to introduce some new control flow to force a single lane to be
792 // active. We do this by splitting I's basic block at I, and introducing the
793 // new block such that:
794 // entry --> single_lane -\
795 // \------------------> exit
796 Instruction *const SingleLaneTerminator =
797 SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, &DTU, nullptr);
798
799 // At this point, we have split the I's block to allow one lane in wavefront
800 // to update the precomputed reduced value. Also, completed the codegen for
801 // new control flow i.e. iterative loop which perform reduction and scan using
802 // ComputeLoop and ComputeEnd.
803 // For the new control flow, we need to move branch instruction i.e.
804 // terminator created during SplitBlockAndInsertIfThen from I's block to
805 // ComputeEnd block. We also need to set up predecessor to next block when
806 // single lane done updating the final reduced value.
807 BasicBlock *Predecessor = nullptr;
808 if (!UseWaveReductionIntrinsic && ScanImpl == ScanOptions::Iterative) {
809 // Move terminator from I's block to ComputeEnd block.
810 //
811 // OriginalBB is known to have a branch as terminator because
812 // SplitBlockAndInsertIfThen will have inserted one.
813 CondBrInst *Terminator = cast<CondBrInst>(OriginalBB->getTerminator());
814 B.SetInsertPoint(ComputeEnd);
815 Terminator->removeFromParent();
816 B.Insert(Terminator);
817
818 // Branch to ComputeLoop Block unconditionally from the I's block for
819 // iterative approach.
820 B.SetInsertPoint(OriginalBB);
821 B.CreateBr(ComputeLoop);
822
823 // Update the dominator tree for new control flow.
825 {{DominatorTree::Insert, OriginalBB, ComputeLoop},
826 {DominatorTree::Insert, ComputeLoop, ComputeEnd}});
827
828 // We're moving the terminator from EntryBB to ComputeEnd, make sure we move
829 // the DT edges as well.
830 for (auto *Succ : Terminator->successors()) {
831 DomTreeUpdates.push_back({DominatorTree::Insert, ComputeEnd, Succ});
832 DomTreeUpdates.push_back({DominatorTree::Delete, OriginalBB, Succ});
833 }
834
835 DTU.applyUpdates(DomTreeUpdates);
836
837 Predecessor = ComputeEnd;
838 } else {
839 Predecessor = OriginalBB;
840 }
841 // Move the IR builder into single_lane next.
842 B.SetInsertPoint(SingleLaneTerminator);
843
844 // Clone the original atomic operation into single lane, replacing the
845 // original value with our newly created one.
846 Instruction *const NewI = I.clone();
847 B.Insert(NewI);
848 NewI->setOperand(ValIdx, NewV);
849
850 // Move the IR builder into exit next, and start inserting just before the
851 // original instruction.
852 B.SetInsertPoint(&I);
853
854 if (NeedResult) {
855 // Create a PHI node to get our new atomic result into the exit block.
856 PHINode *const PHI = B.CreatePHI(Ty, 2);
857 PHI->addIncoming(PoisonValue::get(Ty), Predecessor);
858 PHI->addIncoming(NewI, SingleLaneTerminator->getParent());
859
860 // We need to broadcast the value who was the lowest active lane (the first
861 // lane) to all other lanes in the wavefront.
862
863 Value *ReadlaneVal = PHI;
864 if (TyBitWidth < 32)
865 ReadlaneVal = B.CreateZExt(PHI, B.getInt32Ty());
866
867 Value *BroadcastI = B.CreateIntrinsic(
868 ReadlaneVal->getType(), Intrinsic::amdgcn_readfirstlane, ReadlaneVal);
869 if (TyBitWidth < 32)
870 BroadcastI = B.CreateTrunc(BroadcastI, Ty);
871
872 // Now that we have the result of our single atomic operation, we need to
873 // get our individual lane's slice into the result. We use the lane offset
874 // we previously calculated combined with the atomic result value we got
875 // from the first lane, to get our lane's index into the atomic result.
876 Value *LaneOffset = nullptr;
877 if (ValDivergent) {
878 if (ScanImpl == ScanOptions::DPP) {
879 LaneOffset =
880 B.CreateIntrinsic(Intrinsic::amdgcn_strict_wwm, Ty, ExclScan);
881 } else if (ScanImpl == ScanOptions::Iterative) {
882 LaneOffset = ExclScan;
883 } else {
884 llvm_unreachable("Atomic Optimzer is disabled for None strategy");
885 }
886 } else {
887 Mbcnt = isAtomicFloatingPointTy ? B.CreateUIToFP(Mbcnt, Ty)
888 : B.CreateIntCast(Mbcnt, Ty, false);
889 switch (Op) {
890 default:
891 llvm_unreachable("Unhandled atomic op");
894 LaneOffset = buildMul(B, V, Mbcnt);
895 break;
904 LaneOffset = B.CreateSelect(Cond, Identity, V);
905 break;
907 LaneOffset = buildMul(B, V, B.CreateAnd(Mbcnt, 1));
908 break;
910 case AtomicRMWInst::FSub: {
911 LaneOffset = B.CreateFMul(V, Mbcnt);
912 break;
913 }
914 }
915 }
916 Value *Result = buildNonAtomicBinOp(B, Op, BroadcastI, LaneOffset);
917 if (isAtomicFloatingPointTy) {
918 // For fadd/fsub the first active lane of LaneOffset should be the
919 // identity (-0.0 for fadd or +0.0 for fsub) but the value we calculated
920 // is V * +0.0 which might have the wrong sign or might be nan (if V is
921 // inf or nan).
922 //
923 // For all floating point ops if the in-memory value was a nan then the
924 // binop we just built might have quieted it or changed its payload.
925 //
926 // Correct all these problems by using BroadcastI as the result in the
927 // first active lane.
928 Result = B.CreateSelect(Cond, BroadcastI, Result);
929 }
930
931 if (IsPixelShader) {
932 // Need a final PHI to reconverge to above the helper lane branch mask.
933 B.SetInsertPoint(PixelExitBB->getFirstNonPHIIt());
934
935 PHINode *const PHI = B.CreatePHI(Ty, 2);
936 PHI->addIncoming(PoisonValue::get(Ty), PixelEntryBB);
937 PHI->addIncoming(Result, I.getParent());
938 I.replaceAllUsesWith(PHI);
939 } else {
940 // Replace the original atomic instruction with the new one.
941 I.replaceAllUsesWith(Result);
942 }
943 }
944
945 // And delete the original.
946 I.eraseFromParent();
947}
948
949INITIALIZE_PASS_BEGIN(AMDGPUAtomicOptimizer, DEBUG_TYPE,
950 "AMDGPU atomic optimizations", false, false)
953INITIALIZE_PASS_END(AMDGPUAtomicOptimizer, DEBUG_TYPE,
954 "AMDGPU atomic optimizations", false, false)
955
957 return new AMDGPUAtomicOptimizer(ScanStrategy);
958}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static Constant * getIdentityValueForAtomicOp(Type *const Ty, AtomicRMWInst::BinOp Op)
static bool isLegalCrossLaneType(Type *Ty)
static Value * buildMul(IRBuilder<> &B, Value *LHS, Value *RHS)
static Value * buildNonAtomicBinOp(IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *LHS, Value *RHS)
static Intrinsic::ID getWaveReductionIntrinsic(AtomicRMWInst::BinOp Op)
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool runOnFunction(Function &F, bool PostInlining)
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
SmallVector< MachineOperand, 4 > Cond
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
Target-Independent Code Generator Pass Configuration Options pass.
LLVM IR instance of the generic uniformity analysis.
Value * RHS
Value * LHS
bool isSingleLaneExecution(const Function &Kernel) const
Return true if only a single workitem can be active in a wave.
unsigned getWavefrontSize() const
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1213
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1183
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
an instruction that atomically reads a memory location, combines it with another value,...
static bool isFPOperation(BinOp Op)
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ FSub
*p = old - v
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
DominatorTree & getDomTree()
Definition Dominators.h:285
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
const SITargetLowering * getTargetLowering() const override
bool isWave32() const
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
bool isDivergentAtUse(const UseT &U) const
Whether U is divergent at its use.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
Base class for instruction visitors.
Definition InstVisitor.h:78
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Primary interface to the complete machine description for the target machine.
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
Target-Independent Code Generator Pass Configuration Options.
TMC & getTM() const
Get the right type of TargetMachine for this target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
@ FloatTyID
32-bit floating point type
Definition Type.h:59
@ IntegerTyID
Arbitrary bit width integers.
Definition Type.h:71
@ DoubleTyID
64-bit floating point type
Definition Type.h:60
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
Analysis pass which computes UniformityInfo.
Legacy analysis pass which computes a CycleInfo.
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ LOCAL_ADDRESS
Address space for local memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
ScanOptions
Definition AMDGPU.h:159
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
FunctionPass * createAMDGPUAtomicOptimizerPass(ScanOptions ScanStrategy)
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DWARFExpression::Operation Op
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
char & AMDGPUAtomicOptimizerID
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)