1d8e91e46SDimitry Andric //===-- AMDGPUAtomicOptimizer.cpp -----------------------------------------===//
2d8e91e46SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d8e91e46SDimitry Andric //
7d8e91e46SDimitry Andric //===----------------------------------------------------------------------===//
8d8e91e46SDimitry Andric //
9d8e91e46SDimitry Andric /// \file
10d8e91e46SDimitry Andric /// This pass optimizes atomic operations by using a single lane of a wavefront
11d8e91e46SDimitry Andric /// to perform the atomic operation, thus reducing contention on that memory
12d8e91e46SDimitry Andric /// location.
137fa27ce4SDimitry Andric /// Atomic optimizer uses following strategies to compute scan and reduced
147fa27ce4SDimitry Andric /// values
157fa27ce4SDimitry Andric /// 1. DPP -
167fa27ce4SDimitry Andric /// This is the most efficient implementation for scan. DPP uses Whole Wave
177fa27ce4SDimitry Andric /// Mode (WWM)
187fa27ce4SDimitry Andric /// 2. Iterative -
197fa27ce4SDimitry Andric // An alternative implementation iterates over all active lanes
207fa27ce4SDimitry Andric /// of Wavefront using llvm.cttz and performs scan using readlane & writelane
217fa27ce4SDimitry Andric /// intrinsics
22d8e91e46SDimitry Andric //===----------------------------------------------------------------------===//
23d8e91e46SDimitry Andric
24d8e91e46SDimitry Andric #include "AMDGPU.h"
25b60736ecSDimitry Andric #include "GCNSubtarget.h"
267fa27ce4SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
277fa27ce4SDimitry Andric #include "llvm/Analysis/UniformityAnalysis.h"
28d8e91e46SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
29d8e91e46SDimitry Andric #include "llvm/IR/IRBuilder.h"
30d8e91e46SDimitry Andric #include "llvm/IR/InstVisitor.h"
31b60736ecSDimitry Andric #include "llvm/IR/IntrinsicsAMDGPU.h"
32706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
33b60736ecSDimitry Andric #include "llvm/Target/TargetMachine.h"
34d8e91e46SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
35d8e91e46SDimitry Andric
36d8e91e46SDimitry Andric #define DEBUG_TYPE "amdgpu-atomic-optimizer"
37d8e91e46SDimitry Andric
38d8e91e46SDimitry Andric using namespace llvm;
391d5ae102SDimitry Andric using namespace llvm::AMDGPU;
40d8e91e46SDimitry Andric
41d8e91e46SDimitry Andric namespace {
42d8e91e46SDimitry Andric
43d8e91e46SDimitry Andric struct ReplacementInfo {
44d8e91e46SDimitry Andric Instruction *I;
45e6d15924SDimitry Andric AtomicRMWInst::BinOp Op;
46d8e91e46SDimitry Andric unsigned ValIdx;
47d8e91e46SDimitry Andric bool ValDivergent;
48d8e91e46SDimitry Andric };
49d8e91e46SDimitry Andric
507fa27ce4SDimitry Andric class AMDGPUAtomicOptimizer : public FunctionPass {
517fa27ce4SDimitry Andric public:
527fa27ce4SDimitry Andric static char ID;
537fa27ce4SDimitry Andric ScanOptions ScanImpl;
AMDGPUAtomicOptimizer(ScanOptions ScanImpl)547fa27ce4SDimitry Andric AMDGPUAtomicOptimizer(ScanOptions ScanImpl)
557fa27ce4SDimitry Andric : FunctionPass(ID), ScanImpl(ScanImpl) {}
567fa27ce4SDimitry Andric
577fa27ce4SDimitry Andric bool runOnFunction(Function &F) override;
587fa27ce4SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const597fa27ce4SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
607fa27ce4SDimitry Andric AU.addPreserved<DominatorTreeWrapperPass>();
617fa27ce4SDimitry Andric AU.addRequired<UniformityInfoWrapperPass>();
627fa27ce4SDimitry Andric AU.addRequired<TargetPassConfig>();
637fa27ce4SDimitry Andric }
647fa27ce4SDimitry Andric };
657fa27ce4SDimitry Andric
667fa27ce4SDimitry Andric class AMDGPUAtomicOptimizerImpl
677fa27ce4SDimitry Andric : public InstVisitor<AMDGPUAtomicOptimizerImpl> {
68d8e91e46SDimitry Andric private:
69d8e91e46SDimitry Andric SmallVector<ReplacementInfo, 8> ToReplace;
707fa27ce4SDimitry Andric const UniformityInfo *UA;
71d8e91e46SDimitry Andric const DataLayout *DL;
727fa27ce4SDimitry Andric DomTreeUpdater &DTU;
731d5ae102SDimitry Andric const GCNSubtarget *ST;
74d8e91e46SDimitry Andric bool IsPixelShader;
757fa27ce4SDimitry Andric ScanOptions ScanImpl;
76d8e91e46SDimitry Andric
77344a3780SDimitry Andric Value *buildReduction(IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *V,
78344a3780SDimitry Andric Value *const Identity) const;
791d5ae102SDimitry Andric Value *buildScan(IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *V,
801d5ae102SDimitry Andric Value *const Identity) const;
811d5ae102SDimitry Andric Value *buildShiftRight(IRBuilder<> &B, Value *V, Value *const Identity) const;
827fa27ce4SDimitry Andric
837fa27ce4SDimitry Andric std::pair<Value *, Value *>
847fa27ce4SDimitry Andric buildScanIteratively(IRBuilder<> &B, AtomicRMWInst::BinOp Op,
857fa27ce4SDimitry Andric Value *const Identity, Value *V, Instruction &I,
867fa27ce4SDimitry Andric BasicBlock *ComputeLoop, BasicBlock *ComputeEnd) const;
877fa27ce4SDimitry Andric
88e6d15924SDimitry Andric void optimizeAtomic(Instruction &I, AtomicRMWInst::BinOp Op, unsigned ValIdx,
89e6d15924SDimitry Andric bool ValDivergent) const;
90d8e91e46SDimitry Andric
91d8e91e46SDimitry Andric public:
927fa27ce4SDimitry Andric AMDGPUAtomicOptimizerImpl() = delete;
93d8e91e46SDimitry Andric
AMDGPUAtomicOptimizerImpl(const UniformityInfo * UA,const DataLayout * DL,DomTreeUpdater & DTU,const GCNSubtarget * ST,bool IsPixelShader,ScanOptions ScanImpl)947fa27ce4SDimitry Andric AMDGPUAtomicOptimizerImpl(const UniformityInfo *UA, const DataLayout *DL,
957fa27ce4SDimitry Andric DomTreeUpdater &DTU, const GCNSubtarget *ST,
967fa27ce4SDimitry Andric bool IsPixelShader, ScanOptions ScanImpl)
977fa27ce4SDimitry Andric : UA(UA), DL(DL), DTU(DTU), ST(ST), IsPixelShader(IsPixelShader),
987fa27ce4SDimitry Andric ScanImpl(ScanImpl) {}
99d8e91e46SDimitry Andric
1007fa27ce4SDimitry Andric bool run(Function &F);
101d8e91e46SDimitry Andric
102d8e91e46SDimitry Andric void visitAtomicRMWInst(AtomicRMWInst &I);
103d8e91e46SDimitry Andric void visitIntrinsicInst(IntrinsicInst &I);
104d8e91e46SDimitry Andric };
105d8e91e46SDimitry Andric
106d8e91e46SDimitry Andric } // namespace
107d8e91e46SDimitry Andric
108d8e91e46SDimitry Andric char AMDGPUAtomicOptimizer::ID = 0;
109d8e91e46SDimitry Andric
110d8e91e46SDimitry Andric char &llvm::AMDGPUAtomicOptimizerID = AMDGPUAtomicOptimizer::ID;
111d8e91e46SDimitry Andric
runOnFunction(Function & F)112d8e91e46SDimitry Andric bool AMDGPUAtomicOptimizer::runOnFunction(Function &F) {
113d8e91e46SDimitry Andric if (skipFunction(F)) {
114d8e91e46SDimitry Andric return false;
115d8e91e46SDimitry Andric }
116d8e91e46SDimitry Andric
1177fa27ce4SDimitry Andric const UniformityInfo *UA =
1187fa27ce4SDimitry Andric &getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
119ac9a064cSDimitry Andric const DataLayout *DL = &F.getDataLayout();
1207fa27ce4SDimitry Andric
121d8e91e46SDimitry Andric DominatorTreeWrapperPass *const DTW =
122d8e91e46SDimitry Andric getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1237fa27ce4SDimitry Andric DomTreeUpdater DTU(DTW ? &DTW->getDomTree() : nullptr,
1247fa27ce4SDimitry Andric DomTreeUpdater::UpdateStrategy::Lazy);
1257fa27ce4SDimitry Andric
126d8e91e46SDimitry Andric const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
127d8e91e46SDimitry Andric const TargetMachine &TM = TPC.getTM<TargetMachine>();
1287fa27ce4SDimitry Andric const GCNSubtarget *ST = &TM.getSubtarget<GCNSubtarget>(F);
1297fa27ce4SDimitry Andric
1307fa27ce4SDimitry Andric bool IsPixelShader = F.getCallingConv() == CallingConv::AMDGPU_PS;
1317fa27ce4SDimitry Andric
1327fa27ce4SDimitry Andric return AMDGPUAtomicOptimizerImpl(UA, DL, DTU, ST, IsPixelShader, ScanImpl)
1337fa27ce4SDimitry Andric .run(F);
1347fa27ce4SDimitry Andric }
1357fa27ce4SDimitry Andric
run(Function & F,FunctionAnalysisManager & AM)1367fa27ce4SDimitry Andric PreservedAnalyses AMDGPUAtomicOptimizerPass::run(Function &F,
1377fa27ce4SDimitry Andric FunctionAnalysisManager &AM) {
1387fa27ce4SDimitry Andric
1397fa27ce4SDimitry Andric const auto *UA = &AM.getResult<UniformityInfoAnalysis>(F);
140ac9a064cSDimitry Andric const DataLayout *DL = &F.getDataLayout();
1417fa27ce4SDimitry Andric
1427fa27ce4SDimitry Andric DomTreeUpdater DTU(&AM.getResult<DominatorTreeAnalysis>(F),
1437fa27ce4SDimitry Andric DomTreeUpdater::UpdateStrategy::Lazy);
1447fa27ce4SDimitry Andric const GCNSubtarget *ST = &TM.getSubtarget<GCNSubtarget>(F);
1457fa27ce4SDimitry Andric
1467fa27ce4SDimitry Andric bool IsPixelShader = F.getCallingConv() == CallingConv::AMDGPU_PS;
1477fa27ce4SDimitry Andric
1487fa27ce4SDimitry Andric bool IsChanged =
1497fa27ce4SDimitry Andric AMDGPUAtomicOptimizerImpl(UA, DL, DTU, ST, IsPixelShader, ScanImpl)
1507fa27ce4SDimitry Andric .run(F);
1517fa27ce4SDimitry Andric
1527fa27ce4SDimitry Andric if (!IsChanged) {
1537fa27ce4SDimitry Andric return PreservedAnalyses::all();
1547fa27ce4SDimitry Andric }
1557fa27ce4SDimitry Andric
1567fa27ce4SDimitry Andric PreservedAnalyses PA;
1577fa27ce4SDimitry Andric PA.preserve<DominatorTreeAnalysis>();
1587fa27ce4SDimitry Andric return PA;
1597fa27ce4SDimitry Andric }
1607fa27ce4SDimitry Andric
run(Function & F)1617fa27ce4SDimitry Andric bool AMDGPUAtomicOptimizerImpl::run(Function &F) {
1627fa27ce4SDimitry Andric
1637fa27ce4SDimitry Andric // Scan option None disables the Pass
1647fa27ce4SDimitry Andric if (ScanImpl == ScanOptions::None) {
1657fa27ce4SDimitry Andric return false;
1667fa27ce4SDimitry Andric }
167d8e91e46SDimitry Andric
168d8e91e46SDimitry Andric visit(F);
169d8e91e46SDimitry Andric
170d8e91e46SDimitry Andric const bool Changed = !ToReplace.empty();
171d8e91e46SDimitry Andric
172d8e91e46SDimitry Andric for (ReplacementInfo &Info : ToReplace) {
173d8e91e46SDimitry Andric optimizeAtomic(*Info.I, Info.Op, Info.ValIdx, Info.ValDivergent);
174d8e91e46SDimitry Andric }
175d8e91e46SDimitry Andric
176d8e91e46SDimitry Andric ToReplace.clear();
177d8e91e46SDimitry Andric
178d8e91e46SDimitry Andric return Changed;
179d8e91e46SDimitry Andric }
180d8e91e46SDimitry Andric
isLegalCrossLaneType(Type * Ty)181ac9a064cSDimitry Andric static bool isLegalCrossLaneType(Type *Ty) {
182ac9a064cSDimitry Andric switch (Ty->getTypeID()) {
183ac9a064cSDimitry Andric case Type::FloatTyID:
184ac9a064cSDimitry Andric case Type::DoubleTyID:
185ac9a064cSDimitry Andric return true;
186ac9a064cSDimitry Andric case Type::IntegerTyID: {
187ac9a064cSDimitry Andric unsigned Size = Ty->getIntegerBitWidth();
188ac9a064cSDimitry Andric return (Size == 32 || Size == 64);
189ac9a064cSDimitry Andric }
190ac9a064cSDimitry Andric default:
191ac9a064cSDimitry Andric return false;
192ac9a064cSDimitry Andric }
193ac9a064cSDimitry Andric }
194ac9a064cSDimitry Andric
visitAtomicRMWInst(AtomicRMWInst & I)1957fa27ce4SDimitry Andric void AMDGPUAtomicOptimizerImpl::visitAtomicRMWInst(AtomicRMWInst &I) {
196d8e91e46SDimitry Andric // Early exit for unhandled address space atomic instructions.
197d8e91e46SDimitry Andric switch (I.getPointerAddressSpace()) {
198d8e91e46SDimitry Andric default:
199d8e91e46SDimitry Andric return;
200d8e91e46SDimitry Andric case AMDGPUAS::GLOBAL_ADDRESS:
201d8e91e46SDimitry Andric case AMDGPUAS::LOCAL_ADDRESS:
202d8e91e46SDimitry Andric break;
203d8e91e46SDimitry Andric }
204d8e91e46SDimitry Andric
205e6d15924SDimitry Andric AtomicRMWInst::BinOp Op = I.getOperation();
206d8e91e46SDimitry Andric
207e6d15924SDimitry Andric switch (Op) {
208d8e91e46SDimitry Andric default:
209d8e91e46SDimitry Andric return;
210d8e91e46SDimitry Andric case AtomicRMWInst::Add:
211d8e91e46SDimitry Andric case AtomicRMWInst::Sub:
212e6d15924SDimitry Andric case AtomicRMWInst::And:
213e6d15924SDimitry Andric case AtomicRMWInst::Or:
214e6d15924SDimitry Andric case AtomicRMWInst::Xor:
215e6d15924SDimitry Andric case AtomicRMWInst::Max:
216e6d15924SDimitry Andric case AtomicRMWInst::Min:
217e6d15924SDimitry Andric case AtomicRMWInst::UMax:
218e6d15924SDimitry Andric case AtomicRMWInst::UMin:
219b1c73532SDimitry Andric case AtomicRMWInst::FAdd:
220b1c73532SDimitry Andric case AtomicRMWInst::FSub:
221b1c73532SDimitry Andric case AtomicRMWInst::FMax:
222b1c73532SDimitry Andric case AtomicRMWInst::FMin:
223d8e91e46SDimitry Andric break;
224d8e91e46SDimitry Andric }
225d8e91e46SDimitry Andric
226ac9a064cSDimitry Andric // Only 32 and 64 bit floating point atomic ops are supported.
227ac9a064cSDimitry Andric if (AtomicRMWInst::isFPOperation(Op) &&
228ac9a064cSDimitry Andric !(I.getType()->isFloatTy() || I.getType()->isDoubleTy())) {
229b1c73532SDimitry Andric return;
230b1c73532SDimitry Andric }
231b1c73532SDimitry Andric
232d8e91e46SDimitry Andric const unsigned PtrIdx = 0;
233d8e91e46SDimitry Andric const unsigned ValIdx = 1;
234d8e91e46SDimitry Andric
235d8e91e46SDimitry Andric // If the pointer operand is divergent, then each lane is doing an atomic
236d8e91e46SDimitry Andric // operation on a different address, and we cannot optimize that.
2377fa27ce4SDimitry Andric if (UA->isDivergentUse(I.getOperandUse(PtrIdx))) {
238d8e91e46SDimitry Andric return;
239d8e91e46SDimitry Andric }
240d8e91e46SDimitry Andric
241ac9a064cSDimitry Andric bool ValDivergent = UA->isDivergentUse(I.getOperandUse(ValIdx));
242d8e91e46SDimitry Andric
243d8e91e46SDimitry Andric // If the value operand is divergent, each lane is contributing a different
244d8e91e46SDimitry Andric // value to the atomic calculation. We can only optimize divergent values if
245ac9a064cSDimitry Andric // we have DPP available on our subtarget (for DPP strategy), and the atomic
246ac9a064cSDimitry Andric // operation is 32 or 64 bits.
247ac9a064cSDimitry Andric if (ValDivergent) {
248ac9a064cSDimitry Andric if (ScanImpl == ScanOptions::DPP && !ST->hasDPP())
249ac9a064cSDimitry Andric return;
250ac9a064cSDimitry Andric
251ac9a064cSDimitry Andric if (!isLegalCrossLaneType(I.getType()))
252d8e91e46SDimitry Andric return;
253d8e91e46SDimitry Andric }
254d8e91e46SDimitry Andric
255d8e91e46SDimitry Andric // If we get here, we can optimize the atomic using a single wavefront-wide
256d8e91e46SDimitry Andric // atomic operation to do the calculation for the entire wavefront, so
257d8e91e46SDimitry Andric // remember the instruction so we can come back to it.
258d8e91e46SDimitry Andric const ReplacementInfo Info = {&I, Op, ValIdx, ValDivergent};
259d8e91e46SDimitry Andric
260d8e91e46SDimitry Andric ToReplace.push_back(Info);
261d8e91e46SDimitry Andric }
262d8e91e46SDimitry Andric
visitIntrinsicInst(IntrinsicInst & I)2637fa27ce4SDimitry Andric void AMDGPUAtomicOptimizerImpl::visitIntrinsicInst(IntrinsicInst &I) {
264e6d15924SDimitry Andric AtomicRMWInst::BinOp Op;
265d8e91e46SDimitry Andric
266d8e91e46SDimitry Andric switch (I.getIntrinsicID()) {
267d8e91e46SDimitry Andric default:
268d8e91e46SDimitry Andric return;
269d8e91e46SDimitry Andric case Intrinsic::amdgcn_struct_buffer_atomic_add:
2707fa27ce4SDimitry Andric case Intrinsic::amdgcn_struct_ptr_buffer_atomic_add:
271d8e91e46SDimitry Andric case Intrinsic::amdgcn_raw_buffer_atomic_add:
2727fa27ce4SDimitry Andric case Intrinsic::amdgcn_raw_ptr_buffer_atomic_add:
273e6d15924SDimitry Andric Op = AtomicRMWInst::Add;
274d8e91e46SDimitry Andric break;
275d8e91e46SDimitry Andric case Intrinsic::amdgcn_struct_buffer_atomic_sub:
2767fa27ce4SDimitry Andric case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub:
277d8e91e46SDimitry Andric case Intrinsic::amdgcn_raw_buffer_atomic_sub:
2787fa27ce4SDimitry Andric case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub:
279e6d15924SDimitry Andric Op = AtomicRMWInst::Sub;
280e6d15924SDimitry Andric break;
281e6d15924SDimitry Andric case Intrinsic::amdgcn_struct_buffer_atomic_and:
2827fa27ce4SDimitry Andric case Intrinsic::amdgcn_struct_ptr_buffer_atomic_and:
283e6d15924SDimitry Andric case Intrinsic::amdgcn_raw_buffer_atomic_and:
2847fa27ce4SDimitry Andric case Intrinsic::amdgcn_raw_ptr_buffer_atomic_and:
285e6d15924SDimitry Andric Op = AtomicRMWInst::And;
286e6d15924SDimitry Andric break;
287e6d15924SDimitry Andric case Intrinsic::amdgcn_struct_buffer_atomic_or:
2887fa27ce4SDimitry Andric case Intrinsic::amdgcn_struct_ptr_buffer_atomic_or:
289e6d15924SDimitry Andric case Intrinsic::amdgcn_raw_buffer_atomic_or:
2907fa27ce4SDimitry Andric case Intrinsic::amdgcn_raw_ptr_buffer_atomic_or:
291e6d15924SDimitry Andric Op = AtomicRMWInst::Or;
292e6d15924SDimitry Andric break;
293e6d15924SDimitry Andric case Intrinsic::amdgcn_struct_buffer_atomic_xor:
2947fa27ce4SDimitry Andric case Intrinsic::amdgcn_struct_ptr_buffer_atomic_xor:
295e6d15924SDimitry Andric case Intrinsic::amdgcn_raw_buffer_atomic_xor:
2967fa27ce4SDimitry Andric case Intrinsic::amdgcn_raw_ptr_buffer_atomic_xor:
297e6d15924SDimitry Andric Op = AtomicRMWInst::Xor;
298e6d15924SDimitry Andric break;
299e6d15924SDimitry Andric case Intrinsic::amdgcn_struct_buffer_atomic_smin:
3007fa27ce4SDimitry Andric case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smin:
301e6d15924SDimitry Andric case Intrinsic::amdgcn_raw_buffer_atomic_smin:
3027fa27ce4SDimitry Andric case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smin:
303e6d15924SDimitry Andric Op = AtomicRMWInst::Min;
304e6d15924SDimitry Andric break;
305e6d15924SDimitry Andric case Intrinsic::amdgcn_struct_buffer_atomic_umin:
3067fa27ce4SDimitry Andric case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umin:
307e6d15924SDimitry Andric case Intrinsic::amdgcn_raw_buffer_atomic_umin:
3087fa27ce4SDimitry Andric case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umin:
309e6d15924SDimitry Andric Op = AtomicRMWInst::UMin;
310e6d15924SDimitry Andric break;
311e6d15924SDimitry Andric case Intrinsic::amdgcn_struct_buffer_atomic_smax:
3127fa27ce4SDimitry Andric case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smax:
313e6d15924SDimitry Andric case Intrinsic::amdgcn_raw_buffer_atomic_smax:
3147fa27ce4SDimitry Andric case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smax:
315e6d15924SDimitry Andric Op = AtomicRMWInst::Max;
316e6d15924SDimitry Andric break;
317e6d15924SDimitry Andric case Intrinsic::amdgcn_struct_buffer_atomic_umax:
3187fa27ce4SDimitry Andric case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umax:
319e6d15924SDimitry Andric case Intrinsic::amdgcn_raw_buffer_atomic_umax:
3207fa27ce4SDimitry Andric case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umax:
321e6d15924SDimitry Andric Op = AtomicRMWInst::UMax;
322d8e91e46SDimitry Andric break;
323d8e91e46SDimitry Andric }
324d8e91e46SDimitry Andric
325d8e91e46SDimitry Andric const unsigned ValIdx = 0;
326d8e91e46SDimitry Andric
3277fa27ce4SDimitry Andric const bool ValDivergent = UA->isDivergentUse(I.getOperandUse(ValIdx));
328d8e91e46SDimitry Andric
329d8e91e46SDimitry Andric // If the value operand is divergent, each lane is contributing a different
330d8e91e46SDimitry Andric // value to the atomic calculation. We can only optimize divergent values if
331ac9a064cSDimitry Andric // we have DPP available on our subtarget (for DPP strategy), and the atomic
332ac9a064cSDimitry Andric // operation is 32 or 64 bits.
333ac9a064cSDimitry Andric if (ValDivergent) {
334ac9a064cSDimitry Andric if (ScanImpl == ScanOptions::DPP && !ST->hasDPP())
335ac9a064cSDimitry Andric return;
336ac9a064cSDimitry Andric
337ac9a064cSDimitry Andric if (!isLegalCrossLaneType(I.getType()))
338d8e91e46SDimitry Andric return;
339d8e91e46SDimitry Andric }
340d8e91e46SDimitry Andric
341d8e91e46SDimitry Andric // If any of the other arguments to the intrinsic are divergent, we can't
342d8e91e46SDimitry Andric // optimize the operation.
343d8e91e46SDimitry Andric for (unsigned Idx = 1; Idx < I.getNumOperands(); Idx++) {
3447fa27ce4SDimitry Andric if (UA->isDivergentUse(I.getOperandUse(Idx))) {
345d8e91e46SDimitry Andric return;
346d8e91e46SDimitry Andric }
347d8e91e46SDimitry Andric }
348d8e91e46SDimitry Andric
349d8e91e46SDimitry Andric // If we get here, we can optimize the atomic using a single wavefront-wide
350d8e91e46SDimitry Andric // atomic operation to do the calculation for the entire wavefront, so
351d8e91e46SDimitry Andric // remember the instruction so we can come back to it.
352d8e91e46SDimitry Andric const ReplacementInfo Info = {&I, Op, ValIdx, ValDivergent};
353d8e91e46SDimitry Andric
354d8e91e46SDimitry Andric ToReplace.push_back(Info);
355d8e91e46SDimitry Andric }
356d8e91e46SDimitry Andric
357e6d15924SDimitry Andric // Use the builder to create the non-atomic counterpart of the specified
358e6d15924SDimitry Andric // atomicrmw binary op.
buildNonAtomicBinOp(IRBuilder<> & B,AtomicRMWInst::BinOp Op,Value * LHS,Value * RHS)359e6d15924SDimitry Andric static Value *buildNonAtomicBinOp(IRBuilder<> &B, AtomicRMWInst::BinOp Op,
360e6d15924SDimitry Andric Value *LHS, Value *RHS) {
361e6d15924SDimitry Andric CmpInst::Predicate Pred;
362e6d15924SDimitry Andric
363e6d15924SDimitry Andric switch (Op) {
364e6d15924SDimitry Andric default:
365e6d15924SDimitry Andric llvm_unreachable("Unhandled atomic op");
366e6d15924SDimitry Andric case AtomicRMWInst::Add:
367e6d15924SDimitry Andric return B.CreateBinOp(Instruction::Add, LHS, RHS);
368b1c73532SDimitry Andric case AtomicRMWInst::FAdd:
369b1c73532SDimitry Andric return B.CreateFAdd(LHS, RHS);
370e6d15924SDimitry Andric case AtomicRMWInst::Sub:
371e6d15924SDimitry Andric return B.CreateBinOp(Instruction::Sub, LHS, RHS);
372b1c73532SDimitry Andric case AtomicRMWInst::FSub:
373b1c73532SDimitry Andric return B.CreateFSub(LHS, RHS);
374e6d15924SDimitry Andric case AtomicRMWInst::And:
375e6d15924SDimitry Andric return B.CreateBinOp(Instruction::And, LHS, RHS);
376e6d15924SDimitry Andric case AtomicRMWInst::Or:
377e6d15924SDimitry Andric return B.CreateBinOp(Instruction::Or, LHS, RHS);
378e6d15924SDimitry Andric case AtomicRMWInst::Xor:
379e6d15924SDimitry Andric return B.CreateBinOp(Instruction::Xor, LHS, RHS);
380e6d15924SDimitry Andric
381e6d15924SDimitry Andric case AtomicRMWInst::Max:
382e6d15924SDimitry Andric Pred = CmpInst::ICMP_SGT;
383e6d15924SDimitry Andric break;
384e6d15924SDimitry Andric case AtomicRMWInst::Min:
385e6d15924SDimitry Andric Pred = CmpInst::ICMP_SLT;
386e6d15924SDimitry Andric break;
387e6d15924SDimitry Andric case AtomicRMWInst::UMax:
388e6d15924SDimitry Andric Pred = CmpInst::ICMP_UGT;
389e6d15924SDimitry Andric break;
390e6d15924SDimitry Andric case AtomicRMWInst::UMin:
391e6d15924SDimitry Andric Pred = CmpInst::ICMP_ULT;
392e6d15924SDimitry Andric break;
393b1c73532SDimitry Andric case AtomicRMWInst::FMax:
394b1c73532SDimitry Andric return B.CreateMaxNum(LHS, RHS);
395b1c73532SDimitry Andric case AtomicRMWInst::FMin:
396b1c73532SDimitry Andric return B.CreateMinNum(LHS, RHS);
397e6d15924SDimitry Andric }
398e6d15924SDimitry Andric Value *Cond = B.CreateICmp(Pred, LHS, RHS);
399e6d15924SDimitry Andric return B.CreateSelect(Cond, LHS, RHS);
400e6d15924SDimitry Andric }
401e6d15924SDimitry Andric
402344a3780SDimitry Andric // Use the builder to create a reduction of V across the wavefront, with all
403344a3780SDimitry Andric // lanes active, returning the same result in all lanes.
buildReduction(IRBuilder<> & B,AtomicRMWInst::BinOp Op,Value * V,Value * const Identity) const4047fa27ce4SDimitry Andric Value *AMDGPUAtomicOptimizerImpl::buildReduction(IRBuilder<> &B,
4057fa27ce4SDimitry Andric AtomicRMWInst::BinOp Op,
4067fa27ce4SDimitry Andric Value *V,
407344a3780SDimitry Andric Value *const Identity) const {
408b1c73532SDimitry Andric Type *AtomicTy = V->getType();
409344a3780SDimitry Andric Module *M = B.GetInsertBlock()->getModule();
410344a3780SDimitry Andric Function *UpdateDPP =
411b1c73532SDimitry Andric Intrinsic::getDeclaration(M, Intrinsic::amdgcn_update_dpp, AtomicTy);
412344a3780SDimitry Andric
413344a3780SDimitry Andric // Reduce within each row of 16 lanes.
414344a3780SDimitry Andric for (unsigned Idx = 0; Idx < 4; Idx++) {
415344a3780SDimitry Andric V = buildNonAtomicBinOp(
416344a3780SDimitry Andric B, Op, V,
417344a3780SDimitry Andric B.CreateCall(UpdateDPP,
418344a3780SDimitry Andric {Identity, V, B.getInt32(DPP::ROW_XMASK0 | 1 << Idx),
419344a3780SDimitry Andric B.getInt32(0xf), B.getInt32(0xf), B.getFalse()}));
420344a3780SDimitry Andric }
421344a3780SDimitry Andric
422344a3780SDimitry Andric // Reduce within each pair of rows (i.e. 32 lanes).
423344a3780SDimitry Andric assert(ST->hasPermLaneX16());
424b1c73532SDimitry Andric Value *Permlanex16Call = B.CreateIntrinsic(
425ac9a064cSDimitry Andric V->getType(), Intrinsic::amdgcn_permlanex16,
426b1c73532SDimitry Andric {V, V, B.getInt32(-1), B.getInt32(-1), B.getFalse(), B.getFalse()});
427ac9a064cSDimitry Andric V = buildNonAtomicBinOp(B, Op, V, Permlanex16Call);
428b1c73532SDimitry Andric if (ST->isWave32()) {
429344a3780SDimitry Andric return V;
430b1c73532SDimitry Andric }
431344a3780SDimitry Andric
432145449b1SDimitry Andric if (ST->hasPermLane64()) {
433145449b1SDimitry Andric // Reduce across the upper and lower 32 lanes.
434b1c73532SDimitry Andric Value *Permlane64Call =
435ac9a064cSDimitry Andric B.CreateIntrinsic(V->getType(), Intrinsic::amdgcn_permlane64, V);
436ac9a064cSDimitry Andric return buildNonAtomicBinOp(B, Op, V, Permlane64Call);
437145449b1SDimitry Andric }
438145449b1SDimitry Andric
439344a3780SDimitry Andric // Pick an arbitrary lane from 0..31 and an arbitrary lane from 32..63 and
440344a3780SDimitry Andric // combine them with a scalar operation.
441344a3780SDimitry Andric Function *ReadLane =
442ac9a064cSDimitry Andric Intrinsic::getDeclaration(M, Intrinsic::amdgcn_readlane, AtomicTy);
443b1c73532SDimitry Andric Value *Lane0 = B.CreateCall(ReadLane, {V, B.getInt32(0)});
444b1c73532SDimitry Andric Value *Lane32 = B.CreateCall(ReadLane, {V, B.getInt32(32)});
445ac9a064cSDimitry Andric return buildNonAtomicBinOp(B, Op, Lane0, Lane32);
446344a3780SDimitry Andric }
447344a3780SDimitry Andric
4481d5ae102SDimitry Andric // Use the builder to create an inclusive scan of V across the wavefront, with
4491d5ae102SDimitry Andric // all lanes active.
buildScan(IRBuilder<> & B,AtomicRMWInst::BinOp Op,Value * V,Value * Identity) const4507fa27ce4SDimitry Andric Value *AMDGPUAtomicOptimizerImpl::buildScan(IRBuilder<> &B,
4517fa27ce4SDimitry Andric AtomicRMWInst::BinOp Op, Value *V,
452b1c73532SDimitry Andric Value *Identity) const {
453b1c73532SDimitry Andric Type *AtomicTy = V->getType();
4541d5ae102SDimitry Andric Module *M = B.GetInsertBlock()->getModule();
4551d5ae102SDimitry Andric Function *UpdateDPP =
456b1c73532SDimitry Andric Intrinsic::getDeclaration(M, Intrinsic::amdgcn_update_dpp, AtomicTy);
4571d5ae102SDimitry Andric
4581d5ae102SDimitry Andric for (unsigned Idx = 0; Idx < 4; Idx++) {
4591d5ae102SDimitry Andric V = buildNonAtomicBinOp(
4601d5ae102SDimitry Andric B, Op, V,
4611d5ae102SDimitry Andric B.CreateCall(UpdateDPP,
4621d5ae102SDimitry Andric {Identity, V, B.getInt32(DPP::ROW_SHR0 | 1 << Idx),
4631d5ae102SDimitry Andric B.getInt32(0xf), B.getInt32(0xf), B.getFalse()}));
4641d5ae102SDimitry Andric }
4651d5ae102SDimitry Andric if (ST->hasDPPBroadcasts()) {
4661d5ae102SDimitry Andric // GFX9 has DPP row broadcast operations.
4671d5ae102SDimitry Andric V = buildNonAtomicBinOp(
4681d5ae102SDimitry Andric B, Op, V,
4691d5ae102SDimitry Andric B.CreateCall(UpdateDPP,
4701d5ae102SDimitry Andric {Identity, V, B.getInt32(DPP::BCAST15), B.getInt32(0xa),
4711d5ae102SDimitry Andric B.getInt32(0xf), B.getFalse()}));
4721d5ae102SDimitry Andric V = buildNonAtomicBinOp(
4731d5ae102SDimitry Andric B, Op, V,
4741d5ae102SDimitry Andric B.CreateCall(UpdateDPP,
4751d5ae102SDimitry Andric {Identity, V, B.getInt32(DPP::BCAST31), B.getInt32(0xc),
4761d5ae102SDimitry Andric B.getInt32(0xf), B.getFalse()}));
4771d5ae102SDimitry Andric } else {
4781d5ae102SDimitry Andric // On GFX10 all DPP operations are confined to a single row. To get cross-
4791d5ae102SDimitry Andric // row operations we have to use permlane or readlane.
4801d5ae102SDimitry Andric
4811d5ae102SDimitry Andric // Combine lane 15 into lanes 16..31 (and, for wave 64, lane 47 into lanes
4821d5ae102SDimitry Andric // 48..63).
483344a3780SDimitry Andric assert(ST->hasPermLaneX16());
484b1c73532SDimitry Andric Value *PermX = B.CreateIntrinsic(
485ac9a064cSDimitry Andric V->getType(), Intrinsic::amdgcn_permlanex16,
486344a3780SDimitry Andric {V, V, B.getInt32(-1), B.getInt32(-1), B.getFalse(), B.getFalse()});
487b1c73532SDimitry Andric
488ac9a064cSDimitry Andric Value *UpdateDPPCall = B.CreateCall(
489ac9a064cSDimitry Andric UpdateDPP, {Identity, PermX, B.getInt32(DPP::QUAD_PERM_ID),
490ac9a064cSDimitry Andric B.getInt32(0xa), B.getInt32(0xf), B.getFalse()});
491ac9a064cSDimitry Andric V = buildNonAtomicBinOp(B, Op, V, UpdateDPPCall);
492b1c73532SDimitry Andric
4931d5ae102SDimitry Andric if (!ST->isWave32()) {
4941d5ae102SDimitry Andric // Combine lane 31 into lanes 32..63.
495ac9a064cSDimitry Andric Value *const Lane31 = B.CreateIntrinsic(
496ac9a064cSDimitry Andric V->getType(), Intrinsic::amdgcn_readlane, {V, B.getInt32(31)});
497b1c73532SDimitry Andric
498b1c73532SDimitry Andric Value *UpdateDPPCall = B.CreateCall(
499b1c73532SDimitry Andric UpdateDPP, {Identity, Lane31, B.getInt32(DPP::QUAD_PERM_ID),
500b1c73532SDimitry Andric B.getInt32(0xc), B.getInt32(0xf), B.getFalse()});
501b1c73532SDimitry Andric
502ac9a064cSDimitry Andric V = buildNonAtomicBinOp(B, Op, V, UpdateDPPCall);
5031d5ae102SDimitry Andric }
5041d5ae102SDimitry Andric }
5051d5ae102SDimitry Andric return V;
5061d5ae102SDimitry Andric }
5071d5ae102SDimitry Andric
5081d5ae102SDimitry Andric // Use the builder to create a shift right of V across the wavefront, with all
5091d5ae102SDimitry Andric // lanes active, to turn an inclusive scan into an exclusive scan.
buildShiftRight(IRBuilder<> & B,Value * V,Value * Identity) const5107fa27ce4SDimitry Andric Value *AMDGPUAtomicOptimizerImpl::buildShiftRight(IRBuilder<> &B, Value *V,
511b1c73532SDimitry Andric Value *Identity) const {
512b1c73532SDimitry Andric Type *AtomicTy = V->getType();
5131d5ae102SDimitry Andric Module *M = B.GetInsertBlock()->getModule();
5141d5ae102SDimitry Andric Function *UpdateDPP =
515b1c73532SDimitry Andric Intrinsic::getDeclaration(M, Intrinsic::amdgcn_update_dpp, AtomicTy);
5161d5ae102SDimitry Andric if (ST->hasDPPWavefrontShifts()) {
5171d5ae102SDimitry Andric // GFX9 has DPP wavefront shift operations.
5181d5ae102SDimitry Andric V = B.CreateCall(UpdateDPP,
5191d5ae102SDimitry Andric {Identity, V, B.getInt32(DPP::WAVE_SHR1), B.getInt32(0xf),
5201d5ae102SDimitry Andric B.getInt32(0xf), B.getFalse()});
5211d5ae102SDimitry Andric } else {
522344a3780SDimitry Andric Function *ReadLane =
523ac9a064cSDimitry Andric Intrinsic::getDeclaration(M, Intrinsic::amdgcn_readlane, AtomicTy);
524344a3780SDimitry Andric Function *WriteLane =
525ac9a064cSDimitry Andric Intrinsic::getDeclaration(M, Intrinsic::amdgcn_writelane, AtomicTy);
526344a3780SDimitry Andric
5271d5ae102SDimitry Andric // On GFX10 all DPP operations are confined to a single row. To get cross-
5281d5ae102SDimitry Andric // row operations we have to use permlane or readlane.
5291d5ae102SDimitry Andric Value *Old = V;
5301d5ae102SDimitry Andric V = B.CreateCall(UpdateDPP,
5311d5ae102SDimitry Andric {Identity, V, B.getInt32(DPP::ROW_SHR0 + 1),
5321d5ae102SDimitry Andric B.getInt32(0xf), B.getInt32(0xf), B.getFalse()});
5331d5ae102SDimitry Andric
5341d5ae102SDimitry Andric // Copy the old lane 15 to the new lane 16.
535ac9a064cSDimitry Andric V = B.CreateCall(WriteLane, {B.CreateCall(ReadLane, {Old, B.getInt32(15)}),
536ac9a064cSDimitry Andric B.getInt32(16), V});
537ac9a064cSDimitry Andric
538b1c73532SDimitry Andric if (!ST->isWave32()) {
539b1c73532SDimitry Andric // Copy the old lane 31 to the new lane 32.
540ac9a064cSDimitry Andric V = B.CreateCall(
541ac9a064cSDimitry Andric WriteLane,
542ac9a064cSDimitry Andric {B.CreateCall(ReadLane, {Old, B.getInt32(31)}), B.getInt32(32), V});
5431d5ae102SDimitry Andric
5441d5ae102SDimitry Andric // Copy the old lane 47 to the new lane 48.
5451d5ae102SDimitry Andric V = B.CreateCall(
5461d5ae102SDimitry Andric WriteLane,
5471d5ae102SDimitry Andric {B.CreateCall(ReadLane, {Old, B.getInt32(47)}), B.getInt32(48), V});
5481d5ae102SDimitry Andric }
5491d5ae102SDimitry Andric }
5501d5ae102SDimitry Andric
5511d5ae102SDimitry Andric return V;
5521d5ae102SDimitry Andric }
5531d5ae102SDimitry Andric
5547fa27ce4SDimitry Andric // Use the builder to create an exclusive scan and compute the final reduced
5557fa27ce4SDimitry Andric // value using an iterative approach. This provides an alternative
5567fa27ce4SDimitry Andric // implementation to DPP which uses WMM for scan computations. This API iterate
5577fa27ce4SDimitry Andric // over active lanes to read, compute and update the value using
5587fa27ce4SDimitry Andric // readlane and writelane intrinsics.
buildScanIteratively(IRBuilder<> & B,AtomicRMWInst::BinOp Op,Value * const Identity,Value * V,Instruction & I,BasicBlock * ComputeLoop,BasicBlock * ComputeEnd) const5597fa27ce4SDimitry Andric std::pair<Value *, Value *> AMDGPUAtomicOptimizerImpl::buildScanIteratively(
5607fa27ce4SDimitry Andric IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *const Identity, Value *V,
5617fa27ce4SDimitry Andric Instruction &I, BasicBlock *ComputeLoop, BasicBlock *ComputeEnd) const {
5627fa27ce4SDimitry Andric auto *Ty = I.getType();
5637fa27ce4SDimitry Andric auto *WaveTy = B.getIntNTy(ST->getWavefrontSize());
5647fa27ce4SDimitry Andric auto *EntryBB = I.getParent();
5657fa27ce4SDimitry Andric auto NeedResult = !I.use_empty();
5667fa27ce4SDimitry Andric
5677fa27ce4SDimitry Andric auto *Ballot =
5687fa27ce4SDimitry Andric B.CreateIntrinsic(Intrinsic::amdgcn_ballot, WaveTy, B.getTrue());
5697fa27ce4SDimitry Andric
5707fa27ce4SDimitry Andric // Start inserting instructions for ComputeLoop block
5717fa27ce4SDimitry Andric B.SetInsertPoint(ComputeLoop);
5727fa27ce4SDimitry Andric // Phi nodes for Accumulator, Scan results destination, and Active Lanes
5737fa27ce4SDimitry Andric auto *Accumulator = B.CreatePHI(Ty, 2, "Accumulator");
5747fa27ce4SDimitry Andric Accumulator->addIncoming(Identity, EntryBB);
5757fa27ce4SDimitry Andric PHINode *OldValuePhi = nullptr;
5767fa27ce4SDimitry Andric if (NeedResult) {
5777fa27ce4SDimitry Andric OldValuePhi = B.CreatePHI(Ty, 2, "OldValuePhi");
5787fa27ce4SDimitry Andric OldValuePhi->addIncoming(PoisonValue::get(Ty), EntryBB);
5797fa27ce4SDimitry Andric }
5807fa27ce4SDimitry Andric auto *ActiveBits = B.CreatePHI(WaveTy, 2, "ActiveBits");
5817fa27ce4SDimitry Andric ActiveBits->addIncoming(Ballot, EntryBB);
5827fa27ce4SDimitry Andric
5837fa27ce4SDimitry Andric // Use llvm.cttz instrinsic to find the lowest remaining active lane.
5847fa27ce4SDimitry Andric auto *FF1 =
5857fa27ce4SDimitry Andric B.CreateIntrinsic(Intrinsic::cttz, WaveTy, {ActiveBits, B.getTrue()});
586b1c73532SDimitry Andric
587ac9a064cSDimitry Andric auto *LaneIdxInt = B.CreateTrunc(FF1, B.getInt32Ty());
5887fa27ce4SDimitry Andric
5897fa27ce4SDimitry Andric // Get the value required for atomic operation
590ac9a064cSDimitry Andric Value *LaneValue = B.CreateIntrinsic(V->getType(), Intrinsic::amdgcn_readlane,
591ac9a064cSDimitry Andric {V, LaneIdxInt});
5927fa27ce4SDimitry Andric
5937fa27ce4SDimitry Andric // Perform writelane if intermediate scan results are required later in the
5947fa27ce4SDimitry Andric // kernel computations
5957fa27ce4SDimitry Andric Value *OldValue = nullptr;
5967fa27ce4SDimitry Andric if (NeedResult) {
597ac9a064cSDimitry Andric OldValue = B.CreateIntrinsic(V->getType(), Intrinsic::amdgcn_writelane,
598ac9a064cSDimitry Andric {Accumulator, LaneIdxInt, OldValuePhi});
5997fa27ce4SDimitry Andric OldValuePhi->addIncoming(OldValue, ComputeLoop);
6007fa27ce4SDimitry Andric }
6017fa27ce4SDimitry Andric
6027fa27ce4SDimitry Andric // Accumulate the results
6037fa27ce4SDimitry Andric auto *NewAccumulator = buildNonAtomicBinOp(B, Op, Accumulator, LaneValue);
6047fa27ce4SDimitry Andric Accumulator->addIncoming(NewAccumulator, ComputeLoop);
6057fa27ce4SDimitry Andric
6067fa27ce4SDimitry Andric // Set bit to zero of current active lane so that for next iteration llvm.cttz
6077fa27ce4SDimitry Andric // return the next active lane
6087fa27ce4SDimitry Andric auto *Mask = B.CreateShl(ConstantInt::get(WaveTy, 1), FF1);
6097fa27ce4SDimitry Andric
6107fa27ce4SDimitry Andric auto *InverseMask = B.CreateXor(Mask, ConstantInt::get(WaveTy, -1));
6117fa27ce4SDimitry Andric auto *NewActiveBits = B.CreateAnd(ActiveBits, InverseMask);
6127fa27ce4SDimitry Andric ActiveBits->addIncoming(NewActiveBits, ComputeLoop);
6137fa27ce4SDimitry Andric
6147fa27ce4SDimitry Andric // Branch out of the loop when all lanes are processed.
6157fa27ce4SDimitry Andric auto *IsEnd = B.CreateICmpEQ(NewActiveBits, ConstantInt::get(WaveTy, 0));
6167fa27ce4SDimitry Andric B.CreateCondBr(IsEnd, ComputeEnd, ComputeLoop);
6177fa27ce4SDimitry Andric
6187fa27ce4SDimitry Andric B.SetInsertPoint(ComputeEnd);
6197fa27ce4SDimitry Andric
6207fa27ce4SDimitry Andric return {OldValue, NewAccumulator};
6217fa27ce4SDimitry Andric }
6227fa27ce4SDimitry Andric
getIdentityValueForAtomicOp(Type * const Ty,AtomicRMWInst::BinOp Op)623b1c73532SDimitry Andric static Constant *getIdentityValueForAtomicOp(Type *const Ty,
624b1c73532SDimitry Andric AtomicRMWInst::BinOp Op) {
625b1c73532SDimitry Andric LLVMContext &C = Ty->getContext();
626b1c73532SDimitry Andric const unsigned BitWidth = Ty->getPrimitiveSizeInBits();
627e6d15924SDimitry Andric switch (Op) {
628e6d15924SDimitry Andric default:
629e6d15924SDimitry Andric llvm_unreachable("Unhandled atomic op");
630e6d15924SDimitry Andric case AtomicRMWInst::Add:
631e6d15924SDimitry Andric case AtomicRMWInst::Sub:
632e6d15924SDimitry Andric case AtomicRMWInst::Or:
633e6d15924SDimitry Andric case AtomicRMWInst::Xor:
634e6d15924SDimitry Andric case AtomicRMWInst::UMax:
635b1c73532SDimitry Andric return ConstantInt::get(C, APInt::getMinValue(BitWidth));
636e6d15924SDimitry Andric case AtomicRMWInst::And:
637e6d15924SDimitry Andric case AtomicRMWInst::UMin:
638b1c73532SDimitry Andric return ConstantInt::get(C, APInt::getMaxValue(BitWidth));
639e6d15924SDimitry Andric case AtomicRMWInst::Max:
640b1c73532SDimitry Andric return ConstantInt::get(C, APInt::getSignedMinValue(BitWidth));
641e6d15924SDimitry Andric case AtomicRMWInst::Min:
642b1c73532SDimitry Andric return ConstantInt::get(C, APInt::getSignedMaxValue(BitWidth));
643b1c73532SDimitry Andric case AtomicRMWInst::FAdd:
644b1c73532SDimitry Andric return ConstantFP::get(C, APFloat::getZero(Ty->getFltSemantics(), true));
645b1c73532SDimitry Andric case AtomicRMWInst::FSub:
646b1c73532SDimitry Andric return ConstantFP::get(C, APFloat::getZero(Ty->getFltSemantics(), false));
647b1c73532SDimitry Andric case AtomicRMWInst::FMin:
648b1c73532SDimitry Andric case AtomicRMWInst::FMax:
649ac9a064cSDimitry Andric // FIXME: atomicrmw fmax/fmin behave like llvm.maxnum/minnum so NaN is the
650ac9a064cSDimitry Andric // closest thing they have to an identity, but it still does not preserve
651ac9a064cSDimitry Andric // the difference between quiet and signaling NaNs or NaNs with different
652ac9a064cSDimitry Andric // payloads.
653ac9a064cSDimitry Andric return ConstantFP::get(C, APFloat::getNaN(Ty->getFltSemantics()));
654e6d15924SDimitry Andric }
655e6d15924SDimitry Andric }
656e6d15924SDimitry Andric
buildMul(IRBuilder<> & B,Value * LHS,Value * RHS)657b60736ecSDimitry Andric static Value *buildMul(IRBuilder<> &B, Value *LHS, Value *RHS) {
658b60736ecSDimitry Andric const ConstantInt *CI = dyn_cast<ConstantInt>(LHS);
659b60736ecSDimitry Andric return (CI && CI->isOne()) ? RHS : B.CreateMul(LHS, RHS);
660b60736ecSDimitry Andric }
661b60736ecSDimitry Andric
optimizeAtomic(Instruction & I,AtomicRMWInst::BinOp Op,unsigned ValIdx,bool ValDivergent) const6627fa27ce4SDimitry Andric void AMDGPUAtomicOptimizerImpl::optimizeAtomic(Instruction &I,
663e6d15924SDimitry Andric AtomicRMWInst::BinOp Op,
664d8e91e46SDimitry Andric unsigned ValIdx,
665d8e91e46SDimitry Andric bool ValDivergent) const {
666d8e91e46SDimitry Andric // Start building just before the instruction.
667d8e91e46SDimitry Andric IRBuilder<> B(&I);
668d8e91e46SDimitry Andric
669b1c73532SDimitry Andric if (AtomicRMWInst::isFPOperation(Op)) {
670b1c73532SDimitry Andric B.setIsFPConstrained(I.getFunction()->hasFnAttribute(Attribute::StrictFP));
671b1c73532SDimitry Andric }
672b1c73532SDimitry Andric
673d8e91e46SDimitry Andric // If we are in a pixel shader, because of how we have to mask out helper
674d8e91e46SDimitry Andric // lane invocations, we need to record the entry and exit BB's.
675d8e91e46SDimitry Andric BasicBlock *PixelEntryBB = nullptr;
676d8e91e46SDimitry Andric BasicBlock *PixelExitBB = nullptr;
677d8e91e46SDimitry Andric
678d8e91e46SDimitry Andric // If we're optimizing an atomic within a pixel shader, we need to wrap the
679d8e91e46SDimitry Andric // entire atomic operation in a helper-lane check. We do not want any helper
680d8e91e46SDimitry Andric // lanes that are around only for the purposes of derivatives to take part
681d8e91e46SDimitry Andric // in any cross-lane communication, and we use a branch on whether the lane is
682d8e91e46SDimitry Andric // live to do this.
683d8e91e46SDimitry Andric if (IsPixelShader) {
684d8e91e46SDimitry Andric // Record I's original position as the entry block.
685d8e91e46SDimitry Andric PixelEntryBB = I.getParent();
686d8e91e46SDimitry Andric
687d8e91e46SDimitry Andric Value *const Cond = B.CreateIntrinsic(Intrinsic::amdgcn_ps_live, {}, {});
688d8e91e46SDimitry Andric Instruction *const NonHelperTerminator =
6897fa27ce4SDimitry Andric SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, &DTU, nullptr);
690d8e91e46SDimitry Andric
691d8e91e46SDimitry Andric // Record I's new position as the exit block.
692d8e91e46SDimitry Andric PixelExitBB = I.getParent();
693d8e91e46SDimitry Andric
694d8e91e46SDimitry Andric I.moveBefore(NonHelperTerminator);
695d8e91e46SDimitry Andric B.SetInsertPoint(&I);
696d8e91e46SDimitry Andric }
697d8e91e46SDimitry Andric
698d8e91e46SDimitry Andric Type *const Ty = I.getType();
699b1c73532SDimitry Andric Type *Int32Ty = B.getInt32Ty();
700b1c73532SDimitry Andric bool isAtomicFloatingPointTy = Ty->isFloatingPointTy();
701ac9a064cSDimitry Andric [[maybe_unused]] const unsigned TyBitWidth = DL->getTypeSizeInBits(Ty);
702d8e91e46SDimitry Andric
703d8e91e46SDimitry Andric // This is the value in the atomic operation we need to combine in order to
704d8e91e46SDimitry Andric // reduce the number of atomic operations.
705b1c73532SDimitry Andric Value *V = I.getOperand(ValIdx);
706d8e91e46SDimitry Andric
707d8e91e46SDimitry Andric // We need to know how many lanes are active within the wavefront, and we do
708e6d15924SDimitry Andric // this by doing a ballot of active lanes.
7091d5ae102SDimitry Andric Type *const WaveTy = B.getIntNTy(ST->getWavefrontSize());
710cfca06d7SDimitry Andric CallInst *const Ballot =
711cfca06d7SDimitry Andric B.CreateIntrinsic(Intrinsic::amdgcn_ballot, WaveTy, B.getTrue());
712d8e91e46SDimitry Andric
713d8e91e46SDimitry Andric // We need to know how many lanes are active within the wavefront that are
714d8e91e46SDimitry Andric // below us. If we counted each lane linearly starting from 0, a lane is
715d8e91e46SDimitry Andric // below us only if its associated index was less than ours. We do this by
716d8e91e46SDimitry Andric // using the mbcnt intrinsic.
7171d5ae102SDimitry Andric Value *Mbcnt;
7181d5ae102SDimitry Andric if (ST->isWave32()) {
7191d5ae102SDimitry Andric Mbcnt = B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_lo, {},
7201d5ae102SDimitry Andric {Ballot, B.getInt32(0)});
7211d5ae102SDimitry Andric } else {
722b1c73532SDimitry Andric Value *const ExtractLo = B.CreateTrunc(Ballot, Int32Ty);
723b1c73532SDimitry Andric Value *const ExtractHi = B.CreateTrunc(B.CreateLShr(Ballot, 32), Int32Ty);
7241d5ae102SDimitry Andric Mbcnt = B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_lo, {},
7251d5ae102SDimitry Andric {ExtractLo, B.getInt32(0)});
7261d5ae102SDimitry Andric Mbcnt =
7271d5ae102SDimitry Andric B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_hi, {}, {ExtractHi, Mbcnt});
7281d5ae102SDimitry Andric }
729d8e91e46SDimitry Andric
730b1c73532SDimitry Andric Function *F = I.getFunction();
731b1c73532SDimitry Andric LLVMContext &C = F->getContext();
732b1c73532SDimitry Andric
733b1c73532SDimitry Andric // For atomic sub, perform scan with add operation and allow one lane to
734b1c73532SDimitry Andric // subtract the reduced value later.
735b1c73532SDimitry Andric AtomicRMWInst::BinOp ScanOp = Op;
736b1c73532SDimitry Andric if (Op == AtomicRMWInst::Sub) {
737b1c73532SDimitry Andric ScanOp = AtomicRMWInst::Add;
738b1c73532SDimitry Andric } else if (Op == AtomicRMWInst::FSub) {
739b1c73532SDimitry Andric ScanOp = AtomicRMWInst::FAdd;
740b1c73532SDimitry Andric }
741b1c73532SDimitry Andric Value *Identity = getIdentityValueForAtomicOp(Ty, ScanOp);
742d8e91e46SDimitry Andric
743e6d15924SDimitry Andric Value *ExclScan = nullptr;
744d8e91e46SDimitry Andric Value *NewV = nullptr;
745d8e91e46SDimitry Andric
746344a3780SDimitry Andric const bool NeedResult = !I.use_empty();
747344a3780SDimitry Andric
7487fa27ce4SDimitry Andric BasicBlock *ComputeLoop = nullptr;
7497fa27ce4SDimitry Andric BasicBlock *ComputeEnd = nullptr;
750d8e91e46SDimitry Andric // If we have a divergent value in each lane, we need to combine the value
751d8e91e46SDimitry Andric // using DPP.
752d8e91e46SDimitry Andric if (ValDivergent) {
7537fa27ce4SDimitry Andric if (ScanImpl == ScanOptions::DPP) {
754e6d15924SDimitry Andric // First we need to set all inactive invocations to the identity value, so
755e6d15924SDimitry Andric // that they can correctly contribute to the final result.
756ac9a064cSDimitry Andric NewV =
757ac9a064cSDimitry Andric B.CreateIntrinsic(Intrinsic::amdgcn_set_inactive, Ty, {V, Identity});
758344a3780SDimitry Andric if (!NeedResult && ST->hasPermLaneX16()) {
7597fa27ce4SDimitry Andric // On GFX10 the permlanex16 instruction helps us build a reduction
7607fa27ce4SDimitry Andric // without too many readlanes and writelanes, which are generally bad
7617fa27ce4SDimitry Andric // for performance.
762344a3780SDimitry Andric NewV = buildReduction(B, ScanOp, NewV, Identity);
763344a3780SDimitry Andric } else {
7641d5ae102SDimitry Andric NewV = buildScan(B, ScanOp, NewV, Identity);
765344a3780SDimitry Andric if (NeedResult)
7661d5ae102SDimitry Andric ExclScan = buildShiftRight(B, NewV, Identity);
7677fa27ce4SDimitry Andric // Read the value from the last lane, which has accumulated the values
7687fa27ce4SDimitry Andric // of each active lane in the wavefront. This will be our new value
7697fa27ce4SDimitry Andric // which we will provide to the atomic operation.
7701d5ae102SDimitry Andric Value *const LastLaneIdx = B.getInt32(ST->getWavefrontSize() - 1);
771ac9a064cSDimitry Andric NewV = B.CreateIntrinsic(Ty, Intrinsic::amdgcn_readlane,
7721d5ae102SDimitry Andric {NewV, LastLaneIdx});
773d8e91e46SDimitry Andric }
774e6d15924SDimitry Andric // Finally mark the readlanes in the WWM section.
775344a3780SDimitry Andric NewV = B.CreateIntrinsic(Intrinsic::amdgcn_strict_wwm, Ty, NewV);
7767fa27ce4SDimitry Andric } else if (ScanImpl == ScanOptions::Iterative) {
7777fa27ce4SDimitry Andric // Alternative implementation for scan
7787fa27ce4SDimitry Andric ComputeLoop = BasicBlock::Create(C, "ComputeLoop", F);
7797fa27ce4SDimitry Andric ComputeEnd = BasicBlock::Create(C, "ComputeEnd", F);
7807fa27ce4SDimitry Andric std::tie(ExclScan, NewV) = buildScanIteratively(B, ScanOp, Identity, V, I,
7817fa27ce4SDimitry Andric ComputeLoop, ComputeEnd);
7827fa27ce4SDimitry Andric } else {
7837fa27ce4SDimitry Andric llvm_unreachable("Atomic Optimzer is disabled for None strategy");
7847fa27ce4SDimitry Andric }
785e6d15924SDimitry Andric } else {
786e6d15924SDimitry Andric switch (Op) {
787e6d15924SDimitry Andric default:
788e6d15924SDimitry Andric llvm_unreachable("Unhandled atomic op");
789e6d15924SDimitry Andric
790e6d15924SDimitry Andric case AtomicRMWInst::Add:
791e6d15924SDimitry Andric case AtomicRMWInst::Sub: {
792e6d15924SDimitry Andric // The new value we will be contributing to the atomic operation is the
793e6d15924SDimitry Andric // old value times the number of active lanes.
794e6d15924SDimitry Andric Value *const Ctpop = B.CreateIntCast(
795e6d15924SDimitry Andric B.CreateUnaryIntrinsic(Intrinsic::ctpop, Ballot), Ty, false);
796b60736ecSDimitry Andric NewV = buildMul(B, V, Ctpop);
797e6d15924SDimitry Andric break;
798e6d15924SDimitry Andric }
799b1c73532SDimitry Andric case AtomicRMWInst::FAdd:
800b1c73532SDimitry Andric case AtomicRMWInst::FSub: {
801b1c73532SDimitry Andric Value *const Ctpop = B.CreateIntCast(
802b1c73532SDimitry Andric B.CreateUnaryIntrinsic(Intrinsic::ctpop, Ballot), Int32Ty, false);
803b1c73532SDimitry Andric Value *const CtpopFP = B.CreateUIToFP(Ctpop, Ty);
804b1c73532SDimitry Andric NewV = B.CreateFMul(V, CtpopFP);
805b1c73532SDimitry Andric break;
806b1c73532SDimitry Andric }
807e6d15924SDimitry Andric case AtomicRMWInst::And:
808e6d15924SDimitry Andric case AtomicRMWInst::Or:
809e6d15924SDimitry Andric case AtomicRMWInst::Max:
810e6d15924SDimitry Andric case AtomicRMWInst::Min:
811e6d15924SDimitry Andric case AtomicRMWInst::UMax:
812e6d15924SDimitry Andric case AtomicRMWInst::UMin:
813b1c73532SDimitry Andric case AtomicRMWInst::FMin:
814b1c73532SDimitry Andric case AtomicRMWInst::FMax:
815e6d15924SDimitry Andric // These operations with a uniform value are idempotent: doing the atomic
816e6d15924SDimitry Andric // operation multiple times has the same effect as doing it once.
817e6d15924SDimitry Andric NewV = V;
818e6d15924SDimitry Andric break;
819e6d15924SDimitry Andric
820e6d15924SDimitry Andric case AtomicRMWInst::Xor:
821e6d15924SDimitry Andric // The new value we will be contributing to the atomic operation is the
822e6d15924SDimitry Andric // old value times the parity of the number of active lanes.
823e6d15924SDimitry Andric Value *const Ctpop = B.CreateIntCast(
824e6d15924SDimitry Andric B.CreateUnaryIntrinsic(Intrinsic::ctpop, Ballot), Ty, false);
825b60736ecSDimitry Andric NewV = buildMul(B, V, B.CreateAnd(Ctpop, 1));
826e6d15924SDimitry Andric break;
827e6d15924SDimitry Andric }
828d8e91e46SDimitry Andric }
829d8e91e46SDimitry Andric
830d8e91e46SDimitry Andric // We only want a single lane to enter our new control flow, and we do this
831d8e91e46SDimitry Andric // by checking if there are any active lanes below us. Only one lane will
832d8e91e46SDimitry Andric // have 0 active lanes below us, so that will be the only one to progress.
833b1c73532SDimitry Andric Value *const Cond = B.CreateICmpEQ(Mbcnt, B.getInt32(0));
834d8e91e46SDimitry Andric
835d8e91e46SDimitry Andric // Store I's original basic block before we split the block.
836ac9a064cSDimitry Andric BasicBlock *const OriginalBB = I.getParent();
837d8e91e46SDimitry Andric
838d8e91e46SDimitry Andric // We need to introduce some new control flow to force a single lane to be
839d8e91e46SDimitry Andric // active. We do this by splitting I's basic block at I, and introducing the
840d8e91e46SDimitry Andric // new block such that:
841d8e91e46SDimitry Andric // entry --> single_lane -\
842d8e91e46SDimitry Andric // \------------------> exit
843d8e91e46SDimitry Andric Instruction *const SingleLaneTerminator =
8447fa27ce4SDimitry Andric SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, &DTU, nullptr);
845d8e91e46SDimitry Andric
8467fa27ce4SDimitry Andric // At this point, we have split the I's block to allow one lane in wavefront
8477fa27ce4SDimitry Andric // to update the precomputed reduced value. Also, completed the codegen for
8487fa27ce4SDimitry Andric // new control flow i.e. iterative loop which perform reduction and scan using
8497fa27ce4SDimitry Andric // ComputeLoop and ComputeEnd.
8507fa27ce4SDimitry Andric // For the new control flow, we need to move branch instruction i.e.
8517fa27ce4SDimitry Andric // terminator created during SplitBlockAndInsertIfThen from I's block to
8527fa27ce4SDimitry Andric // ComputeEnd block. We also need to set up predecessor to next block when
8537fa27ce4SDimitry Andric // single lane done updating the final reduced value.
8547fa27ce4SDimitry Andric BasicBlock *Predecessor = nullptr;
8557fa27ce4SDimitry Andric if (ValDivergent && ScanImpl == ScanOptions::Iterative) {
8567fa27ce4SDimitry Andric // Move terminator from I's block to ComputeEnd block.
857ac9a064cSDimitry Andric //
858ac9a064cSDimitry Andric // OriginalBB is known to have a branch as terminator because
859ac9a064cSDimitry Andric // SplitBlockAndInsertIfThen will have inserted one.
860ac9a064cSDimitry Andric BranchInst *Terminator = cast<BranchInst>(OriginalBB->getTerminator());
8617fa27ce4SDimitry Andric B.SetInsertPoint(ComputeEnd);
8627fa27ce4SDimitry Andric Terminator->removeFromParent();
8637fa27ce4SDimitry Andric B.Insert(Terminator);
8647fa27ce4SDimitry Andric
8657fa27ce4SDimitry Andric // Branch to ComputeLoop Block unconditionally from the I's block for
8667fa27ce4SDimitry Andric // iterative approach.
867ac9a064cSDimitry Andric B.SetInsertPoint(OriginalBB);
8687fa27ce4SDimitry Andric B.CreateBr(ComputeLoop);
8697fa27ce4SDimitry Andric
8707fa27ce4SDimitry Andric // Update the dominator tree for new control flow.
871ac9a064cSDimitry Andric SmallVector<DominatorTree::UpdateType, 6> DomTreeUpdates(
872ac9a064cSDimitry Andric {{DominatorTree::Insert, OriginalBB, ComputeLoop},
873ac9a064cSDimitry Andric {DominatorTree::Insert, ComputeLoop, ComputeEnd}});
874ac9a064cSDimitry Andric
875ac9a064cSDimitry Andric // We're moving the terminator from EntryBB to ComputeEnd, make sure we move
876ac9a064cSDimitry Andric // the DT edges as well.
877ac9a064cSDimitry Andric for (auto *Succ : Terminator->successors()) {
878ac9a064cSDimitry Andric DomTreeUpdates.push_back({DominatorTree::Insert, ComputeEnd, Succ});
879ac9a064cSDimitry Andric DomTreeUpdates.push_back({DominatorTree::Delete, OriginalBB, Succ});
880ac9a064cSDimitry Andric }
881ac9a064cSDimitry Andric
882ac9a064cSDimitry Andric DTU.applyUpdates(DomTreeUpdates);
8837fa27ce4SDimitry Andric
8847fa27ce4SDimitry Andric Predecessor = ComputeEnd;
8857fa27ce4SDimitry Andric } else {
886ac9a064cSDimitry Andric Predecessor = OriginalBB;
8877fa27ce4SDimitry Andric }
888d8e91e46SDimitry Andric // Move the IR builder into single_lane next.
889d8e91e46SDimitry Andric B.SetInsertPoint(SingleLaneTerminator);
890d8e91e46SDimitry Andric
891d8e91e46SDimitry Andric // Clone the original atomic operation into single lane, replacing the
892d8e91e46SDimitry Andric // original value with our newly created one.
893d8e91e46SDimitry Andric Instruction *const NewI = I.clone();
894d8e91e46SDimitry Andric B.Insert(NewI);
895d8e91e46SDimitry Andric NewI->setOperand(ValIdx, NewV);
896d8e91e46SDimitry Andric
897d8e91e46SDimitry Andric // Move the IR builder into exit next, and start inserting just before the
898d8e91e46SDimitry Andric // original instruction.
899d8e91e46SDimitry Andric B.SetInsertPoint(&I);
900d8e91e46SDimitry Andric
9011d5ae102SDimitry Andric if (NeedResult) {
902d8e91e46SDimitry Andric // Create a PHI node to get our new atomic result into the exit block.
903d8e91e46SDimitry Andric PHINode *const PHI = B.CreatePHI(Ty, 2);
9047fa27ce4SDimitry Andric PHI->addIncoming(PoisonValue::get(Ty), Predecessor);
905d8e91e46SDimitry Andric PHI->addIncoming(NewI, SingleLaneTerminator->getParent());
906d8e91e46SDimitry Andric
907d8e91e46SDimitry Andric // We need to broadcast the value who was the lowest active lane (the first
908d8e91e46SDimitry Andric // lane) to all other lanes in the wavefront. We use an intrinsic for this,
909d8e91e46SDimitry Andric // but have to handle 64-bit broadcasts with two calls to this intrinsic.
910d8e91e46SDimitry Andric Value *BroadcastI = nullptr;
911ac9a064cSDimitry Andric BroadcastI = B.CreateIntrinsic(Ty, Intrinsic::amdgcn_readfirstlane, PHI);
912d8e91e46SDimitry Andric
913d8e91e46SDimitry Andric // Now that we have the result of our single atomic operation, we need to
9141d5ae102SDimitry Andric // get our individual lane's slice into the result. We use the lane offset
9151d5ae102SDimitry Andric // we previously calculated combined with the atomic result value we got
9161d5ae102SDimitry Andric // from the first lane, to get our lane's index into the atomic result.
917e6d15924SDimitry Andric Value *LaneOffset = nullptr;
918e6d15924SDimitry Andric if (ValDivergent) {
9197fa27ce4SDimitry Andric if (ScanImpl == ScanOptions::DPP) {
920344a3780SDimitry Andric LaneOffset =
921344a3780SDimitry Andric B.CreateIntrinsic(Intrinsic::amdgcn_strict_wwm, Ty, ExclScan);
9227fa27ce4SDimitry Andric } else if (ScanImpl == ScanOptions::Iterative) {
9237fa27ce4SDimitry Andric LaneOffset = ExclScan;
9247fa27ce4SDimitry Andric } else {
9257fa27ce4SDimitry Andric llvm_unreachable("Atomic Optimzer is disabled for None strategy");
9267fa27ce4SDimitry Andric }
927e6d15924SDimitry Andric } else {
928b1c73532SDimitry Andric Mbcnt = isAtomicFloatingPointTy ? B.CreateUIToFP(Mbcnt, Ty)
929b1c73532SDimitry Andric : B.CreateIntCast(Mbcnt, Ty, false);
930e6d15924SDimitry Andric switch (Op) {
931e6d15924SDimitry Andric default:
932e6d15924SDimitry Andric llvm_unreachable("Unhandled atomic op");
933e6d15924SDimitry Andric case AtomicRMWInst::Add:
934e6d15924SDimitry Andric case AtomicRMWInst::Sub:
935b60736ecSDimitry Andric LaneOffset = buildMul(B, V, Mbcnt);
936e6d15924SDimitry Andric break;
937e6d15924SDimitry Andric case AtomicRMWInst::And:
938e6d15924SDimitry Andric case AtomicRMWInst::Or:
939e6d15924SDimitry Andric case AtomicRMWInst::Max:
940e6d15924SDimitry Andric case AtomicRMWInst::Min:
941e6d15924SDimitry Andric case AtomicRMWInst::UMax:
942e6d15924SDimitry Andric case AtomicRMWInst::UMin:
943b1c73532SDimitry Andric case AtomicRMWInst::FMin:
944b1c73532SDimitry Andric case AtomicRMWInst::FMax:
945e6d15924SDimitry Andric LaneOffset = B.CreateSelect(Cond, Identity, V);
946e6d15924SDimitry Andric break;
947e6d15924SDimitry Andric case AtomicRMWInst::Xor:
948b60736ecSDimitry Andric LaneOffset = buildMul(B, V, B.CreateAnd(Mbcnt, 1));
949e6d15924SDimitry Andric break;
950b1c73532SDimitry Andric case AtomicRMWInst::FAdd:
951b1c73532SDimitry Andric case AtomicRMWInst::FSub: {
952b1c73532SDimitry Andric LaneOffset = B.CreateFMul(V, Mbcnt);
953b1c73532SDimitry Andric break;
954b1c73532SDimitry Andric }
955e6d15924SDimitry Andric }
956e6d15924SDimitry Andric }
957ac9a064cSDimitry Andric Value *Result = buildNonAtomicBinOp(B, Op, BroadcastI, LaneOffset);
958ac9a064cSDimitry Andric if (isAtomicFloatingPointTy) {
959ac9a064cSDimitry Andric // For fadd/fsub the first active lane of LaneOffset should be the
960ac9a064cSDimitry Andric // identity (-0.0 for fadd or +0.0 for fsub) but the value we calculated
961ac9a064cSDimitry Andric // is V * +0.0 which might have the wrong sign or might be nan (if V is
962ac9a064cSDimitry Andric // inf or nan).
963ac9a064cSDimitry Andric //
964ac9a064cSDimitry Andric // For all floating point ops if the in-memory value was a nan then the
965ac9a064cSDimitry Andric // binop we just built might have quieted it or changed its payload.
966ac9a064cSDimitry Andric //
967ac9a064cSDimitry Andric // Correct all these problems by using BroadcastI as the result in the
968ac9a064cSDimitry Andric // first active lane.
969ac9a064cSDimitry Andric Result = B.CreateSelect(Cond, BroadcastI, Result);
970ac9a064cSDimitry Andric }
971d8e91e46SDimitry Andric
972d8e91e46SDimitry Andric if (IsPixelShader) {
973d8e91e46SDimitry Andric // Need a final PHI to reconverge to above the helper lane branch mask.
974b1c73532SDimitry Andric B.SetInsertPoint(PixelExitBB, PixelExitBB->getFirstNonPHIIt());
975d8e91e46SDimitry Andric
976d8e91e46SDimitry Andric PHINode *const PHI = B.CreatePHI(Ty, 2);
977e3b55780SDimitry Andric PHI->addIncoming(PoisonValue::get(Ty), PixelEntryBB);
978d8e91e46SDimitry Andric PHI->addIncoming(Result, I.getParent());
979d8e91e46SDimitry Andric I.replaceAllUsesWith(PHI);
980d8e91e46SDimitry Andric } else {
981d8e91e46SDimitry Andric // Replace the original atomic instruction with the new one.
982d8e91e46SDimitry Andric I.replaceAllUsesWith(Result);
983d8e91e46SDimitry Andric }
9841d5ae102SDimitry Andric }
985d8e91e46SDimitry Andric
986d8e91e46SDimitry Andric // And delete the original.
987d8e91e46SDimitry Andric I.eraseFromParent();
988d8e91e46SDimitry Andric }
989d8e91e46SDimitry Andric
990d8e91e46SDimitry Andric INITIALIZE_PASS_BEGIN(AMDGPUAtomicOptimizer, DEBUG_TYPE,
991d8e91e46SDimitry Andric "AMDGPU atomic optimizations", false, false)
INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass)9927fa27ce4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass)
993d8e91e46SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
994d8e91e46SDimitry Andric INITIALIZE_PASS_END(AMDGPUAtomicOptimizer, DEBUG_TYPE,
995d8e91e46SDimitry Andric "AMDGPU atomic optimizations", false, false)
996d8e91e46SDimitry Andric
9977fa27ce4SDimitry Andric FunctionPass *llvm::createAMDGPUAtomicOptimizerPass(ScanOptions ScanStrategy) {
9987fa27ce4SDimitry Andric return new AMDGPUAtomicOptimizer(ScanStrategy);
999d8e91e46SDimitry Andric }
1000