xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAtomicOptimizer.cpp (revision 5def4c47d4bd90b209b9b4a4ba9faec15846d8fd)
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 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "AMDGPU.h"
17 #include "GCNSubtarget.h"
18 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
19 #include "llvm/CodeGen/TargetPassConfig.h"
20 #include "llvm/IR/IRBuilder.h"
21 #include "llvm/IR/InstVisitor.h"
22 #include "llvm/IR/IntrinsicsAMDGPU.h"
23 #include "llvm/InitializePasses.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
26 
27 #define DEBUG_TYPE "amdgpu-atomic-optimizer"
28 
29 using namespace llvm;
30 using namespace llvm::AMDGPU;
31 
32 namespace {
33 
34 struct ReplacementInfo {
35   Instruction *I;
36   AtomicRMWInst::BinOp Op;
37   unsigned ValIdx;
38   bool ValDivergent;
39 };
40 
41 class AMDGPUAtomicOptimizer : public FunctionPass,
42                               public InstVisitor<AMDGPUAtomicOptimizer> {
43 private:
44   SmallVector<ReplacementInfo, 8> ToReplace;
45   const LegacyDivergenceAnalysis *DA;
46   const DataLayout *DL;
47   DominatorTree *DT;
48   const GCNSubtarget *ST;
49   bool IsPixelShader;
50 
51   Value *buildScan(IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *V,
52                    Value *const Identity) const;
53   Value *buildShiftRight(IRBuilder<> &B, Value *V, Value *const Identity) const;
54   void optimizeAtomic(Instruction &I, AtomicRMWInst::BinOp Op, unsigned ValIdx,
55                       bool ValDivergent) const;
56 
57 public:
58   static char ID;
59 
60   AMDGPUAtomicOptimizer() : FunctionPass(ID) {}
61 
62   bool runOnFunction(Function &F) override;
63 
64   void getAnalysisUsage(AnalysisUsage &AU) const override {
65     AU.addPreserved<DominatorTreeWrapperPass>();
66     AU.addRequired<LegacyDivergenceAnalysis>();
67     AU.addRequired<TargetPassConfig>();
68   }
69 
70   void visitAtomicRMWInst(AtomicRMWInst &I);
71   void visitIntrinsicInst(IntrinsicInst &I);
72 };
73 
74 } // namespace
75 
76 char AMDGPUAtomicOptimizer::ID = 0;
77 
78 char &llvm::AMDGPUAtomicOptimizerID = AMDGPUAtomicOptimizer::ID;
79 
80 bool AMDGPUAtomicOptimizer::runOnFunction(Function &F) {
81   if (skipFunction(F)) {
82     return false;
83   }
84 
85   DA = &getAnalysis<LegacyDivergenceAnalysis>();
86   DL = &F.getParent()->getDataLayout();
87   DominatorTreeWrapperPass *const DTW =
88       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
89   DT = DTW ? &DTW->getDomTree() : nullptr;
90   const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
91   const TargetMachine &TM = TPC.getTM<TargetMachine>();
92   ST = &TM.getSubtarget<GCNSubtarget>(F);
93   IsPixelShader = F.getCallingConv() == CallingConv::AMDGPU_PS;
94 
95   visit(F);
96 
97   const bool Changed = !ToReplace.empty();
98 
99   for (ReplacementInfo &Info : ToReplace) {
100     optimizeAtomic(*Info.I, Info.Op, Info.ValIdx, Info.ValDivergent);
101   }
102 
103   ToReplace.clear();
104 
105   return Changed;
106 }
107 
108 void AMDGPUAtomicOptimizer::visitAtomicRMWInst(AtomicRMWInst &I) {
109   // Early exit for unhandled address space atomic instructions.
110   switch (I.getPointerAddressSpace()) {
111   default:
112     return;
113   case AMDGPUAS::GLOBAL_ADDRESS:
114   case AMDGPUAS::LOCAL_ADDRESS:
115     break;
116   }
117 
118   AtomicRMWInst::BinOp Op = I.getOperation();
119 
120   switch (Op) {
121   default:
122     return;
123   case AtomicRMWInst::Add:
124   case AtomicRMWInst::Sub:
125   case AtomicRMWInst::And:
126   case AtomicRMWInst::Or:
127   case AtomicRMWInst::Xor:
128   case AtomicRMWInst::Max:
129   case AtomicRMWInst::Min:
130   case AtomicRMWInst::UMax:
131   case AtomicRMWInst::UMin:
132     break;
133   }
134 
135   const unsigned PtrIdx = 0;
136   const unsigned ValIdx = 1;
137 
138   // If the pointer operand is divergent, then each lane is doing an atomic
139   // operation on a different address, and we cannot optimize that.
140   if (DA->isDivergentUse(&I.getOperandUse(PtrIdx))) {
141     return;
142   }
143 
144   const bool ValDivergent = DA->isDivergentUse(&I.getOperandUse(ValIdx));
145 
146   // If the value operand is divergent, each lane is contributing a different
147   // value to the atomic calculation. We can only optimize divergent values if
148   // we have DPP available on our subtarget, and the atomic operation is 32
149   // bits.
150   if (ValDivergent &&
151       (!ST->hasDPP() || DL->getTypeSizeInBits(I.getType()) != 32)) {
152     return;
153   }
154 
155   // If we get here, we can optimize the atomic using a single wavefront-wide
156   // atomic operation to do the calculation for the entire wavefront, so
157   // remember the instruction so we can come back to it.
158   const ReplacementInfo Info = {&I, Op, ValIdx, ValDivergent};
159 
160   ToReplace.push_back(Info);
161 }
162 
163 void AMDGPUAtomicOptimizer::visitIntrinsicInst(IntrinsicInst &I) {
164   AtomicRMWInst::BinOp Op;
165 
166   switch (I.getIntrinsicID()) {
167   default:
168     return;
169   case Intrinsic::amdgcn_buffer_atomic_add:
170   case Intrinsic::amdgcn_struct_buffer_atomic_add:
171   case Intrinsic::amdgcn_raw_buffer_atomic_add:
172     Op = AtomicRMWInst::Add;
173     break;
174   case Intrinsic::amdgcn_buffer_atomic_sub:
175   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
176   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
177     Op = AtomicRMWInst::Sub;
178     break;
179   case Intrinsic::amdgcn_buffer_atomic_and:
180   case Intrinsic::amdgcn_struct_buffer_atomic_and:
181   case Intrinsic::amdgcn_raw_buffer_atomic_and:
182     Op = AtomicRMWInst::And;
183     break;
184   case Intrinsic::amdgcn_buffer_atomic_or:
185   case Intrinsic::amdgcn_struct_buffer_atomic_or:
186   case Intrinsic::amdgcn_raw_buffer_atomic_or:
187     Op = AtomicRMWInst::Or;
188     break;
189   case Intrinsic::amdgcn_buffer_atomic_xor:
190   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
191   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
192     Op = AtomicRMWInst::Xor;
193     break;
194   case Intrinsic::amdgcn_buffer_atomic_smin:
195   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
196   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
197     Op = AtomicRMWInst::Min;
198     break;
199   case Intrinsic::amdgcn_buffer_atomic_umin:
200   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
201   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
202     Op = AtomicRMWInst::UMin;
203     break;
204   case Intrinsic::amdgcn_buffer_atomic_smax:
205   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
206   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
207     Op = AtomicRMWInst::Max;
208     break;
209   case Intrinsic::amdgcn_buffer_atomic_umax:
210   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
211   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
212     Op = AtomicRMWInst::UMax;
213     break;
214   }
215 
216   const unsigned ValIdx = 0;
217 
218   const bool ValDivergent = DA->isDivergentUse(&I.getOperandUse(ValIdx));
219 
220   // If the value operand is divergent, each lane is contributing a different
221   // value to the atomic calculation. We can only optimize divergent values if
222   // we have DPP available on our subtarget, and the atomic operation is 32
223   // bits.
224   if (ValDivergent &&
225       (!ST->hasDPP() || DL->getTypeSizeInBits(I.getType()) != 32)) {
226     return;
227   }
228 
229   // If any of the other arguments to the intrinsic are divergent, we can't
230   // optimize the operation.
231   for (unsigned Idx = 1; Idx < I.getNumOperands(); Idx++) {
232     if (DA->isDivergentUse(&I.getOperandUse(Idx))) {
233       return;
234     }
235   }
236 
237   // If we get here, we can optimize the atomic using a single wavefront-wide
238   // atomic operation to do the calculation for the entire wavefront, so
239   // remember the instruction so we can come back to it.
240   const ReplacementInfo Info = {&I, Op, ValIdx, ValDivergent};
241 
242   ToReplace.push_back(Info);
243 }
244 
245 // Use the builder to create the non-atomic counterpart of the specified
246 // atomicrmw binary op.
247 static Value *buildNonAtomicBinOp(IRBuilder<> &B, AtomicRMWInst::BinOp Op,
248                                   Value *LHS, Value *RHS) {
249   CmpInst::Predicate Pred;
250 
251   switch (Op) {
252   default:
253     llvm_unreachable("Unhandled atomic op");
254   case AtomicRMWInst::Add:
255     return B.CreateBinOp(Instruction::Add, LHS, RHS);
256   case AtomicRMWInst::Sub:
257     return B.CreateBinOp(Instruction::Sub, LHS, RHS);
258   case AtomicRMWInst::And:
259     return B.CreateBinOp(Instruction::And, LHS, RHS);
260   case AtomicRMWInst::Or:
261     return B.CreateBinOp(Instruction::Or, LHS, RHS);
262   case AtomicRMWInst::Xor:
263     return B.CreateBinOp(Instruction::Xor, LHS, RHS);
264 
265   case AtomicRMWInst::Max:
266     Pred = CmpInst::ICMP_SGT;
267     break;
268   case AtomicRMWInst::Min:
269     Pred = CmpInst::ICMP_SLT;
270     break;
271   case AtomicRMWInst::UMax:
272     Pred = CmpInst::ICMP_UGT;
273     break;
274   case AtomicRMWInst::UMin:
275     Pred = CmpInst::ICMP_ULT;
276     break;
277   }
278   Value *Cond = B.CreateICmp(Pred, LHS, RHS);
279   return B.CreateSelect(Cond, LHS, RHS);
280 }
281 
282 // Use the builder to create an inclusive scan of V across the wavefront, with
283 // all lanes active.
284 Value *AMDGPUAtomicOptimizer::buildScan(IRBuilder<> &B, AtomicRMWInst::BinOp Op,
285                                         Value *V, Value *const Identity) const {
286   Type *const Ty = V->getType();
287   Module *M = B.GetInsertBlock()->getModule();
288   Function *UpdateDPP =
289       Intrinsic::getDeclaration(M, Intrinsic::amdgcn_update_dpp, Ty);
290   Function *PermLaneX16 =
291       Intrinsic::getDeclaration(M, Intrinsic::amdgcn_permlanex16, {});
292   Function *ReadLane =
293       Intrinsic::getDeclaration(M, Intrinsic::amdgcn_readlane, {});
294 
295   for (unsigned Idx = 0; Idx < 4; Idx++) {
296     V = buildNonAtomicBinOp(
297         B, Op, V,
298         B.CreateCall(UpdateDPP,
299                      {Identity, V, B.getInt32(DPP::ROW_SHR0 | 1 << Idx),
300                       B.getInt32(0xf), B.getInt32(0xf), B.getFalse()}));
301   }
302   if (ST->hasDPPBroadcasts()) {
303     // GFX9 has DPP row broadcast operations.
304     V = buildNonAtomicBinOp(
305         B, Op, V,
306         B.CreateCall(UpdateDPP,
307                      {Identity, V, B.getInt32(DPP::BCAST15), B.getInt32(0xa),
308                       B.getInt32(0xf), B.getFalse()}));
309     V = buildNonAtomicBinOp(
310         B, Op, V,
311         B.CreateCall(UpdateDPP,
312                      {Identity, V, B.getInt32(DPP::BCAST31), B.getInt32(0xc),
313                       B.getInt32(0xf), B.getFalse()}));
314   } else {
315     // On GFX10 all DPP operations are confined to a single row. To get cross-
316     // row operations we have to use permlane or readlane.
317 
318     // Combine lane 15 into lanes 16..31 (and, for wave 64, lane 47 into lanes
319     // 48..63).
320     Value *const PermX =
321         B.CreateCall(PermLaneX16, {V, V, B.getInt32(-1), B.getInt32(-1),
322                                    B.getFalse(), B.getFalse()});
323     V = buildNonAtomicBinOp(
324         B, Op, V,
325         B.CreateCall(UpdateDPP,
326                      {Identity, PermX, B.getInt32(DPP::QUAD_PERM_ID),
327                       B.getInt32(0xa), B.getInt32(0xf), B.getFalse()}));
328     if (!ST->isWave32()) {
329       // Combine lane 31 into lanes 32..63.
330       Value *const Lane31 = B.CreateCall(ReadLane, {V, B.getInt32(31)});
331       V = buildNonAtomicBinOp(
332           B, Op, V,
333           B.CreateCall(UpdateDPP,
334                        {Identity, Lane31, B.getInt32(DPP::QUAD_PERM_ID),
335                         B.getInt32(0xc), B.getInt32(0xf), B.getFalse()}));
336     }
337   }
338   return V;
339 }
340 
341 // Use the builder to create a shift right of V across the wavefront, with all
342 // lanes active, to turn an inclusive scan into an exclusive scan.
343 Value *AMDGPUAtomicOptimizer::buildShiftRight(IRBuilder<> &B, Value *V,
344                                               Value *const Identity) const {
345   Type *const Ty = V->getType();
346   Module *M = B.GetInsertBlock()->getModule();
347   Function *UpdateDPP =
348       Intrinsic::getDeclaration(M, Intrinsic::amdgcn_update_dpp, Ty);
349   Function *ReadLane =
350       Intrinsic::getDeclaration(M, Intrinsic::amdgcn_readlane, {});
351   Function *WriteLane =
352       Intrinsic::getDeclaration(M, Intrinsic::amdgcn_writelane, {});
353 
354   if (ST->hasDPPWavefrontShifts()) {
355     // GFX9 has DPP wavefront shift operations.
356     V = B.CreateCall(UpdateDPP,
357                      {Identity, V, B.getInt32(DPP::WAVE_SHR1), B.getInt32(0xf),
358                       B.getInt32(0xf), B.getFalse()});
359   } else {
360     // On GFX10 all DPP operations are confined to a single row. To get cross-
361     // row operations we have to use permlane or readlane.
362     Value *Old = V;
363     V = B.CreateCall(UpdateDPP,
364                      {Identity, V, B.getInt32(DPP::ROW_SHR0 + 1),
365                       B.getInt32(0xf), B.getInt32(0xf), B.getFalse()});
366 
367     // Copy the old lane 15 to the new lane 16.
368     V = B.CreateCall(WriteLane, {B.CreateCall(ReadLane, {Old, B.getInt32(15)}),
369                                  B.getInt32(16), V});
370 
371     if (!ST->isWave32()) {
372       // Copy the old lane 31 to the new lane 32.
373       V = B.CreateCall(
374           WriteLane,
375           {B.CreateCall(ReadLane, {Old, B.getInt32(31)}), B.getInt32(32), V});
376 
377       // Copy the old lane 47 to the new lane 48.
378       V = B.CreateCall(
379           WriteLane,
380           {B.CreateCall(ReadLane, {Old, B.getInt32(47)}), B.getInt32(48), V});
381     }
382   }
383 
384   return V;
385 }
386 
387 static APInt getIdentityValueForAtomicOp(AtomicRMWInst::BinOp Op,
388                                          unsigned BitWidth) {
389   switch (Op) {
390   default:
391     llvm_unreachable("Unhandled atomic op");
392   case AtomicRMWInst::Add:
393   case AtomicRMWInst::Sub:
394   case AtomicRMWInst::Or:
395   case AtomicRMWInst::Xor:
396   case AtomicRMWInst::UMax:
397     return APInt::getMinValue(BitWidth);
398   case AtomicRMWInst::And:
399   case AtomicRMWInst::UMin:
400     return APInt::getMaxValue(BitWidth);
401   case AtomicRMWInst::Max:
402     return APInt::getSignedMinValue(BitWidth);
403   case AtomicRMWInst::Min:
404     return APInt::getSignedMaxValue(BitWidth);
405   }
406 }
407 
408 static Value *buildMul(IRBuilder<> &B, Value *LHS, Value *RHS) {
409   const ConstantInt *CI = dyn_cast<ConstantInt>(LHS);
410   return (CI && CI->isOne()) ? RHS : B.CreateMul(LHS, RHS);
411 }
412 
413 void AMDGPUAtomicOptimizer::optimizeAtomic(Instruction &I,
414                                            AtomicRMWInst::BinOp Op,
415                                            unsigned ValIdx,
416                                            bool ValDivergent) const {
417   // Start building just before the instruction.
418   IRBuilder<> B(&I);
419 
420   // If we are in a pixel shader, because of how we have to mask out helper
421   // lane invocations, we need to record the entry and exit BB's.
422   BasicBlock *PixelEntryBB = nullptr;
423   BasicBlock *PixelExitBB = nullptr;
424 
425   // If we're optimizing an atomic within a pixel shader, we need to wrap the
426   // entire atomic operation in a helper-lane check. We do not want any helper
427   // lanes that are around only for the purposes of derivatives to take part
428   // in any cross-lane communication, and we use a branch on whether the lane is
429   // live to do this.
430   if (IsPixelShader) {
431     // Record I's original position as the entry block.
432     PixelEntryBB = I.getParent();
433 
434     Value *const Cond = B.CreateIntrinsic(Intrinsic::amdgcn_ps_live, {}, {});
435     Instruction *const NonHelperTerminator =
436         SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, DT, nullptr);
437 
438     // Record I's new position as the exit block.
439     PixelExitBB = I.getParent();
440 
441     I.moveBefore(NonHelperTerminator);
442     B.SetInsertPoint(&I);
443   }
444 
445   Type *const Ty = I.getType();
446   const unsigned TyBitWidth = DL->getTypeSizeInBits(Ty);
447   auto *const VecTy = FixedVectorType::get(B.getInt32Ty(), 2);
448 
449   // This is the value in the atomic operation we need to combine in order to
450   // reduce the number of atomic operations.
451   Value *const V = I.getOperand(ValIdx);
452 
453   // We need to know how many lanes are active within the wavefront, and we do
454   // this by doing a ballot of active lanes.
455   Type *const WaveTy = B.getIntNTy(ST->getWavefrontSize());
456   CallInst *const Ballot =
457       B.CreateIntrinsic(Intrinsic::amdgcn_ballot, WaveTy, B.getTrue());
458 
459   // We need to know how many lanes are active within the wavefront that are
460   // below us. If we counted each lane linearly starting from 0, a lane is
461   // below us only if its associated index was less than ours. We do this by
462   // using the mbcnt intrinsic.
463   Value *Mbcnt;
464   if (ST->isWave32()) {
465     Mbcnt = B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_lo, {},
466                               {Ballot, B.getInt32(0)});
467   } else {
468     Value *const BitCast = B.CreateBitCast(Ballot, VecTy);
469     Value *const ExtractLo = B.CreateExtractElement(BitCast, B.getInt32(0));
470     Value *const ExtractHi = B.CreateExtractElement(BitCast, B.getInt32(1));
471     Mbcnt = B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_lo, {},
472                               {ExtractLo, B.getInt32(0)});
473     Mbcnt =
474         B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_hi, {}, {ExtractHi, Mbcnt});
475   }
476   Mbcnt = B.CreateIntCast(Mbcnt, Ty, false);
477 
478   Value *const Identity = B.getInt(getIdentityValueForAtomicOp(Op, TyBitWidth));
479 
480   Value *ExclScan = nullptr;
481   Value *NewV = nullptr;
482 
483   // If we have a divergent value in each lane, we need to combine the value
484   // using DPP.
485   if (ValDivergent) {
486     // First we need to set all inactive invocations to the identity value, so
487     // that they can correctly contribute to the final result.
488     NewV = B.CreateIntrinsic(Intrinsic::amdgcn_set_inactive, Ty, {V, Identity});
489 
490     const AtomicRMWInst::BinOp ScanOp =
491         Op == AtomicRMWInst::Sub ? AtomicRMWInst::Add : Op;
492     NewV = buildScan(B, ScanOp, NewV, Identity);
493     ExclScan = buildShiftRight(B, NewV, Identity);
494 
495     // Read the value from the last lane, which has accumlated the values of
496     // each active lane in the wavefront. This will be our new value which we
497     // will provide to the atomic operation.
498     Value *const LastLaneIdx = B.getInt32(ST->getWavefrontSize() - 1);
499     if (TyBitWidth == 64) {
500       Value *const ExtractLo = B.CreateTrunc(NewV, B.getInt32Ty());
501       Value *const ExtractHi =
502           B.CreateTrunc(B.CreateLShr(NewV, 32), B.getInt32Ty());
503       CallInst *const ReadLaneLo = B.CreateIntrinsic(
504           Intrinsic::amdgcn_readlane, {}, {ExtractLo, LastLaneIdx});
505       CallInst *const ReadLaneHi = B.CreateIntrinsic(
506           Intrinsic::amdgcn_readlane, {}, {ExtractHi, LastLaneIdx});
507       Value *const PartialInsert = B.CreateInsertElement(
508           UndefValue::get(VecTy), ReadLaneLo, B.getInt32(0));
509       Value *const Insert =
510           B.CreateInsertElement(PartialInsert, ReadLaneHi, B.getInt32(1));
511       NewV = B.CreateBitCast(Insert, Ty);
512     } else if (TyBitWidth == 32) {
513       NewV = B.CreateIntrinsic(Intrinsic::amdgcn_readlane, {},
514                                {NewV, LastLaneIdx});
515     } else {
516       llvm_unreachable("Unhandled atomic bit width");
517     }
518 
519     // Finally mark the readlanes in the WWM section.
520     NewV = B.CreateIntrinsic(Intrinsic::amdgcn_wwm, Ty, NewV);
521   } else {
522     switch (Op) {
523     default:
524       llvm_unreachable("Unhandled atomic op");
525 
526     case AtomicRMWInst::Add:
527     case AtomicRMWInst::Sub: {
528       // The new value we will be contributing to the atomic operation is the
529       // old value times the number of active lanes.
530       Value *const Ctpop = B.CreateIntCast(
531           B.CreateUnaryIntrinsic(Intrinsic::ctpop, Ballot), Ty, false);
532       NewV = buildMul(B, V, Ctpop);
533       break;
534     }
535 
536     case AtomicRMWInst::And:
537     case AtomicRMWInst::Or:
538     case AtomicRMWInst::Max:
539     case AtomicRMWInst::Min:
540     case AtomicRMWInst::UMax:
541     case AtomicRMWInst::UMin:
542       // These operations with a uniform value are idempotent: doing the atomic
543       // operation multiple times has the same effect as doing it once.
544       NewV = V;
545       break;
546 
547     case AtomicRMWInst::Xor:
548       // The new value we will be contributing to the atomic operation is the
549       // old value times the parity of the number of active lanes.
550       Value *const Ctpop = B.CreateIntCast(
551           B.CreateUnaryIntrinsic(Intrinsic::ctpop, Ballot), Ty, false);
552       NewV = buildMul(B, V, B.CreateAnd(Ctpop, 1));
553       break;
554     }
555   }
556 
557   // We only want a single lane to enter our new control flow, and we do this
558   // by checking if there are any active lanes below us. Only one lane will
559   // have 0 active lanes below us, so that will be the only one to progress.
560   Value *const Cond = B.CreateICmpEQ(Mbcnt, B.getIntN(TyBitWidth, 0));
561 
562   // Store I's original basic block before we split the block.
563   BasicBlock *const EntryBB = I.getParent();
564 
565   // We need to introduce some new control flow to force a single lane to be
566   // active. We do this by splitting I's basic block at I, and introducing the
567   // new block such that:
568   // entry --> single_lane -\
569   //       \------------------> exit
570   Instruction *const SingleLaneTerminator =
571       SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, DT, nullptr);
572 
573   // Move the IR builder into single_lane next.
574   B.SetInsertPoint(SingleLaneTerminator);
575 
576   // Clone the original atomic operation into single lane, replacing the
577   // original value with our newly created one.
578   Instruction *const NewI = I.clone();
579   B.Insert(NewI);
580   NewI->setOperand(ValIdx, NewV);
581 
582   // Move the IR builder into exit next, and start inserting just before the
583   // original instruction.
584   B.SetInsertPoint(&I);
585 
586   const bool NeedResult = !I.use_empty();
587   if (NeedResult) {
588     // Create a PHI node to get our new atomic result into the exit block.
589     PHINode *const PHI = B.CreatePHI(Ty, 2);
590     PHI->addIncoming(UndefValue::get(Ty), EntryBB);
591     PHI->addIncoming(NewI, SingleLaneTerminator->getParent());
592 
593     // We need to broadcast the value who was the lowest active lane (the first
594     // lane) to all other lanes in the wavefront. We use an intrinsic for this,
595     // but have to handle 64-bit broadcasts with two calls to this intrinsic.
596     Value *BroadcastI = nullptr;
597 
598     if (TyBitWidth == 64) {
599       Value *const ExtractLo = B.CreateTrunc(PHI, B.getInt32Ty());
600       Value *const ExtractHi =
601           B.CreateTrunc(B.CreateLShr(PHI, 32), B.getInt32Ty());
602       CallInst *const ReadFirstLaneLo =
603           B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, ExtractLo);
604       CallInst *const ReadFirstLaneHi =
605           B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, ExtractHi);
606       Value *const PartialInsert = B.CreateInsertElement(
607           UndefValue::get(VecTy), ReadFirstLaneLo, B.getInt32(0));
608       Value *const Insert =
609           B.CreateInsertElement(PartialInsert, ReadFirstLaneHi, B.getInt32(1));
610       BroadcastI = B.CreateBitCast(Insert, Ty);
611     } else if (TyBitWidth == 32) {
612 
613       BroadcastI = B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, PHI);
614     } else {
615       llvm_unreachable("Unhandled atomic bit width");
616     }
617 
618     // Now that we have the result of our single atomic operation, we need to
619     // get our individual lane's slice into the result. We use the lane offset
620     // we previously calculated combined with the atomic result value we got
621     // from the first lane, to get our lane's index into the atomic result.
622     Value *LaneOffset = nullptr;
623     if (ValDivergent) {
624       LaneOffset = B.CreateIntrinsic(Intrinsic::amdgcn_wwm, Ty, ExclScan);
625     } else {
626       switch (Op) {
627       default:
628         llvm_unreachable("Unhandled atomic op");
629       case AtomicRMWInst::Add:
630       case AtomicRMWInst::Sub:
631         LaneOffset = buildMul(B, V, Mbcnt);
632         break;
633       case AtomicRMWInst::And:
634       case AtomicRMWInst::Or:
635       case AtomicRMWInst::Max:
636       case AtomicRMWInst::Min:
637       case AtomicRMWInst::UMax:
638       case AtomicRMWInst::UMin:
639         LaneOffset = B.CreateSelect(Cond, Identity, V);
640         break;
641       case AtomicRMWInst::Xor:
642         LaneOffset = buildMul(B, V, B.CreateAnd(Mbcnt, 1));
643         break;
644       }
645     }
646     Value *const Result = buildNonAtomicBinOp(B, Op, BroadcastI, LaneOffset);
647 
648     if (IsPixelShader) {
649       // Need a final PHI to reconverge to above the helper lane branch mask.
650       B.SetInsertPoint(PixelExitBB->getFirstNonPHI());
651 
652       PHINode *const PHI = B.CreatePHI(Ty, 2);
653       PHI->addIncoming(UndefValue::get(Ty), PixelEntryBB);
654       PHI->addIncoming(Result, I.getParent());
655       I.replaceAllUsesWith(PHI);
656     } else {
657       // Replace the original atomic instruction with the new one.
658       I.replaceAllUsesWith(Result);
659     }
660   }
661 
662   // And delete the original.
663   I.eraseFromParent();
664 }
665 
666 INITIALIZE_PASS_BEGIN(AMDGPUAtomicOptimizer, DEBUG_TYPE,
667                       "AMDGPU atomic optimizations", false, false)
668 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
669 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
670 INITIALIZE_PASS_END(AMDGPUAtomicOptimizer, DEBUG_TYPE,
671                     "AMDGPU atomic optimizations", false, false)
672 
673 FunctionPass *llvm::createAMDGPUAtomicOptimizerPass() {
674   return new AMDGPUAtomicOptimizer();
675 }
676