xref: /llvm-project/llvm/lib/CodeGen/AtomicExpandPass.cpp (revision 06286832db0c4ee1899f9cee1b8f6234e45f16c7)
1 //===- AtomicExpandPass.cpp - Expand atomic instructions ------------------===//
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 // This file contains a pass (at IR level) to replace atomic instructions with
10 // __atomic_* library calls, or target specific instruction which implement the
11 // same semantics in a way which better fits the target backend.  This can
12 // include the use of (intrinsic-based) load-linked/store-conditional loops,
13 // AtomicCmpXchg, or type coercions.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/STLFunctionalExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Analysis/InstSimplifyFolder.h"
21 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
22 #include "llvm/CodeGen/AtomicExpand.h"
23 #include "llvm/CodeGen/AtomicExpandUtils.h"
24 #include "llvm/CodeGen/RuntimeLibcallUtil.h"
25 #include "llvm/CodeGen/TargetLowering.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/CodeGen/TargetSubtargetInfo.h"
28 #include "llvm/CodeGen/ValueTypes.h"
29 #include "llvm/IR/Attributes.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/Constant.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/IRBuilder.h"
37 #include "llvm/IR/InstIterator.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/MDBuilder.h"
41 #include "llvm/IR/MemoryModelRelaxationAnnotations.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/IR/User.h"
45 #include "llvm/IR/Value.h"
46 #include "llvm/InitializePasses.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/AtomicOrdering.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Transforms/Utils/LowerAtomic.h"
55 #include <cassert>
56 #include <cstdint>
57 #include <iterator>
58 
59 using namespace llvm;
60 
61 #define DEBUG_TYPE "atomic-expand"
62 
63 namespace {
64 
65 class AtomicExpandImpl {
66   const TargetLowering *TLI = nullptr;
67   const DataLayout *DL = nullptr;
68 
69 private:
70   bool bracketInstWithFences(Instruction *I, AtomicOrdering Order);
71   IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
72   LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
73   bool tryExpandAtomicLoad(LoadInst *LI);
74   bool expandAtomicLoadToLL(LoadInst *LI);
75   bool expandAtomicLoadToCmpXchg(LoadInst *LI);
76   StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
77   bool tryExpandAtomicStore(StoreInst *SI);
78   void expandAtomicStore(StoreInst *SI);
79   bool tryExpandAtomicRMW(AtomicRMWInst *AI);
80   AtomicRMWInst *convertAtomicXchgToIntegerType(AtomicRMWInst *RMWI);
81   Value *
82   insertRMWLLSCLoop(IRBuilderBase &Builder, Type *ResultTy, Value *Addr,
83                     Align AddrAlign, AtomicOrdering MemOpOrder,
84                     function_ref<Value *(IRBuilderBase &, Value *)> PerformOp);
85   void expandAtomicOpToLLSC(
86       Instruction *I, Type *ResultTy, Value *Addr, Align AddrAlign,
87       AtomicOrdering MemOpOrder,
88       function_ref<Value *(IRBuilderBase &, Value *)> PerformOp);
89   void expandPartwordAtomicRMW(
90       AtomicRMWInst *I, TargetLoweringBase::AtomicExpansionKind ExpansionKind);
91   AtomicRMWInst *widenPartwordAtomicRMW(AtomicRMWInst *AI);
92   bool expandPartwordCmpXchg(AtomicCmpXchgInst *I);
93   void expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI);
94   void expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI);
95 
96   AtomicCmpXchgInst *convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI);
97   static Value *insertRMWCmpXchgLoop(
98       IRBuilderBase &Builder, Type *ResultType, Value *Addr, Align AddrAlign,
99       AtomicOrdering MemOpOrder, SyncScope::ID SSID,
100       function_ref<Value *(IRBuilderBase &, Value *)> PerformOp,
101       CreateCmpXchgInstFun CreateCmpXchg);
102   bool tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI);
103 
104   bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
105   bool isIdempotentRMW(AtomicRMWInst *RMWI);
106   bool simplifyIdempotentRMW(AtomicRMWInst *RMWI);
107 
108   bool expandAtomicOpToLibcall(Instruction *I, unsigned Size, Align Alignment,
109                                Value *PointerOperand, Value *ValueOperand,
110                                Value *CASExpected, AtomicOrdering Ordering,
111                                AtomicOrdering Ordering2,
112                                ArrayRef<RTLIB::Libcall> Libcalls);
113   void expandAtomicLoadToLibcall(LoadInst *LI);
114   void expandAtomicStoreToLibcall(StoreInst *LI);
115   void expandAtomicRMWToLibcall(AtomicRMWInst *I);
116   void expandAtomicCASToLibcall(AtomicCmpXchgInst *I);
117 
118   friend bool
119   llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
120                                  CreateCmpXchgInstFun CreateCmpXchg);
121 
122   bool processAtomicInstr(Instruction *I);
123 
124 public:
125   bool run(Function &F, const TargetMachine *TM);
126 };
127 
128 class AtomicExpandLegacy : public FunctionPass {
129 public:
130   static char ID; // Pass identification, replacement for typeid
131 
132   AtomicExpandLegacy() : FunctionPass(ID) {
133     initializeAtomicExpandLegacyPass(*PassRegistry::getPassRegistry());
134   }
135 
136   bool runOnFunction(Function &F) override;
137 };
138 
139 // IRBuilder to be used for replacement atomic instructions.
140 struct ReplacementIRBuilder
141     : IRBuilder<InstSimplifyFolder, IRBuilderCallbackInserter> {
142   MDNode *MMRAMD = nullptr;
143 
144   // Preserves the DebugLoc from I, and preserves still valid metadata.
145   // Enable StrictFP builder mode when appropriate.
146   explicit ReplacementIRBuilder(Instruction *I, const DataLayout &DL)
147       : IRBuilder(I->getContext(), InstSimplifyFolder(DL),
148                   IRBuilderCallbackInserter(
149                       [this](Instruction *I) { addMMRAMD(I); })) {
150     SetInsertPoint(I);
151     this->CollectMetadataToCopy(I, {LLVMContext::MD_pcsections});
152     if (BB->getParent()->getAttributes().hasFnAttr(Attribute::StrictFP))
153       this->setIsFPConstrained(true);
154 
155     MMRAMD = I->getMetadata(LLVMContext::MD_mmra);
156   }
157 
158   void addMMRAMD(Instruction *I) {
159     if (canInstructionHaveMMRAs(*I))
160       I->setMetadata(LLVMContext::MD_mmra, MMRAMD);
161   }
162 };
163 
164 } // end anonymous namespace
165 
166 char AtomicExpandLegacy::ID = 0;
167 
168 char &llvm::AtomicExpandID = AtomicExpandLegacy::ID;
169 
170 INITIALIZE_PASS_BEGIN(AtomicExpandLegacy, DEBUG_TYPE,
171                       "Expand Atomic instructions", false, false)
172 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
173 INITIALIZE_PASS_END(AtomicExpandLegacy, DEBUG_TYPE,
174                     "Expand Atomic instructions", false, false)
175 
176 // Helper functions to retrieve the size of atomic instructions.
177 static unsigned getAtomicOpSize(LoadInst *LI) {
178   const DataLayout &DL = LI->getDataLayout();
179   return DL.getTypeStoreSize(LI->getType());
180 }
181 
182 static unsigned getAtomicOpSize(StoreInst *SI) {
183   const DataLayout &DL = SI->getDataLayout();
184   return DL.getTypeStoreSize(SI->getValueOperand()->getType());
185 }
186 
187 static unsigned getAtomicOpSize(AtomicRMWInst *RMWI) {
188   const DataLayout &DL = RMWI->getDataLayout();
189   return DL.getTypeStoreSize(RMWI->getValOperand()->getType());
190 }
191 
192 static unsigned getAtomicOpSize(AtomicCmpXchgInst *CASI) {
193   const DataLayout &DL = CASI->getDataLayout();
194   return DL.getTypeStoreSize(CASI->getCompareOperand()->getType());
195 }
196 
197 // Determine if a particular atomic operation has a supported size,
198 // and is of appropriate alignment, to be passed through for target
199 // lowering. (Versus turning into a __atomic libcall)
200 template <typename Inst>
201 static bool atomicSizeSupported(const TargetLowering *TLI, Inst *I) {
202   unsigned Size = getAtomicOpSize(I);
203   Align Alignment = I->getAlign();
204   return Alignment >= Size &&
205          Size <= TLI->getMaxAtomicSizeInBitsSupported() / 8;
206 }
207 
208 bool AtomicExpandImpl::processAtomicInstr(Instruction *I) {
209   auto *LI = dyn_cast<LoadInst>(I);
210   auto *SI = dyn_cast<StoreInst>(I);
211   auto *RMWI = dyn_cast<AtomicRMWInst>(I);
212   auto *CASI = dyn_cast<AtomicCmpXchgInst>(I);
213 
214   bool MadeChange = false;
215 
216   // If the Size/Alignment is not supported, replace with a libcall.
217   if (LI) {
218     if (!LI->isAtomic())
219       return false;
220 
221     if (!atomicSizeSupported(TLI, LI)) {
222       expandAtomicLoadToLibcall(LI);
223       return true;
224     }
225 
226     if (TLI->shouldCastAtomicLoadInIR(LI) ==
227         TargetLoweringBase::AtomicExpansionKind::CastToInteger) {
228       I = LI = convertAtomicLoadToIntegerType(LI);
229       MadeChange = true;
230     }
231   } else if (SI) {
232     if (!SI->isAtomic())
233       return false;
234 
235     if (!atomicSizeSupported(TLI, SI)) {
236       expandAtomicStoreToLibcall(SI);
237       return true;
238     }
239 
240     if (TLI->shouldCastAtomicStoreInIR(SI) ==
241         TargetLoweringBase::AtomicExpansionKind::CastToInteger) {
242       I = SI = convertAtomicStoreToIntegerType(SI);
243       MadeChange = true;
244     }
245   } else if (RMWI) {
246     if (!atomicSizeSupported(TLI, RMWI)) {
247       expandAtomicRMWToLibcall(RMWI);
248       return true;
249     }
250 
251     if (TLI->shouldCastAtomicRMWIInIR(RMWI) ==
252         TargetLoweringBase::AtomicExpansionKind::CastToInteger) {
253       I = RMWI = convertAtomicXchgToIntegerType(RMWI);
254       MadeChange = true;
255     }
256   } else if (CASI) {
257     if (!atomicSizeSupported(TLI, CASI)) {
258       expandAtomicCASToLibcall(CASI);
259       return true;
260     }
261 
262     // TODO: when we're ready to make the change at the IR level, we can
263     // extend convertCmpXchgToInteger for floating point too.
264     if (CASI->getCompareOperand()->getType()->isPointerTy()) {
265       // TODO: add a TLI hook to control this so that each target can
266       // convert to lowering the original type one at a time.
267       I = CASI = convertCmpXchgToIntegerType(CASI);
268       MadeChange = true;
269     }
270   } else
271     return false;
272 
273   if (TLI->shouldInsertFencesForAtomic(I)) {
274     auto FenceOrdering = AtomicOrdering::Monotonic;
275     if (LI && isAcquireOrStronger(LI->getOrdering())) {
276       FenceOrdering = LI->getOrdering();
277       LI->setOrdering(AtomicOrdering::Monotonic);
278     } else if (SI && isReleaseOrStronger(SI->getOrdering())) {
279       FenceOrdering = SI->getOrdering();
280       SI->setOrdering(AtomicOrdering::Monotonic);
281     } else if (RMWI && (isReleaseOrStronger(RMWI->getOrdering()) ||
282                         isAcquireOrStronger(RMWI->getOrdering()))) {
283       FenceOrdering = RMWI->getOrdering();
284       RMWI->setOrdering(AtomicOrdering::Monotonic);
285     } else if (CASI &&
286                TLI->shouldExpandAtomicCmpXchgInIR(CASI) ==
287                    TargetLoweringBase::AtomicExpansionKind::None &&
288                (isReleaseOrStronger(CASI->getSuccessOrdering()) ||
289                 isAcquireOrStronger(CASI->getSuccessOrdering()) ||
290                 isAcquireOrStronger(CASI->getFailureOrdering()))) {
291       // If a compare and swap is lowered to LL/SC, we can do smarter fence
292       // insertion, with a stronger one on the success path than on the
293       // failure path. As a result, fence insertion is directly done by
294       // expandAtomicCmpXchg in that case.
295       FenceOrdering = CASI->getMergedOrdering();
296       CASI->setSuccessOrdering(AtomicOrdering::Monotonic);
297       CASI->setFailureOrdering(AtomicOrdering::Monotonic);
298     }
299 
300     if (FenceOrdering != AtomicOrdering::Monotonic) {
301       MadeChange |= bracketInstWithFences(I, FenceOrdering);
302     }
303   } else if (I->hasAtomicStore() &&
304              TLI->shouldInsertTrailingFenceForAtomicStore(I)) {
305     auto FenceOrdering = AtomicOrdering::Monotonic;
306     if (SI)
307       FenceOrdering = SI->getOrdering();
308     else if (RMWI)
309       FenceOrdering = RMWI->getOrdering();
310     else if (CASI && TLI->shouldExpandAtomicCmpXchgInIR(CASI) !=
311                          TargetLoweringBase::AtomicExpansionKind::LLSC)
312       // LLSC is handled in expandAtomicCmpXchg().
313       FenceOrdering = CASI->getSuccessOrdering();
314 
315     IRBuilder Builder(I);
316     if (auto TrailingFence =
317             TLI->emitTrailingFence(Builder, I, FenceOrdering)) {
318       TrailingFence->moveAfter(I);
319       MadeChange = true;
320     }
321   }
322 
323   if (LI)
324     MadeChange |= tryExpandAtomicLoad(LI);
325   else if (SI)
326     MadeChange |= tryExpandAtomicStore(SI);
327   else if (RMWI) {
328     // There are two different ways of expanding RMW instructions:
329     // - into a load if it is idempotent
330     // - into a Cmpxchg/LL-SC loop otherwise
331     // we try them in that order.
332 
333     if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
334       MadeChange = true;
335 
336     } else {
337       MadeChange |= tryExpandAtomicRMW(RMWI);
338     }
339   } else if (CASI)
340     MadeChange |= tryExpandAtomicCmpXchg(CASI);
341 
342   return MadeChange;
343 }
344 
345 bool AtomicExpandImpl::run(Function &F, const TargetMachine *TM) {
346   const auto *Subtarget = TM->getSubtargetImpl(F);
347   if (!Subtarget->enableAtomicExpand())
348     return false;
349   TLI = Subtarget->getTargetLowering();
350   DL = &F.getDataLayout();
351 
352   bool MadeChange = false;
353 
354   for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE;) {
355     BasicBlock *BB = &*BBI;
356     ++BBI;
357 
358     BasicBlock::iterator Next;
359 
360     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;
361          I = Next) {
362       Instruction &Inst = *I;
363       Next = std::next(I);
364 
365       if (processAtomicInstr(&Inst)) {
366         MadeChange = true;
367 
368         // Detect control flow change and resume iteration from the original
369         // block to inspect any newly inserted blocks. This allows incremental
370         // legalization of atomicrmw and cmpxchg.
371         if (Next == E || BB != Next->getParent()) {
372           BBI = BB->getIterator();
373           BBE = F.end();
374           break;
375         }
376       }
377     }
378   }
379 
380   return MadeChange;
381 }
382 
383 bool AtomicExpandLegacy::runOnFunction(Function &F) {
384 
385   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
386   if (!TPC)
387     return false;
388   auto *TM = &TPC->getTM<TargetMachine>();
389   AtomicExpandImpl AE;
390   return AE.run(F, TM);
391 }
392 
393 FunctionPass *llvm::createAtomicExpandLegacyPass() {
394   return new AtomicExpandLegacy();
395 }
396 
397 PreservedAnalyses AtomicExpandPass::run(Function &F,
398                                         FunctionAnalysisManager &AM) {
399   AtomicExpandImpl AE;
400 
401   bool Changed = AE.run(F, TM);
402   if (!Changed)
403     return PreservedAnalyses::all();
404 
405   return PreservedAnalyses::none();
406 }
407 
408 bool AtomicExpandImpl::bracketInstWithFences(Instruction *I,
409                                              AtomicOrdering Order) {
410   ReplacementIRBuilder Builder(I, *DL);
411 
412   auto LeadingFence = TLI->emitLeadingFence(Builder, I, Order);
413 
414   auto TrailingFence = TLI->emitTrailingFence(Builder, I, Order);
415   // We have a guard here because not every atomic operation generates a
416   // trailing fence.
417   if (TrailingFence)
418     TrailingFence->moveAfter(I);
419 
420   return (LeadingFence || TrailingFence);
421 }
422 
423 /// Get the iX type with the same bitwidth as T.
424 IntegerType *
425 AtomicExpandImpl::getCorrespondingIntegerType(Type *T, const DataLayout &DL) {
426   EVT VT = TLI->getMemValueType(DL, T);
427   unsigned BitWidth = VT.getStoreSizeInBits();
428   assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
429   return IntegerType::get(T->getContext(), BitWidth);
430 }
431 
432 /// Convert an atomic load of a non-integral type to an integer load of the
433 /// equivalent bitwidth.  See the function comment on
434 /// convertAtomicStoreToIntegerType for background.
435 LoadInst *AtomicExpandImpl::convertAtomicLoadToIntegerType(LoadInst *LI) {
436   auto *M = LI->getModule();
437   Type *NewTy = getCorrespondingIntegerType(LI->getType(), M->getDataLayout());
438 
439   ReplacementIRBuilder Builder(LI, *DL);
440 
441   Value *Addr = LI->getPointerOperand();
442 
443   auto *NewLI = Builder.CreateLoad(NewTy, Addr);
444   NewLI->setAlignment(LI->getAlign());
445   NewLI->setVolatile(LI->isVolatile());
446   NewLI->setAtomic(LI->getOrdering(), LI->getSyncScopeID());
447   LLVM_DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
448 
449   Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
450   LI->replaceAllUsesWith(NewVal);
451   LI->eraseFromParent();
452   return NewLI;
453 }
454 
455 AtomicRMWInst *
456 AtomicExpandImpl::convertAtomicXchgToIntegerType(AtomicRMWInst *RMWI) {
457   assert(RMWI->getOperation() == AtomicRMWInst::Xchg);
458 
459   auto *M = RMWI->getModule();
460   Type *NewTy =
461       getCorrespondingIntegerType(RMWI->getType(), M->getDataLayout());
462 
463   ReplacementIRBuilder Builder(RMWI, *DL);
464 
465   Value *Addr = RMWI->getPointerOperand();
466   Value *Val = RMWI->getValOperand();
467   Value *NewVal = Val->getType()->isPointerTy()
468                       ? Builder.CreatePtrToInt(Val, NewTy)
469                       : Builder.CreateBitCast(Val, NewTy);
470 
471   auto *NewRMWI = Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, Addr, NewVal,
472                                           RMWI->getAlign(), RMWI->getOrdering(),
473                                           RMWI->getSyncScopeID());
474   NewRMWI->setVolatile(RMWI->isVolatile());
475   LLVM_DEBUG(dbgs() << "Replaced " << *RMWI << " with " << *NewRMWI << "\n");
476 
477   Value *NewRVal = RMWI->getType()->isPointerTy()
478                        ? Builder.CreateIntToPtr(NewRMWI, RMWI->getType())
479                        : Builder.CreateBitCast(NewRMWI, RMWI->getType());
480   RMWI->replaceAllUsesWith(NewRVal);
481   RMWI->eraseFromParent();
482   return NewRMWI;
483 }
484 
485 bool AtomicExpandImpl::tryExpandAtomicLoad(LoadInst *LI) {
486   switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
487   case TargetLoweringBase::AtomicExpansionKind::None:
488     return false;
489   case TargetLoweringBase::AtomicExpansionKind::LLSC:
490     expandAtomicOpToLLSC(
491         LI, LI->getType(), LI->getPointerOperand(), LI->getAlign(),
492         LI->getOrdering(),
493         [](IRBuilderBase &Builder, Value *Loaded) { return Loaded; });
494     return true;
495   case TargetLoweringBase::AtomicExpansionKind::LLOnly:
496     return expandAtomicLoadToLL(LI);
497   case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
498     return expandAtomicLoadToCmpXchg(LI);
499   case TargetLoweringBase::AtomicExpansionKind::NotAtomic:
500     LI->setAtomic(AtomicOrdering::NotAtomic);
501     return true;
502   default:
503     llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
504   }
505 }
506 
507 bool AtomicExpandImpl::tryExpandAtomicStore(StoreInst *SI) {
508   switch (TLI->shouldExpandAtomicStoreInIR(SI)) {
509   case TargetLoweringBase::AtomicExpansionKind::None:
510     return false;
511   case TargetLoweringBase::AtomicExpansionKind::Expand:
512     expandAtomicStore(SI);
513     return true;
514   case TargetLoweringBase::AtomicExpansionKind::NotAtomic:
515     SI->setAtomic(AtomicOrdering::NotAtomic);
516     return true;
517   default:
518     llvm_unreachable("Unhandled case in tryExpandAtomicStore");
519   }
520 }
521 
522 bool AtomicExpandImpl::expandAtomicLoadToLL(LoadInst *LI) {
523   ReplacementIRBuilder Builder(LI, *DL);
524 
525   // On some architectures, load-linked instructions are atomic for larger
526   // sizes than normal loads. For example, the only 64-bit load guaranteed
527   // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
528   Value *Val = TLI->emitLoadLinked(Builder, LI->getType(),
529                                    LI->getPointerOperand(), LI->getOrdering());
530   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
531 
532   LI->replaceAllUsesWith(Val);
533   LI->eraseFromParent();
534 
535   return true;
536 }
537 
538 bool AtomicExpandImpl::expandAtomicLoadToCmpXchg(LoadInst *LI) {
539   ReplacementIRBuilder Builder(LI, *DL);
540   AtomicOrdering Order = LI->getOrdering();
541   if (Order == AtomicOrdering::Unordered)
542     Order = AtomicOrdering::Monotonic;
543 
544   Value *Addr = LI->getPointerOperand();
545   Type *Ty = LI->getType();
546   Constant *DummyVal = Constant::getNullValue(Ty);
547 
548   Value *Pair = Builder.CreateAtomicCmpXchg(
549       Addr, DummyVal, DummyVal, LI->getAlign(), Order,
550       AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
551   Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
552 
553   LI->replaceAllUsesWith(Loaded);
554   LI->eraseFromParent();
555 
556   return true;
557 }
558 
559 /// Convert an atomic store of a non-integral type to an integer store of the
560 /// equivalent bitwidth.  We used to not support floating point or vector
561 /// atomics in the IR at all.  The backends learned to deal with the bitcast
562 /// idiom because that was the only way of expressing the notion of a atomic
563 /// float or vector store.  The long term plan is to teach each backend to
564 /// instruction select from the original atomic store, but as a migration
565 /// mechanism, we convert back to the old format which the backends understand.
566 /// Each backend will need individual work to recognize the new format.
567 StoreInst *AtomicExpandImpl::convertAtomicStoreToIntegerType(StoreInst *SI) {
568   ReplacementIRBuilder Builder(SI, *DL);
569   auto *M = SI->getModule();
570   Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
571                                             M->getDataLayout());
572   Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
573 
574   Value *Addr = SI->getPointerOperand();
575 
576   StoreInst *NewSI = Builder.CreateStore(NewVal, Addr);
577   NewSI->setAlignment(SI->getAlign());
578   NewSI->setVolatile(SI->isVolatile());
579   NewSI->setAtomic(SI->getOrdering(), SI->getSyncScopeID());
580   LLVM_DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
581   SI->eraseFromParent();
582   return NewSI;
583 }
584 
585 void AtomicExpandImpl::expandAtomicStore(StoreInst *SI) {
586   // This function is only called on atomic stores that are too large to be
587   // atomic if implemented as a native store. So we replace them by an
588   // atomic swap, that can be implemented for example as a ldrex/strex on ARM
589   // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
590   // It is the responsibility of the target to only signal expansion via
591   // shouldExpandAtomicRMW in cases where this is required and possible.
592   ReplacementIRBuilder Builder(SI, *DL);
593   AtomicOrdering Ordering = SI->getOrdering();
594   assert(Ordering != AtomicOrdering::NotAtomic);
595   AtomicOrdering RMWOrdering = Ordering == AtomicOrdering::Unordered
596                                    ? AtomicOrdering::Monotonic
597                                    : Ordering;
598   AtomicRMWInst *AI = Builder.CreateAtomicRMW(
599       AtomicRMWInst::Xchg, SI->getPointerOperand(), SI->getValueOperand(),
600       SI->getAlign(), RMWOrdering);
601   SI->eraseFromParent();
602 
603   // Now we have an appropriate swap instruction, lower it as usual.
604   tryExpandAtomicRMW(AI);
605 }
606 
607 static void createCmpXchgInstFun(IRBuilderBase &Builder, Value *Addr,
608                                  Value *Loaded, Value *NewVal, Align AddrAlign,
609                                  AtomicOrdering MemOpOrder, SyncScope::ID SSID,
610                                  Value *&Success, Value *&NewLoaded) {
611   Type *OrigTy = NewVal->getType();
612 
613   // This code can go away when cmpxchg supports FP and vector types.
614   assert(!OrigTy->isPointerTy());
615   bool NeedBitcast = OrigTy->isFloatingPointTy() || OrigTy->isVectorTy();
616   if (NeedBitcast) {
617     IntegerType *IntTy = Builder.getIntNTy(OrigTy->getPrimitiveSizeInBits());
618     NewVal = Builder.CreateBitCast(NewVal, IntTy);
619     Loaded = Builder.CreateBitCast(Loaded, IntTy);
620   }
621 
622   Value *Pair = Builder.CreateAtomicCmpXchg(
623       Addr, Loaded, NewVal, AddrAlign, MemOpOrder,
624       AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
625   Success = Builder.CreateExtractValue(Pair, 1, "success");
626   NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
627 
628   if (NeedBitcast)
629     NewLoaded = Builder.CreateBitCast(NewLoaded, OrigTy);
630 }
631 
632 bool AtomicExpandImpl::tryExpandAtomicRMW(AtomicRMWInst *AI) {
633   LLVMContext &Ctx = AI->getModule()->getContext();
634   TargetLowering::AtomicExpansionKind Kind = TLI->shouldExpandAtomicRMWInIR(AI);
635   switch (Kind) {
636   case TargetLoweringBase::AtomicExpansionKind::None:
637     return false;
638   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
639     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
640     unsigned ValueSize = getAtomicOpSize(AI);
641     if (ValueSize < MinCASSize) {
642       expandPartwordAtomicRMW(AI,
643                               TargetLoweringBase::AtomicExpansionKind::LLSC);
644     } else {
645       auto PerformOp = [&](IRBuilderBase &Builder, Value *Loaded) {
646         return buildAtomicRMWValue(AI->getOperation(), Builder, Loaded,
647                                    AI->getValOperand());
648       };
649       expandAtomicOpToLLSC(AI, AI->getType(), AI->getPointerOperand(),
650                            AI->getAlign(), AI->getOrdering(), PerformOp);
651     }
652     return true;
653   }
654   case TargetLoweringBase::AtomicExpansionKind::CmpXChg: {
655     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
656     unsigned ValueSize = getAtomicOpSize(AI);
657     if (ValueSize < MinCASSize) {
658       expandPartwordAtomicRMW(AI,
659                               TargetLoweringBase::AtomicExpansionKind::CmpXChg);
660     } else {
661       SmallVector<StringRef> SSNs;
662       Ctx.getSyncScopeNames(SSNs);
663       auto MemScope = SSNs[AI->getSyncScopeID()].empty()
664                           ? "system"
665                           : SSNs[AI->getSyncScopeID()];
666       OptimizationRemarkEmitter ORE(AI->getFunction());
667       ORE.emit([&]() {
668         return OptimizationRemark(DEBUG_TYPE, "Passed", AI)
669                << "A compare and swap loop was generated for an atomic "
670                << AI->getOperationName(AI->getOperation()) << " operation at "
671                << MemScope << " memory scope";
672       });
673       expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
674     }
675     return true;
676   }
677   case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic: {
678     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
679     unsigned ValueSize = getAtomicOpSize(AI);
680     if (ValueSize < MinCASSize) {
681       AtomicRMWInst::BinOp Op = AI->getOperation();
682       // Widen And/Or/Xor and give the target another chance at expanding it.
683       if (Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
684           Op == AtomicRMWInst::And) {
685         tryExpandAtomicRMW(widenPartwordAtomicRMW(AI));
686         return true;
687       }
688     }
689     expandAtomicRMWToMaskedIntrinsic(AI);
690     return true;
691   }
692   case TargetLoweringBase::AtomicExpansionKind::BitTestIntrinsic: {
693     TLI->emitBitTestAtomicRMWIntrinsic(AI);
694     return true;
695   }
696   case TargetLoweringBase::AtomicExpansionKind::CmpArithIntrinsic: {
697     TLI->emitCmpArithAtomicRMWIntrinsic(AI);
698     return true;
699   }
700   case TargetLoweringBase::AtomicExpansionKind::NotAtomic:
701     return lowerAtomicRMWInst(AI);
702   case TargetLoweringBase::AtomicExpansionKind::Expand:
703     TLI->emitExpandAtomicRMW(AI);
704     return true;
705   default:
706     llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
707   }
708 }
709 
710 namespace {
711 
712 struct PartwordMaskValues {
713   // These three fields are guaranteed to be set by createMaskInstrs.
714   Type *WordType = nullptr;
715   Type *ValueType = nullptr;
716   Type *IntValueType = nullptr;
717   Value *AlignedAddr = nullptr;
718   Align AlignedAddrAlignment;
719   // The remaining fields can be null.
720   Value *ShiftAmt = nullptr;
721   Value *Mask = nullptr;
722   Value *Inv_Mask = nullptr;
723 };
724 
725 LLVM_ATTRIBUTE_UNUSED
726 raw_ostream &operator<<(raw_ostream &O, const PartwordMaskValues &PMV) {
727   auto PrintObj = [&O](auto *V) {
728     if (V)
729       O << *V;
730     else
731       O << "nullptr";
732     O << '\n';
733   };
734   O << "PartwordMaskValues {\n";
735   O << "  WordType: ";
736   PrintObj(PMV.WordType);
737   O << "  ValueType: ";
738   PrintObj(PMV.ValueType);
739   O << "  AlignedAddr: ";
740   PrintObj(PMV.AlignedAddr);
741   O << "  AlignedAddrAlignment: " << PMV.AlignedAddrAlignment.value() << '\n';
742   O << "  ShiftAmt: ";
743   PrintObj(PMV.ShiftAmt);
744   O << "  Mask: ";
745   PrintObj(PMV.Mask);
746   O << "  Inv_Mask: ";
747   PrintObj(PMV.Inv_Mask);
748   O << "}\n";
749   return O;
750 }
751 
752 } // end anonymous namespace
753 
754 /// This is a helper function which builds instructions to provide
755 /// values necessary for partword atomic operations. It takes an
756 /// incoming address, Addr, and ValueType, and constructs the address,
757 /// shift-amounts and masks needed to work with a larger value of size
758 /// WordSize.
759 ///
760 /// AlignedAddr: Addr rounded down to a multiple of WordSize
761 ///
762 /// ShiftAmt: Number of bits to right-shift a WordSize value loaded
763 ///           from AlignAddr for it to have the same value as if
764 ///           ValueType was loaded from Addr.
765 ///
766 /// Mask: Value to mask with the value loaded from AlignAddr to
767 ///       include only the part that would've been loaded from Addr.
768 ///
769 /// Inv_Mask: The inverse of Mask.
770 static PartwordMaskValues createMaskInstrs(IRBuilderBase &Builder,
771                                            Instruction *I, Type *ValueType,
772                                            Value *Addr, Align AddrAlign,
773                                            unsigned MinWordSize) {
774   PartwordMaskValues PMV;
775 
776   Module *M = I->getModule();
777   LLVMContext &Ctx = M->getContext();
778   const DataLayout &DL = M->getDataLayout();
779   unsigned ValueSize = DL.getTypeStoreSize(ValueType);
780 
781   PMV.ValueType = PMV.IntValueType = ValueType;
782   if (PMV.ValueType->isFloatingPointTy() || PMV.ValueType->isVectorTy())
783     PMV.IntValueType =
784         Type::getIntNTy(Ctx, ValueType->getPrimitiveSizeInBits());
785 
786   PMV.WordType = MinWordSize > ValueSize ? Type::getIntNTy(Ctx, MinWordSize * 8)
787                                          : ValueType;
788   if (PMV.ValueType == PMV.WordType) {
789     PMV.AlignedAddr = Addr;
790     PMV.AlignedAddrAlignment = AddrAlign;
791     PMV.ShiftAmt = ConstantInt::get(PMV.ValueType, 0);
792     PMV.Mask = ConstantInt::get(PMV.ValueType, ~0, /*isSigned*/ true);
793     return PMV;
794   }
795 
796   PMV.AlignedAddrAlignment = Align(MinWordSize);
797 
798   assert(ValueSize < MinWordSize);
799 
800   PointerType *PtrTy = cast<PointerType>(Addr->getType());
801   IntegerType *IntTy = DL.getIndexType(Ctx, PtrTy->getAddressSpace());
802   Value *PtrLSB;
803 
804   if (AddrAlign < MinWordSize) {
805     PMV.AlignedAddr = Builder.CreateIntrinsic(
806         Intrinsic::ptrmask, {PtrTy, IntTy},
807         {Addr, ConstantInt::get(IntTy, ~(uint64_t)(MinWordSize - 1))}, nullptr,
808         "AlignedAddr");
809 
810     Value *AddrInt = Builder.CreatePtrToInt(Addr, IntTy);
811     PtrLSB = Builder.CreateAnd(AddrInt, MinWordSize - 1, "PtrLSB");
812   } else {
813     // If the alignment is high enough, the LSB are known 0.
814     PMV.AlignedAddr = Addr;
815     PtrLSB = ConstantInt::getNullValue(IntTy);
816   }
817 
818   if (DL.isLittleEndian()) {
819     // turn bytes into bits
820     PMV.ShiftAmt = Builder.CreateShl(PtrLSB, 3);
821   } else {
822     // turn bytes into bits, and count from the other side.
823     PMV.ShiftAmt = Builder.CreateShl(
824         Builder.CreateXor(PtrLSB, MinWordSize - ValueSize), 3);
825   }
826 
827   PMV.ShiftAmt = Builder.CreateTrunc(PMV.ShiftAmt, PMV.WordType, "ShiftAmt");
828   PMV.Mask = Builder.CreateShl(
829       ConstantInt::get(PMV.WordType, (1 << (ValueSize * 8)) - 1), PMV.ShiftAmt,
830       "Mask");
831 
832   PMV.Inv_Mask = Builder.CreateNot(PMV.Mask, "Inv_Mask");
833 
834   return PMV;
835 }
836 
837 static Value *extractMaskedValue(IRBuilderBase &Builder, Value *WideWord,
838                                  const PartwordMaskValues &PMV) {
839   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
840   if (PMV.WordType == PMV.ValueType)
841     return WideWord;
842 
843   Value *Shift = Builder.CreateLShr(WideWord, PMV.ShiftAmt, "shifted");
844   Value *Trunc = Builder.CreateTrunc(Shift, PMV.IntValueType, "extracted");
845   return Builder.CreateBitCast(Trunc, PMV.ValueType);
846 }
847 
848 static Value *insertMaskedValue(IRBuilderBase &Builder, Value *WideWord,
849                                 Value *Updated, const PartwordMaskValues &PMV) {
850   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
851   assert(Updated->getType() == PMV.ValueType && "Value type mismatch");
852   if (PMV.WordType == PMV.ValueType)
853     return Updated;
854 
855   Updated = Builder.CreateBitCast(Updated, PMV.IntValueType);
856 
857   Value *ZExt = Builder.CreateZExt(Updated, PMV.WordType, "extended");
858   Value *Shift =
859       Builder.CreateShl(ZExt, PMV.ShiftAmt, "shifted", /*HasNUW*/ true);
860   Value *And = Builder.CreateAnd(WideWord, PMV.Inv_Mask, "unmasked");
861   Value *Or = Builder.CreateOr(And, Shift, "inserted");
862   return Or;
863 }
864 
865 /// Emit IR to implement a masked version of a given atomicrmw
866 /// operation. (That is, only the bits under the Mask should be
867 /// affected by the operation)
868 static Value *performMaskedAtomicOp(AtomicRMWInst::BinOp Op,
869                                     IRBuilderBase &Builder, Value *Loaded,
870                                     Value *Shifted_Inc, Value *Inc,
871                                     const PartwordMaskValues &PMV) {
872   // TODO: update to use
873   // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge in order
874   // to merge bits from two values without requiring PMV.Inv_Mask.
875   switch (Op) {
876   case AtomicRMWInst::Xchg: {
877     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
878     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, Shifted_Inc);
879     return FinalVal;
880   }
881   case AtomicRMWInst::Or:
882   case AtomicRMWInst::Xor:
883   case AtomicRMWInst::And:
884     llvm_unreachable("Or/Xor/And handled by widenPartwordAtomicRMW");
885   case AtomicRMWInst::Add:
886   case AtomicRMWInst::Sub:
887   case AtomicRMWInst::Nand: {
888     // The other arithmetic ops need to be masked into place.
889     Value *NewVal = buildAtomicRMWValue(Op, Builder, Loaded, Shifted_Inc);
890     Value *NewVal_Masked = Builder.CreateAnd(NewVal, PMV.Mask);
891     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
892     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Masked);
893     return FinalVal;
894   }
895   case AtomicRMWInst::Max:
896   case AtomicRMWInst::Min:
897   case AtomicRMWInst::UMax:
898   case AtomicRMWInst::UMin:
899   case AtomicRMWInst::FAdd:
900   case AtomicRMWInst::FSub:
901   case AtomicRMWInst::FMin:
902   case AtomicRMWInst::FMax:
903   case AtomicRMWInst::UIncWrap:
904   case AtomicRMWInst::UDecWrap: {
905     // Finally, other ops will operate on the full value, so truncate down to
906     // the original size, and expand out again after doing the
907     // operation. Bitcasts will be inserted for FP values.
908     Value *Loaded_Extract = extractMaskedValue(Builder, Loaded, PMV);
909     Value *NewVal = buildAtomicRMWValue(Op, Builder, Loaded_Extract, Inc);
910     Value *FinalVal = insertMaskedValue(Builder, Loaded, NewVal, PMV);
911     return FinalVal;
912   }
913   default:
914     llvm_unreachable("Unknown atomic op");
915   }
916 }
917 
918 /// Expand a sub-word atomicrmw operation into an appropriate
919 /// word-sized operation.
920 ///
921 /// It will create an LL/SC or cmpxchg loop, as appropriate, the same
922 /// way as a typical atomicrmw expansion. The only difference here is
923 /// that the operation inside of the loop may operate upon only a
924 /// part of the value.
925 void AtomicExpandImpl::expandPartwordAtomicRMW(
926     AtomicRMWInst *AI, TargetLoweringBase::AtomicExpansionKind ExpansionKind) {
927   // Widen And/Or/Xor and give the target another chance at expanding it.
928   AtomicRMWInst::BinOp Op = AI->getOperation();
929   if (Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
930       Op == AtomicRMWInst::And) {
931     tryExpandAtomicRMW(widenPartwordAtomicRMW(AI));
932     return;
933   }
934   AtomicOrdering MemOpOrder = AI->getOrdering();
935   SyncScope::ID SSID = AI->getSyncScopeID();
936 
937   ReplacementIRBuilder Builder(AI, *DL);
938 
939   PartwordMaskValues PMV =
940       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
941                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
942 
943   Value *ValOperand_Shifted = nullptr;
944   if (Op == AtomicRMWInst::Xchg || Op == AtomicRMWInst::Add ||
945       Op == AtomicRMWInst::Sub || Op == AtomicRMWInst::Nand) {
946     Value *ValOp = Builder.CreateBitCast(AI->getValOperand(), PMV.IntValueType);
947     ValOperand_Shifted =
948         Builder.CreateShl(Builder.CreateZExt(ValOp, PMV.WordType), PMV.ShiftAmt,
949                           "ValOperand_Shifted");
950   }
951 
952   auto PerformPartwordOp = [&](IRBuilderBase &Builder, Value *Loaded) {
953     return performMaskedAtomicOp(Op, Builder, Loaded, ValOperand_Shifted,
954                                  AI->getValOperand(), PMV);
955   };
956 
957   Value *OldResult;
958   if (ExpansionKind == TargetLoweringBase::AtomicExpansionKind::CmpXChg) {
959     OldResult = insertRMWCmpXchgLoop(Builder, PMV.WordType, PMV.AlignedAddr,
960                                      PMV.AlignedAddrAlignment, MemOpOrder, SSID,
961                                      PerformPartwordOp, createCmpXchgInstFun);
962   } else {
963     assert(ExpansionKind == TargetLoweringBase::AtomicExpansionKind::LLSC);
964     OldResult = insertRMWLLSCLoop(Builder, PMV.WordType, PMV.AlignedAddr,
965                                   PMV.AlignedAddrAlignment, MemOpOrder,
966                                   PerformPartwordOp);
967   }
968 
969   Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
970   AI->replaceAllUsesWith(FinalOldResult);
971   AI->eraseFromParent();
972 }
973 
974 /// Copy metadata that's safe to preserve when widening atomics.
975 static void copyMetadataForAtomic(Instruction &Dest,
976                                   const Instruction &Source) {
977   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
978   Source.getAllMetadata(MD);
979   LLVMContext &Ctx = Dest.getContext();
980   MDBuilder MDB(Ctx);
981 
982   for (auto [ID, N] : MD) {
983     switch (ID) {
984     case LLVMContext::MD_dbg:
985     case LLVMContext::MD_tbaa:
986     case LLVMContext::MD_tbaa_struct:
987     case LLVMContext::MD_alias_scope:
988     case LLVMContext::MD_noalias:
989     case LLVMContext::MD_access_group:
990     case LLVMContext::MD_mmra:
991       Dest.setMetadata(ID, N);
992       break;
993     default:
994       if (ID == Ctx.getMDKindID("amdgpu.no.remote.memory"))
995         Dest.setMetadata(ID, N);
996       else if (ID == Ctx.getMDKindID("amdgpu.no.fine.grained.memory"))
997         Dest.setMetadata(ID, N);
998 
999       break;
1000     }
1001   }
1002 }
1003 
1004 // Widen the bitwise atomicrmw (or/xor/and) to the minimum supported width.
1005 AtomicRMWInst *AtomicExpandImpl::widenPartwordAtomicRMW(AtomicRMWInst *AI) {
1006   ReplacementIRBuilder Builder(AI, *DL);
1007   AtomicRMWInst::BinOp Op = AI->getOperation();
1008 
1009   assert((Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
1010           Op == AtomicRMWInst::And) &&
1011          "Unable to widen operation");
1012 
1013   PartwordMaskValues PMV =
1014       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
1015                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1016 
1017   Value *ValOperand_Shifted =
1018       Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
1019                         PMV.ShiftAmt, "ValOperand_Shifted");
1020 
1021   Value *NewOperand;
1022 
1023   if (Op == AtomicRMWInst::And)
1024     NewOperand =
1025         Builder.CreateOr(ValOperand_Shifted, PMV.Inv_Mask, "AndOperand");
1026   else
1027     NewOperand = ValOperand_Shifted;
1028 
1029   AtomicRMWInst *NewAI = Builder.CreateAtomicRMW(
1030       Op, PMV.AlignedAddr, NewOperand, PMV.AlignedAddrAlignment,
1031       AI->getOrdering(), AI->getSyncScopeID());
1032 
1033   copyMetadataForAtomic(*NewAI, *AI);
1034 
1035   Value *FinalOldResult = extractMaskedValue(Builder, NewAI, PMV);
1036   AI->replaceAllUsesWith(FinalOldResult);
1037   AI->eraseFromParent();
1038   return NewAI;
1039 }
1040 
1041 bool AtomicExpandImpl::expandPartwordCmpXchg(AtomicCmpXchgInst *CI) {
1042   // The basic idea here is that we're expanding a cmpxchg of a
1043   // smaller memory size up to a word-sized cmpxchg. To do this, we
1044   // need to add a retry-loop for strong cmpxchg, so that
1045   // modifications to other parts of the word don't cause a spurious
1046   // failure.
1047 
1048   // This generates code like the following:
1049   //     [[Setup mask values PMV.*]]
1050   //     %NewVal_Shifted = shl i32 %NewVal, %PMV.ShiftAmt
1051   //     %Cmp_Shifted = shl i32 %Cmp, %PMV.ShiftAmt
1052   //     %InitLoaded = load i32* %addr
1053   //     %InitLoaded_MaskOut = and i32 %InitLoaded, %PMV.Inv_Mask
1054   //     br partword.cmpxchg.loop
1055   // partword.cmpxchg.loop:
1056   //     %Loaded_MaskOut = phi i32 [ %InitLoaded_MaskOut, %entry ],
1057   //        [ %OldVal_MaskOut, %partword.cmpxchg.failure ]
1058   //     %FullWord_NewVal = or i32 %Loaded_MaskOut, %NewVal_Shifted
1059   //     %FullWord_Cmp = or i32 %Loaded_MaskOut, %Cmp_Shifted
1060   //     %NewCI = cmpxchg i32* %PMV.AlignedAddr, i32 %FullWord_Cmp,
1061   //        i32 %FullWord_NewVal success_ordering failure_ordering
1062   //     %OldVal = extractvalue { i32, i1 } %NewCI, 0
1063   //     %Success = extractvalue { i32, i1 } %NewCI, 1
1064   //     br i1 %Success, label %partword.cmpxchg.end,
1065   //        label %partword.cmpxchg.failure
1066   // partword.cmpxchg.failure:
1067   //     %OldVal_MaskOut = and i32 %OldVal, %PMV.Inv_Mask
1068   //     %ShouldContinue = icmp ne i32 %Loaded_MaskOut, %OldVal_MaskOut
1069   //     br i1 %ShouldContinue, label %partword.cmpxchg.loop,
1070   //         label %partword.cmpxchg.end
1071   // partword.cmpxchg.end:
1072   //    %tmp1 = lshr i32 %OldVal, %PMV.ShiftAmt
1073   //    %FinalOldVal = trunc i32 %tmp1 to i8
1074   //    %tmp2 = insertvalue { i8, i1 } undef, i8 %FinalOldVal, 0
1075   //    %Res = insertvalue { i8, i1 } %25, i1 %Success, 1
1076 
1077   Value *Addr = CI->getPointerOperand();
1078   Value *Cmp = CI->getCompareOperand();
1079   Value *NewVal = CI->getNewValOperand();
1080 
1081   BasicBlock *BB = CI->getParent();
1082   Function *F = BB->getParent();
1083   ReplacementIRBuilder Builder(CI, *DL);
1084   LLVMContext &Ctx = Builder.getContext();
1085 
1086   BasicBlock *EndBB =
1087       BB->splitBasicBlock(CI->getIterator(), "partword.cmpxchg.end");
1088   auto FailureBB =
1089       BasicBlock::Create(Ctx, "partword.cmpxchg.failure", F, EndBB);
1090   auto LoopBB = BasicBlock::Create(Ctx, "partword.cmpxchg.loop", F, FailureBB);
1091 
1092   // The split call above "helpfully" added a branch at the end of BB
1093   // (to the wrong place).
1094   std::prev(BB->end())->eraseFromParent();
1095   Builder.SetInsertPoint(BB);
1096 
1097   PartwordMaskValues PMV =
1098       createMaskInstrs(Builder, CI, CI->getCompareOperand()->getType(), Addr,
1099                        CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1100 
1101   // Shift the incoming values over, into the right location in the word.
1102   Value *NewVal_Shifted =
1103       Builder.CreateShl(Builder.CreateZExt(NewVal, PMV.WordType), PMV.ShiftAmt);
1104   Value *Cmp_Shifted =
1105       Builder.CreateShl(Builder.CreateZExt(Cmp, PMV.WordType), PMV.ShiftAmt);
1106 
1107   // Load the entire current word, and mask into place the expected and new
1108   // values
1109   LoadInst *InitLoaded = Builder.CreateLoad(PMV.WordType, PMV.AlignedAddr);
1110   InitLoaded->setVolatile(CI->isVolatile());
1111   Value *InitLoaded_MaskOut = Builder.CreateAnd(InitLoaded, PMV.Inv_Mask);
1112   Builder.CreateBr(LoopBB);
1113 
1114   // partword.cmpxchg.loop:
1115   Builder.SetInsertPoint(LoopBB);
1116   PHINode *Loaded_MaskOut = Builder.CreatePHI(PMV.WordType, 2);
1117   Loaded_MaskOut->addIncoming(InitLoaded_MaskOut, BB);
1118 
1119   // Mask/Or the expected and new values into place in the loaded word.
1120   Value *FullWord_NewVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Shifted);
1121   Value *FullWord_Cmp = Builder.CreateOr(Loaded_MaskOut, Cmp_Shifted);
1122   AtomicCmpXchgInst *NewCI = Builder.CreateAtomicCmpXchg(
1123       PMV.AlignedAddr, FullWord_Cmp, FullWord_NewVal, PMV.AlignedAddrAlignment,
1124       CI->getSuccessOrdering(), CI->getFailureOrdering(), CI->getSyncScopeID());
1125   NewCI->setVolatile(CI->isVolatile());
1126   // When we're building a strong cmpxchg, we need a loop, so you
1127   // might think we could use a weak cmpxchg inside. But, using strong
1128   // allows the below comparison for ShouldContinue, and we're
1129   // expecting the underlying cmpxchg to be a machine instruction,
1130   // which is strong anyways.
1131   NewCI->setWeak(CI->isWeak());
1132 
1133   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
1134   Value *Success = Builder.CreateExtractValue(NewCI, 1);
1135 
1136   if (CI->isWeak())
1137     Builder.CreateBr(EndBB);
1138   else
1139     Builder.CreateCondBr(Success, EndBB, FailureBB);
1140 
1141   // partword.cmpxchg.failure:
1142   Builder.SetInsertPoint(FailureBB);
1143   // Upon failure, verify that the masked-out part of the loaded value
1144   // has been modified.  If it didn't, abort the cmpxchg, since the
1145   // masked-in part must've.
1146   Value *OldVal_MaskOut = Builder.CreateAnd(OldVal, PMV.Inv_Mask);
1147   Value *ShouldContinue = Builder.CreateICmpNE(Loaded_MaskOut, OldVal_MaskOut);
1148   Builder.CreateCondBr(ShouldContinue, LoopBB, EndBB);
1149 
1150   // Add the second value to the phi from above
1151   Loaded_MaskOut->addIncoming(OldVal_MaskOut, FailureBB);
1152 
1153   // partword.cmpxchg.end:
1154   Builder.SetInsertPoint(CI);
1155 
1156   Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
1157   Value *Res = PoisonValue::get(CI->getType());
1158   Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
1159   Res = Builder.CreateInsertValue(Res, Success, 1);
1160 
1161   CI->replaceAllUsesWith(Res);
1162   CI->eraseFromParent();
1163   return true;
1164 }
1165 
1166 void AtomicExpandImpl::expandAtomicOpToLLSC(
1167     Instruction *I, Type *ResultType, Value *Addr, Align AddrAlign,
1168     AtomicOrdering MemOpOrder,
1169     function_ref<Value *(IRBuilderBase &, Value *)> PerformOp) {
1170   ReplacementIRBuilder Builder(I, *DL);
1171   Value *Loaded = insertRMWLLSCLoop(Builder, ResultType, Addr, AddrAlign,
1172                                     MemOpOrder, PerformOp);
1173 
1174   I->replaceAllUsesWith(Loaded);
1175   I->eraseFromParent();
1176 }
1177 
1178 void AtomicExpandImpl::expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI) {
1179   ReplacementIRBuilder Builder(AI, *DL);
1180 
1181   PartwordMaskValues PMV =
1182       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
1183                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1184 
1185   // The value operand must be sign-extended for signed min/max so that the
1186   // target's signed comparison instructions can be used. Otherwise, just
1187   // zero-ext.
1188   Instruction::CastOps CastOp = Instruction::ZExt;
1189   AtomicRMWInst::BinOp RMWOp = AI->getOperation();
1190   if (RMWOp == AtomicRMWInst::Max || RMWOp == AtomicRMWInst::Min)
1191     CastOp = Instruction::SExt;
1192 
1193   Value *ValOperand_Shifted = Builder.CreateShl(
1194       Builder.CreateCast(CastOp, AI->getValOperand(), PMV.WordType),
1195       PMV.ShiftAmt, "ValOperand_Shifted");
1196   Value *OldResult = TLI->emitMaskedAtomicRMWIntrinsic(
1197       Builder, AI, PMV.AlignedAddr, ValOperand_Shifted, PMV.Mask, PMV.ShiftAmt,
1198       AI->getOrdering());
1199   Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
1200   AI->replaceAllUsesWith(FinalOldResult);
1201   AI->eraseFromParent();
1202 }
1203 
1204 void AtomicExpandImpl::expandAtomicCmpXchgToMaskedIntrinsic(
1205     AtomicCmpXchgInst *CI) {
1206   ReplacementIRBuilder Builder(CI, *DL);
1207 
1208   PartwordMaskValues PMV = createMaskInstrs(
1209       Builder, CI, CI->getCompareOperand()->getType(), CI->getPointerOperand(),
1210       CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1211 
1212   Value *CmpVal_Shifted = Builder.CreateShl(
1213       Builder.CreateZExt(CI->getCompareOperand(), PMV.WordType), PMV.ShiftAmt,
1214       "CmpVal_Shifted");
1215   Value *NewVal_Shifted = Builder.CreateShl(
1216       Builder.CreateZExt(CI->getNewValOperand(), PMV.WordType), PMV.ShiftAmt,
1217       "NewVal_Shifted");
1218   Value *OldVal = TLI->emitMaskedAtomicCmpXchgIntrinsic(
1219       Builder, CI, PMV.AlignedAddr, CmpVal_Shifted, NewVal_Shifted, PMV.Mask,
1220       CI->getMergedOrdering());
1221   Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
1222   Value *Res = PoisonValue::get(CI->getType());
1223   Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
1224   Value *Success = Builder.CreateICmpEQ(
1225       CmpVal_Shifted, Builder.CreateAnd(OldVal, PMV.Mask), "Success");
1226   Res = Builder.CreateInsertValue(Res, Success, 1);
1227 
1228   CI->replaceAllUsesWith(Res);
1229   CI->eraseFromParent();
1230 }
1231 
1232 Value *AtomicExpandImpl::insertRMWLLSCLoop(
1233     IRBuilderBase &Builder, Type *ResultTy, Value *Addr, Align AddrAlign,
1234     AtomicOrdering MemOpOrder,
1235     function_ref<Value *(IRBuilderBase &, Value *)> PerformOp) {
1236   LLVMContext &Ctx = Builder.getContext();
1237   BasicBlock *BB = Builder.GetInsertBlock();
1238   Function *F = BB->getParent();
1239 
1240   assert(AddrAlign >=
1241              F->getDataLayout().getTypeStoreSize(ResultTy) &&
1242          "Expected at least natural alignment at this point.");
1243 
1244   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1245   //
1246   // The standard expansion we produce is:
1247   //     [...]
1248   // atomicrmw.start:
1249   //     %loaded = @load.linked(%addr)
1250   //     %new = some_op iN %loaded, %incr
1251   //     %stored = @store_conditional(%new, %addr)
1252   //     %try_again = icmp i32 ne %stored, 0
1253   //     br i1 %try_again, label %loop, label %atomicrmw.end
1254   // atomicrmw.end:
1255   //     [...]
1256   BasicBlock *ExitBB =
1257       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
1258   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1259 
1260   // The split call above "helpfully" added a branch at the end of BB (to the
1261   // wrong place).
1262   std::prev(BB->end())->eraseFromParent();
1263   Builder.SetInsertPoint(BB);
1264   Builder.CreateBr(LoopBB);
1265 
1266   // Start the main loop block now that we've taken care of the preliminaries.
1267   Builder.SetInsertPoint(LoopBB);
1268   Value *Loaded = TLI->emitLoadLinked(Builder, ResultTy, Addr, MemOpOrder);
1269 
1270   Value *NewVal = PerformOp(Builder, Loaded);
1271 
1272   Value *StoreSuccess =
1273       TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
1274   Value *TryAgain = Builder.CreateICmpNE(
1275       StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
1276   Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
1277 
1278   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1279   return Loaded;
1280 }
1281 
1282 /// Convert an atomic cmpxchg of a non-integral type to an integer cmpxchg of
1283 /// the equivalent bitwidth.  We used to not support pointer cmpxchg in the
1284 /// IR.  As a migration step, we convert back to what use to be the standard
1285 /// way to represent a pointer cmpxchg so that we can update backends one by
1286 /// one.
1287 AtomicCmpXchgInst *
1288 AtomicExpandImpl::convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI) {
1289   auto *M = CI->getModule();
1290   Type *NewTy = getCorrespondingIntegerType(CI->getCompareOperand()->getType(),
1291                                             M->getDataLayout());
1292 
1293   ReplacementIRBuilder Builder(CI, *DL);
1294 
1295   Value *Addr = CI->getPointerOperand();
1296 
1297   Value *NewCmp = Builder.CreatePtrToInt(CI->getCompareOperand(), NewTy);
1298   Value *NewNewVal = Builder.CreatePtrToInt(CI->getNewValOperand(), NewTy);
1299 
1300   auto *NewCI = Builder.CreateAtomicCmpXchg(
1301       Addr, NewCmp, NewNewVal, CI->getAlign(), CI->getSuccessOrdering(),
1302       CI->getFailureOrdering(), CI->getSyncScopeID());
1303   NewCI->setVolatile(CI->isVolatile());
1304   NewCI->setWeak(CI->isWeak());
1305   LLVM_DEBUG(dbgs() << "Replaced " << *CI << " with " << *NewCI << "\n");
1306 
1307   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
1308   Value *Succ = Builder.CreateExtractValue(NewCI, 1);
1309 
1310   OldVal = Builder.CreateIntToPtr(OldVal, CI->getCompareOperand()->getType());
1311 
1312   Value *Res = PoisonValue::get(CI->getType());
1313   Res = Builder.CreateInsertValue(Res, OldVal, 0);
1314   Res = Builder.CreateInsertValue(Res, Succ, 1);
1315 
1316   CI->replaceAllUsesWith(Res);
1317   CI->eraseFromParent();
1318   return NewCI;
1319 }
1320 
1321 bool AtomicExpandImpl::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
1322   AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
1323   AtomicOrdering FailureOrder = CI->getFailureOrdering();
1324   Value *Addr = CI->getPointerOperand();
1325   BasicBlock *BB = CI->getParent();
1326   Function *F = BB->getParent();
1327   LLVMContext &Ctx = F->getContext();
1328   // If shouldInsertFencesForAtomic() returns true, then the target does not
1329   // want to deal with memory orders, and emitLeading/TrailingFence should take
1330   // care of everything. Otherwise, emitLeading/TrailingFence are no-op and we
1331   // should preserve the ordering.
1332   bool ShouldInsertFencesForAtomic = TLI->shouldInsertFencesForAtomic(CI);
1333   AtomicOrdering MemOpOrder = ShouldInsertFencesForAtomic
1334                                   ? AtomicOrdering::Monotonic
1335                                   : CI->getMergedOrdering();
1336 
1337   // In implementations which use a barrier to achieve release semantics, we can
1338   // delay emitting this barrier until we know a store is actually going to be
1339   // attempted. The cost of this delay is that we need 2 copies of the block
1340   // emitting the load-linked, affecting code size.
1341   //
1342   // Ideally, this logic would be unconditional except for the minsize check
1343   // since in other cases the extra blocks naturally collapse down to the
1344   // minimal loop. Unfortunately, this puts too much stress on later
1345   // optimisations so we avoid emitting the extra logic in those cases too.
1346   bool HasReleasedLoadBB = !CI->isWeak() && ShouldInsertFencesForAtomic &&
1347                            SuccessOrder != AtomicOrdering::Monotonic &&
1348                            SuccessOrder != AtomicOrdering::Acquire &&
1349                            !F->hasMinSize();
1350 
1351   // There's no overhead for sinking the release barrier in a weak cmpxchg, so
1352   // do it even on minsize.
1353   bool UseUnconditionalReleaseBarrier = F->hasMinSize() && !CI->isWeak();
1354 
1355   // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
1356   //
1357   // The full expansion we produce is:
1358   //     [...]
1359   // %aligned.addr = ...
1360   // cmpxchg.start:
1361   //     %unreleasedload = @load.linked(%aligned.addr)
1362   //     %unreleasedload.extract = extract value from %unreleasedload
1363   //     %should_store = icmp eq %unreleasedload.extract, %desired
1364   //     br i1 %should_store, label %cmpxchg.releasingstore,
1365   //                          label %cmpxchg.nostore
1366   // cmpxchg.releasingstore:
1367   //     fence?
1368   //     br label cmpxchg.trystore
1369   // cmpxchg.trystore:
1370   //     %loaded.trystore = phi [%unreleasedload, %cmpxchg.releasingstore],
1371   //                            [%releasedload, %cmpxchg.releasedload]
1372   //     %updated.new = insert %new into %loaded.trystore
1373   //     %stored = @store_conditional(%updated.new, %aligned.addr)
1374   //     %success = icmp eq i32 %stored, 0
1375   //     br i1 %success, label %cmpxchg.success,
1376   //                     label %cmpxchg.releasedload/%cmpxchg.failure
1377   // cmpxchg.releasedload:
1378   //     %releasedload = @load.linked(%aligned.addr)
1379   //     %releasedload.extract = extract value from %releasedload
1380   //     %should_store = icmp eq %releasedload.extract, %desired
1381   //     br i1 %should_store, label %cmpxchg.trystore,
1382   //                          label %cmpxchg.failure
1383   // cmpxchg.success:
1384   //     fence?
1385   //     br label %cmpxchg.end
1386   // cmpxchg.nostore:
1387   //     %loaded.nostore = phi [%unreleasedload, %cmpxchg.start],
1388   //                           [%releasedload,
1389   //                               %cmpxchg.releasedload/%cmpxchg.trystore]
1390   //     @load_linked_fail_balance()?
1391   //     br label %cmpxchg.failure
1392   // cmpxchg.failure:
1393   //     fence?
1394   //     br label %cmpxchg.end
1395   // cmpxchg.end:
1396   //     %loaded.exit = phi [%loaded.nostore, %cmpxchg.failure],
1397   //                        [%loaded.trystore, %cmpxchg.trystore]
1398   //     %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
1399   //     %loaded = extract value from %loaded.exit
1400   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
1401   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
1402   //     [...]
1403   BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
1404   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
1405   auto NoStoreBB = BasicBlock::Create(Ctx, "cmpxchg.nostore", F, FailureBB);
1406   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, NoStoreBB);
1407   auto ReleasedLoadBB =
1408       BasicBlock::Create(Ctx, "cmpxchg.releasedload", F, SuccessBB);
1409   auto TryStoreBB =
1410       BasicBlock::Create(Ctx, "cmpxchg.trystore", F, ReleasedLoadBB);
1411   auto ReleasingStoreBB =
1412       BasicBlock::Create(Ctx, "cmpxchg.fencedstore", F, TryStoreBB);
1413   auto StartBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, ReleasingStoreBB);
1414 
1415   ReplacementIRBuilder Builder(CI, *DL);
1416 
1417   // The split call above "helpfully" added a branch at the end of BB (to the
1418   // wrong place), but we might want a fence too. It's easiest to just remove
1419   // the branch entirely.
1420   std::prev(BB->end())->eraseFromParent();
1421   Builder.SetInsertPoint(BB);
1422   if (ShouldInsertFencesForAtomic && UseUnconditionalReleaseBarrier)
1423     TLI->emitLeadingFence(Builder, CI, SuccessOrder);
1424 
1425   PartwordMaskValues PMV =
1426       createMaskInstrs(Builder, CI, CI->getCompareOperand()->getType(), Addr,
1427                        CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1428   Builder.CreateBr(StartBB);
1429 
1430   // Start the main loop block now that we've taken care of the preliminaries.
1431   Builder.SetInsertPoint(StartBB);
1432   Value *UnreleasedLoad =
1433       TLI->emitLoadLinked(Builder, PMV.WordType, PMV.AlignedAddr, MemOpOrder);
1434   Value *UnreleasedLoadExtract =
1435       extractMaskedValue(Builder, UnreleasedLoad, PMV);
1436   Value *ShouldStore = Builder.CreateICmpEQ(
1437       UnreleasedLoadExtract, CI->getCompareOperand(), "should_store");
1438 
1439   // If the cmpxchg doesn't actually need any ordering when it fails, we can
1440   // jump straight past that fence instruction (if it exists).
1441   Builder.CreateCondBr(ShouldStore, ReleasingStoreBB, NoStoreBB);
1442 
1443   Builder.SetInsertPoint(ReleasingStoreBB);
1444   if (ShouldInsertFencesForAtomic && !UseUnconditionalReleaseBarrier)
1445     TLI->emitLeadingFence(Builder, CI, SuccessOrder);
1446   Builder.CreateBr(TryStoreBB);
1447 
1448   Builder.SetInsertPoint(TryStoreBB);
1449   PHINode *LoadedTryStore =
1450       Builder.CreatePHI(PMV.WordType, 2, "loaded.trystore");
1451   LoadedTryStore->addIncoming(UnreleasedLoad, ReleasingStoreBB);
1452   Value *NewValueInsert =
1453       insertMaskedValue(Builder, LoadedTryStore, CI->getNewValOperand(), PMV);
1454   Value *StoreSuccess = TLI->emitStoreConditional(Builder, NewValueInsert,
1455                                                   PMV.AlignedAddr, MemOpOrder);
1456   StoreSuccess = Builder.CreateICmpEQ(
1457       StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
1458   BasicBlock *RetryBB = HasReleasedLoadBB ? ReleasedLoadBB : StartBB;
1459   Builder.CreateCondBr(StoreSuccess, SuccessBB,
1460                        CI->isWeak() ? FailureBB : RetryBB);
1461 
1462   Builder.SetInsertPoint(ReleasedLoadBB);
1463   Value *SecondLoad;
1464   if (HasReleasedLoadBB) {
1465     SecondLoad =
1466         TLI->emitLoadLinked(Builder, PMV.WordType, PMV.AlignedAddr, MemOpOrder);
1467     Value *SecondLoadExtract = extractMaskedValue(Builder, SecondLoad, PMV);
1468     ShouldStore = Builder.CreateICmpEQ(SecondLoadExtract,
1469                                        CI->getCompareOperand(), "should_store");
1470 
1471     // If the cmpxchg doesn't actually need any ordering when it fails, we can
1472     // jump straight past that fence instruction (if it exists).
1473     Builder.CreateCondBr(ShouldStore, TryStoreBB, NoStoreBB);
1474     // Update PHI node in TryStoreBB.
1475     LoadedTryStore->addIncoming(SecondLoad, ReleasedLoadBB);
1476   } else
1477     Builder.CreateUnreachable();
1478 
1479   // Make sure later instructions don't get reordered with a fence if
1480   // necessary.
1481   Builder.SetInsertPoint(SuccessBB);
1482   if (ShouldInsertFencesForAtomic ||
1483       TLI->shouldInsertTrailingFenceForAtomicStore(CI))
1484     TLI->emitTrailingFence(Builder, CI, SuccessOrder);
1485   Builder.CreateBr(ExitBB);
1486 
1487   Builder.SetInsertPoint(NoStoreBB);
1488   PHINode *LoadedNoStore =
1489       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.nostore");
1490   LoadedNoStore->addIncoming(UnreleasedLoad, StartBB);
1491   if (HasReleasedLoadBB)
1492     LoadedNoStore->addIncoming(SecondLoad, ReleasedLoadBB);
1493 
1494   // In the failing case, where we don't execute the store-conditional, the
1495   // target might want to balance out the load-linked with a dedicated
1496   // instruction (e.g., on ARM, clearing the exclusive monitor).
1497   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
1498   Builder.CreateBr(FailureBB);
1499 
1500   Builder.SetInsertPoint(FailureBB);
1501   PHINode *LoadedFailure =
1502       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.failure");
1503   LoadedFailure->addIncoming(LoadedNoStore, NoStoreBB);
1504   if (CI->isWeak())
1505     LoadedFailure->addIncoming(LoadedTryStore, TryStoreBB);
1506   if (ShouldInsertFencesForAtomic)
1507     TLI->emitTrailingFence(Builder, CI, FailureOrder);
1508   Builder.CreateBr(ExitBB);
1509 
1510   // Finally, we have control-flow based knowledge of whether the cmpxchg
1511   // succeeded or not. We expose this to later passes by converting any
1512   // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate
1513   // PHI.
1514   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1515   PHINode *LoadedExit =
1516       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.exit");
1517   LoadedExit->addIncoming(LoadedTryStore, SuccessBB);
1518   LoadedExit->addIncoming(LoadedFailure, FailureBB);
1519   PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2, "success");
1520   Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
1521   Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
1522 
1523   // This is the "exit value" from the cmpxchg expansion. It may be of
1524   // a type wider than the one in the cmpxchg instruction.
1525   Value *LoadedFull = LoadedExit;
1526 
1527   Builder.SetInsertPoint(ExitBB, std::next(Success->getIterator()));
1528   Value *Loaded = extractMaskedValue(Builder, LoadedFull, PMV);
1529 
1530   // Look for any users of the cmpxchg that are just comparing the loaded value
1531   // against the desired one, and replace them with the CFG-derived version.
1532   SmallVector<ExtractValueInst *, 2> PrunedInsts;
1533   for (auto *User : CI->users()) {
1534     ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
1535     if (!EV)
1536       continue;
1537 
1538     assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
1539            "weird extraction from { iN, i1 }");
1540 
1541     if (EV->getIndices()[0] == 0)
1542       EV->replaceAllUsesWith(Loaded);
1543     else
1544       EV->replaceAllUsesWith(Success);
1545 
1546     PrunedInsts.push_back(EV);
1547   }
1548 
1549   // We can remove the instructions now we're no longer iterating through them.
1550   for (auto *EV : PrunedInsts)
1551     EV->eraseFromParent();
1552 
1553   if (!CI->use_empty()) {
1554     // Some use of the full struct return that we don't understand has happened,
1555     // so we've got to reconstruct it properly.
1556     Value *Res;
1557     Res = Builder.CreateInsertValue(PoisonValue::get(CI->getType()), Loaded, 0);
1558     Res = Builder.CreateInsertValue(Res, Success, 1);
1559 
1560     CI->replaceAllUsesWith(Res);
1561   }
1562 
1563   CI->eraseFromParent();
1564   return true;
1565 }
1566 
1567 bool AtomicExpandImpl::isIdempotentRMW(AtomicRMWInst *RMWI) {
1568   auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
1569   if (!C)
1570     return false;
1571 
1572   AtomicRMWInst::BinOp Op = RMWI->getOperation();
1573   switch (Op) {
1574   case AtomicRMWInst::Add:
1575   case AtomicRMWInst::Sub:
1576   case AtomicRMWInst::Or:
1577   case AtomicRMWInst::Xor:
1578     return C->isZero();
1579   case AtomicRMWInst::And:
1580     return C->isMinusOne();
1581   // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
1582   default:
1583     return false;
1584   }
1585 }
1586 
1587 bool AtomicExpandImpl::simplifyIdempotentRMW(AtomicRMWInst *RMWI) {
1588   if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
1589     tryExpandAtomicLoad(ResultingLoad);
1590     return true;
1591   }
1592   return false;
1593 }
1594 
1595 Value *AtomicExpandImpl::insertRMWCmpXchgLoop(
1596     IRBuilderBase &Builder, Type *ResultTy, Value *Addr, Align AddrAlign,
1597     AtomicOrdering MemOpOrder, SyncScope::ID SSID,
1598     function_ref<Value *(IRBuilderBase &, Value *)> PerformOp,
1599     CreateCmpXchgInstFun CreateCmpXchg) {
1600   LLVMContext &Ctx = Builder.getContext();
1601   BasicBlock *BB = Builder.GetInsertBlock();
1602   Function *F = BB->getParent();
1603 
1604   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1605   //
1606   // The standard expansion we produce is:
1607   //     [...]
1608   //     %init_loaded = load atomic iN* %addr
1609   //     br label %loop
1610   // loop:
1611   //     %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
1612   //     %new = some_op iN %loaded, %incr
1613   //     %pair = cmpxchg iN* %addr, iN %loaded, iN %new
1614   //     %new_loaded = extractvalue { iN, i1 } %pair, 0
1615   //     %success = extractvalue { iN, i1 } %pair, 1
1616   //     br i1 %success, label %atomicrmw.end, label %loop
1617   // atomicrmw.end:
1618   //     [...]
1619   BasicBlock *ExitBB =
1620       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
1621   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1622 
1623   // The split call above "helpfully" added a branch at the end of BB (to the
1624   // wrong place), but we want a load. It's easiest to just remove
1625   // the branch entirely.
1626   std::prev(BB->end())->eraseFromParent();
1627   Builder.SetInsertPoint(BB);
1628   LoadInst *InitLoaded = Builder.CreateAlignedLoad(ResultTy, Addr, AddrAlign);
1629   Builder.CreateBr(LoopBB);
1630 
1631   // Start the main loop block now that we've taken care of the preliminaries.
1632   Builder.SetInsertPoint(LoopBB);
1633   PHINode *Loaded = Builder.CreatePHI(ResultTy, 2, "loaded");
1634   Loaded->addIncoming(InitLoaded, BB);
1635 
1636   Value *NewVal = PerformOp(Builder, Loaded);
1637 
1638   Value *NewLoaded = nullptr;
1639   Value *Success = nullptr;
1640 
1641   CreateCmpXchg(Builder, Addr, Loaded, NewVal, AddrAlign,
1642                 MemOpOrder == AtomicOrdering::Unordered
1643                     ? AtomicOrdering::Monotonic
1644                     : MemOpOrder,
1645                 SSID, Success, NewLoaded);
1646   assert(Success && NewLoaded);
1647 
1648   Loaded->addIncoming(NewLoaded, LoopBB);
1649 
1650   Builder.CreateCondBr(Success, ExitBB, LoopBB);
1651 
1652   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1653   return NewLoaded;
1654 }
1655 
1656 bool AtomicExpandImpl::tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
1657   unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
1658   unsigned ValueSize = getAtomicOpSize(CI);
1659 
1660   switch (TLI->shouldExpandAtomicCmpXchgInIR(CI)) {
1661   default:
1662     llvm_unreachable("Unhandled case in tryExpandAtomicCmpXchg");
1663   case TargetLoweringBase::AtomicExpansionKind::None:
1664     if (ValueSize < MinCASSize)
1665       return expandPartwordCmpXchg(CI);
1666     return false;
1667   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
1668     return expandAtomicCmpXchg(CI);
1669   }
1670   case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic:
1671     expandAtomicCmpXchgToMaskedIntrinsic(CI);
1672     return true;
1673   case TargetLoweringBase::AtomicExpansionKind::NotAtomic:
1674     return lowerAtomicCmpXchgInst(CI);
1675   }
1676 }
1677 
1678 // Note: This function is exposed externally by AtomicExpandUtils.h
1679 bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
1680                                     CreateCmpXchgInstFun CreateCmpXchg) {
1681   ReplacementIRBuilder Builder(AI, AI->getDataLayout());
1682   Builder.setIsFPConstrained(
1683       AI->getFunction()->hasFnAttribute(Attribute::StrictFP));
1684 
1685   // FIXME: If FP exceptions are observable, we should force them off for the
1686   // loop for the FP atomics.
1687   Value *Loaded = AtomicExpandImpl::insertRMWCmpXchgLoop(
1688       Builder, AI->getType(), AI->getPointerOperand(), AI->getAlign(),
1689       AI->getOrdering(), AI->getSyncScopeID(),
1690       [&](IRBuilderBase &Builder, Value *Loaded) {
1691         return buildAtomicRMWValue(AI->getOperation(), Builder, Loaded,
1692                                    AI->getValOperand());
1693       },
1694       CreateCmpXchg);
1695 
1696   AI->replaceAllUsesWith(Loaded);
1697   AI->eraseFromParent();
1698   return true;
1699 }
1700 
1701 // In order to use one of the sized library calls such as
1702 // __atomic_fetch_add_4, the alignment must be sufficient, the size
1703 // must be one of the potentially-specialized sizes, and the value
1704 // type must actually exist in C on the target (otherwise, the
1705 // function wouldn't actually be defined.)
1706 static bool canUseSizedAtomicCall(unsigned Size, Align Alignment,
1707                                   const DataLayout &DL) {
1708   // TODO: "LargestSize" is an approximation for "largest type that
1709   // you can express in C". It seems to be the case that int128 is
1710   // supported on all 64-bit platforms, otherwise only up to 64-bit
1711   // integers are supported. If we get this wrong, then we'll try to
1712   // call a sized libcall that doesn't actually exist. There should
1713   // really be some more reliable way in LLVM of determining integer
1714   // sizes which are valid in the target's C ABI...
1715   unsigned LargestSize = DL.getLargestLegalIntTypeSizeInBits() >= 64 ? 16 : 8;
1716   return Alignment >= Size &&
1717          (Size == 1 || Size == 2 || Size == 4 || Size == 8 || Size == 16) &&
1718          Size <= LargestSize;
1719 }
1720 
1721 void AtomicExpandImpl::expandAtomicLoadToLibcall(LoadInst *I) {
1722   static const RTLIB::Libcall Libcalls[6] = {
1723       RTLIB::ATOMIC_LOAD,   RTLIB::ATOMIC_LOAD_1, RTLIB::ATOMIC_LOAD_2,
1724       RTLIB::ATOMIC_LOAD_4, RTLIB::ATOMIC_LOAD_8, RTLIB::ATOMIC_LOAD_16};
1725   unsigned Size = getAtomicOpSize(I);
1726 
1727   bool expanded = expandAtomicOpToLibcall(
1728       I, Size, I->getAlign(), I->getPointerOperand(), nullptr, nullptr,
1729       I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1730   if (!expanded)
1731     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Load");
1732 }
1733 
1734 void AtomicExpandImpl::expandAtomicStoreToLibcall(StoreInst *I) {
1735   static const RTLIB::Libcall Libcalls[6] = {
1736       RTLIB::ATOMIC_STORE,   RTLIB::ATOMIC_STORE_1, RTLIB::ATOMIC_STORE_2,
1737       RTLIB::ATOMIC_STORE_4, RTLIB::ATOMIC_STORE_8, RTLIB::ATOMIC_STORE_16};
1738   unsigned Size = getAtomicOpSize(I);
1739 
1740   bool expanded = expandAtomicOpToLibcall(
1741       I, Size, I->getAlign(), I->getPointerOperand(), I->getValueOperand(),
1742       nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1743   if (!expanded)
1744     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Store");
1745 }
1746 
1747 void AtomicExpandImpl::expandAtomicCASToLibcall(AtomicCmpXchgInst *I) {
1748   static const RTLIB::Libcall Libcalls[6] = {
1749       RTLIB::ATOMIC_COMPARE_EXCHANGE,   RTLIB::ATOMIC_COMPARE_EXCHANGE_1,
1750       RTLIB::ATOMIC_COMPARE_EXCHANGE_2, RTLIB::ATOMIC_COMPARE_EXCHANGE_4,
1751       RTLIB::ATOMIC_COMPARE_EXCHANGE_8, RTLIB::ATOMIC_COMPARE_EXCHANGE_16};
1752   unsigned Size = getAtomicOpSize(I);
1753 
1754   bool expanded = expandAtomicOpToLibcall(
1755       I, Size, I->getAlign(), I->getPointerOperand(), I->getNewValOperand(),
1756       I->getCompareOperand(), I->getSuccessOrdering(), I->getFailureOrdering(),
1757       Libcalls);
1758   if (!expanded)
1759     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for CAS");
1760 }
1761 
1762 static ArrayRef<RTLIB::Libcall> GetRMWLibcall(AtomicRMWInst::BinOp Op) {
1763   static const RTLIB::Libcall LibcallsXchg[6] = {
1764       RTLIB::ATOMIC_EXCHANGE,   RTLIB::ATOMIC_EXCHANGE_1,
1765       RTLIB::ATOMIC_EXCHANGE_2, RTLIB::ATOMIC_EXCHANGE_4,
1766       RTLIB::ATOMIC_EXCHANGE_8, RTLIB::ATOMIC_EXCHANGE_16};
1767   static const RTLIB::Libcall LibcallsAdd[6] = {
1768       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_ADD_1,
1769       RTLIB::ATOMIC_FETCH_ADD_2, RTLIB::ATOMIC_FETCH_ADD_4,
1770       RTLIB::ATOMIC_FETCH_ADD_8, RTLIB::ATOMIC_FETCH_ADD_16};
1771   static const RTLIB::Libcall LibcallsSub[6] = {
1772       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_SUB_1,
1773       RTLIB::ATOMIC_FETCH_SUB_2, RTLIB::ATOMIC_FETCH_SUB_4,
1774       RTLIB::ATOMIC_FETCH_SUB_8, RTLIB::ATOMIC_FETCH_SUB_16};
1775   static const RTLIB::Libcall LibcallsAnd[6] = {
1776       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_AND_1,
1777       RTLIB::ATOMIC_FETCH_AND_2, RTLIB::ATOMIC_FETCH_AND_4,
1778       RTLIB::ATOMIC_FETCH_AND_8, RTLIB::ATOMIC_FETCH_AND_16};
1779   static const RTLIB::Libcall LibcallsOr[6] = {
1780       RTLIB::UNKNOWN_LIBCALL,   RTLIB::ATOMIC_FETCH_OR_1,
1781       RTLIB::ATOMIC_FETCH_OR_2, RTLIB::ATOMIC_FETCH_OR_4,
1782       RTLIB::ATOMIC_FETCH_OR_8, RTLIB::ATOMIC_FETCH_OR_16};
1783   static const RTLIB::Libcall LibcallsXor[6] = {
1784       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_XOR_1,
1785       RTLIB::ATOMIC_FETCH_XOR_2, RTLIB::ATOMIC_FETCH_XOR_4,
1786       RTLIB::ATOMIC_FETCH_XOR_8, RTLIB::ATOMIC_FETCH_XOR_16};
1787   static const RTLIB::Libcall LibcallsNand[6] = {
1788       RTLIB::UNKNOWN_LIBCALL,     RTLIB::ATOMIC_FETCH_NAND_1,
1789       RTLIB::ATOMIC_FETCH_NAND_2, RTLIB::ATOMIC_FETCH_NAND_4,
1790       RTLIB::ATOMIC_FETCH_NAND_8, RTLIB::ATOMIC_FETCH_NAND_16};
1791 
1792   switch (Op) {
1793   case AtomicRMWInst::BAD_BINOP:
1794     llvm_unreachable("Should not have BAD_BINOP.");
1795   case AtomicRMWInst::Xchg:
1796     return ArrayRef(LibcallsXchg);
1797   case AtomicRMWInst::Add:
1798     return ArrayRef(LibcallsAdd);
1799   case AtomicRMWInst::Sub:
1800     return ArrayRef(LibcallsSub);
1801   case AtomicRMWInst::And:
1802     return ArrayRef(LibcallsAnd);
1803   case AtomicRMWInst::Or:
1804     return ArrayRef(LibcallsOr);
1805   case AtomicRMWInst::Xor:
1806     return ArrayRef(LibcallsXor);
1807   case AtomicRMWInst::Nand:
1808     return ArrayRef(LibcallsNand);
1809   case AtomicRMWInst::Max:
1810   case AtomicRMWInst::Min:
1811   case AtomicRMWInst::UMax:
1812   case AtomicRMWInst::UMin:
1813   case AtomicRMWInst::FMax:
1814   case AtomicRMWInst::FMin:
1815   case AtomicRMWInst::FAdd:
1816   case AtomicRMWInst::FSub:
1817   case AtomicRMWInst::UIncWrap:
1818   case AtomicRMWInst::UDecWrap:
1819     // No atomic libcalls are available for max/min/umax/umin.
1820     return {};
1821   }
1822   llvm_unreachable("Unexpected AtomicRMW operation.");
1823 }
1824 
1825 void AtomicExpandImpl::expandAtomicRMWToLibcall(AtomicRMWInst *I) {
1826   ArrayRef<RTLIB::Libcall> Libcalls = GetRMWLibcall(I->getOperation());
1827 
1828   unsigned Size = getAtomicOpSize(I);
1829 
1830   bool Success = false;
1831   if (!Libcalls.empty())
1832     Success = expandAtomicOpToLibcall(
1833         I, Size, I->getAlign(), I->getPointerOperand(), I->getValOperand(),
1834         nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1835 
1836   // The expansion failed: either there were no libcalls at all for
1837   // the operation (min/max), or there were only size-specialized
1838   // libcalls (add/sub/etc) and we needed a generic. So, expand to a
1839   // CAS libcall, via a CAS loop, instead.
1840   if (!Success) {
1841     expandAtomicRMWToCmpXchg(
1842         I, [this](IRBuilderBase &Builder, Value *Addr, Value *Loaded,
1843                   Value *NewVal, Align Alignment, AtomicOrdering MemOpOrder,
1844                   SyncScope::ID SSID, Value *&Success, Value *&NewLoaded) {
1845           // Create the CAS instruction normally...
1846           AtomicCmpXchgInst *Pair = Builder.CreateAtomicCmpXchg(
1847               Addr, Loaded, NewVal, Alignment, MemOpOrder,
1848               AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
1849           Success = Builder.CreateExtractValue(Pair, 1, "success");
1850           NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
1851 
1852           // ...and then expand the CAS into a libcall.
1853           expandAtomicCASToLibcall(Pair);
1854         });
1855   }
1856 }
1857 
1858 // A helper routine for the above expandAtomic*ToLibcall functions.
1859 //
1860 // 'Libcalls' contains an array of enum values for the particular
1861 // ATOMIC libcalls to be emitted. All of the other arguments besides
1862 // 'I' are extracted from the Instruction subclass by the
1863 // caller. Depending on the particular call, some will be null.
1864 bool AtomicExpandImpl::expandAtomicOpToLibcall(
1865     Instruction *I, unsigned Size, Align Alignment, Value *PointerOperand,
1866     Value *ValueOperand, Value *CASExpected, AtomicOrdering Ordering,
1867     AtomicOrdering Ordering2, ArrayRef<RTLIB::Libcall> Libcalls) {
1868   assert(Libcalls.size() == 6);
1869 
1870   LLVMContext &Ctx = I->getContext();
1871   Module *M = I->getModule();
1872   const DataLayout &DL = M->getDataLayout();
1873   IRBuilder<> Builder(I);
1874   IRBuilder<> AllocaBuilder(&I->getFunction()->getEntryBlock().front());
1875 
1876   bool UseSizedLibcall = canUseSizedAtomicCall(Size, Alignment, DL);
1877   Type *SizedIntTy = Type::getIntNTy(Ctx, Size * 8);
1878 
1879   const Align AllocaAlignment = DL.getPrefTypeAlign(SizedIntTy);
1880 
1881   // TODO: the "order" argument type is "int", not int32. So
1882   // getInt32Ty may be wrong if the arch uses e.g. 16-bit ints.
1883   ConstantInt *SizeVal64 = ConstantInt::get(Type::getInt64Ty(Ctx), Size);
1884   assert(Ordering != AtomicOrdering::NotAtomic && "expect atomic MO");
1885   Constant *OrderingVal =
1886       ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering));
1887   Constant *Ordering2Val = nullptr;
1888   if (CASExpected) {
1889     assert(Ordering2 != AtomicOrdering::NotAtomic && "expect atomic MO");
1890     Ordering2Val =
1891         ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering2));
1892   }
1893   bool HasResult = I->getType() != Type::getVoidTy(Ctx);
1894 
1895   RTLIB::Libcall RTLibType;
1896   if (UseSizedLibcall) {
1897     switch (Size) {
1898     case 1:
1899       RTLibType = Libcalls[1];
1900       break;
1901     case 2:
1902       RTLibType = Libcalls[2];
1903       break;
1904     case 4:
1905       RTLibType = Libcalls[3];
1906       break;
1907     case 8:
1908       RTLibType = Libcalls[4];
1909       break;
1910     case 16:
1911       RTLibType = Libcalls[5];
1912       break;
1913     }
1914   } else if (Libcalls[0] != RTLIB::UNKNOWN_LIBCALL) {
1915     RTLibType = Libcalls[0];
1916   } else {
1917     // Can't use sized function, and there's no generic for this
1918     // operation, so give up.
1919     return false;
1920   }
1921 
1922   if (!TLI->getLibcallName(RTLibType)) {
1923     // This target does not implement the requested atomic libcall so give up.
1924     return false;
1925   }
1926 
1927   // Build up the function call. There's two kinds. First, the sized
1928   // variants.  These calls are going to be one of the following (with
1929   // N=1,2,4,8,16):
1930   //  iN    __atomic_load_N(iN *ptr, int ordering)
1931   //  void  __atomic_store_N(iN *ptr, iN val, int ordering)
1932   //  iN    __atomic_{exchange|fetch_*}_N(iN *ptr, iN val, int ordering)
1933   //  bool  __atomic_compare_exchange_N(iN *ptr, iN *expected, iN desired,
1934   //                                    int success_order, int failure_order)
1935   //
1936   // Note that these functions can be used for non-integer atomic
1937   // operations, the values just need to be bitcast to integers on the
1938   // way in and out.
1939   //
1940   // And, then, the generic variants. They look like the following:
1941   //  void  __atomic_load(size_t size, void *ptr, void *ret, int ordering)
1942   //  void  __atomic_store(size_t size, void *ptr, void *val, int ordering)
1943   //  void  __atomic_exchange(size_t size, void *ptr, void *val, void *ret,
1944   //                          int ordering)
1945   //  bool  __atomic_compare_exchange(size_t size, void *ptr, void *expected,
1946   //                                  void *desired, int success_order,
1947   //                                  int failure_order)
1948   //
1949   // The different signatures are built up depending on the
1950   // 'UseSizedLibcall', 'CASExpected', 'ValueOperand', and 'HasResult'
1951   // variables.
1952 
1953   AllocaInst *AllocaCASExpected = nullptr;
1954   AllocaInst *AllocaValue = nullptr;
1955   AllocaInst *AllocaResult = nullptr;
1956 
1957   Type *ResultTy;
1958   SmallVector<Value *, 6> Args;
1959   AttributeList Attr;
1960 
1961   // 'size' argument.
1962   if (!UseSizedLibcall) {
1963     // Note, getIntPtrType is assumed equivalent to size_t.
1964     Args.push_back(ConstantInt::get(DL.getIntPtrType(Ctx), Size));
1965   }
1966 
1967   // 'ptr' argument.
1968   // note: This assumes all address spaces share a common libfunc
1969   // implementation and that addresses are convertable.  For systems without
1970   // that property, we'd need to extend this mechanism to support AS-specific
1971   // families of atomic intrinsics.
1972   Value *PtrVal = PointerOperand;
1973   PtrVal = Builder.CreateAddrSpaceCast(PtrVal, PointerType::getUnqual(Ctx));
1974   Args.push_back(PtrVal);
1975 
1976   // 'expected' argument, if present.
1977   if (CASExpected) {
1978     AllocaCASExpected = AllocaBuilder.CreateAlloca(CASExpected->getType());
1979     AllocaCASExpected->setAlignment(AllocaAlignment);
1980     Builder.CreateLifetimeStart(AllocaCASExpected, SizeVal64);
1981     Builder.CreateAlignedStore(CASExpected, AllocaCASExpected, AllocaAlignment);
1982     Args.push_back(AllocaCASExpected);
1983   }
1984 
1985   // 'val' argument ('desired' for cas), if present.
1986   if (ValueOperand) {
1987     if (UseSizedLibcall) {
1988       Value *IntValue =
1989           Builder.CreateBitOrPointerCast(ValueOperand, SizedIntTy);
1990       Args.push_back(IntValue);
1991     } else {
1992       AllocaValue = AllocaBuilder.CreateAlloca(ValueOperand->getType());
1993       AllocaValue->setAlignment(AllocaAlignment);
1994       Builder.CreateLifetimeStart(AllocaValue, SizeVal64);
1995       Builder.CreateAlignedStore(ValueOperand, AllocaValue, AllocaAlignment);
1996       Args.push_back(AllocaValue);
1997     }
1998   }
1999 
2000   // 'ret' argument.
2001   if (!CASExpected && HasResult && !UseSizedLibcall) {
2002     AllocaResult = AllocaBuilder.CreateAlloca(I->getType());
2003     AllocaResult->setAlignment(AllocaAlignment);
2004     Builder.CreateLifetimeStart(AllocaResult, SizeVal64);
2005     Args.push_back(AllocaResult);
2006   }
2007 
2008   // 'ordering' ('success_order' for cas) argument.
2009   Args.push_back(OrderingVal);
2010 
2011   // 'failure_order' argument, if present.
2012   if (Ordering2Val)
2013     Args.push_back(Ordering2Val);
2014 
2015   // Now, the return type.
2016   if (CASExpected) {
2017     ResultTy = Type::getInt1Ty(Ctx);
2018     Attr = Attr.addRetAttribute(Ctx, Attribute::ZExt);
2019   } else if (HasResult && UseSizedLibcall)
2020     ResultTy = SizedIntTy;
2021   else
2022     ResultTy = Type::getVoidTy(Ctx);
2023 
2024   // Done with setting up arguments and return types, create the call:
2025   SmallVector<Type *, 6> ArgTys;
2026   for (Value *Arg : Args)
2027     ArgTys.push_back(Arg->getType());
2028   FunctionType *FnType = FunctionType::get(ResultTy, ArgTys, false);
2029   FunctionCallee LibcallFn =
2030       M->getOrInsertFunction(TLI->getLibcallName(RTLibType), FnType, Attr);
2031   CallInst *Call = Builder.CreateCall(LibcallFn, Args);
2032   Call->setAttributes(Attr);
2033   Value *Result = Call;
2034 
2035   // And then, extract the results...
2036   if (ValueOperand && !UseSizedLibcall)
2037     Builder.CreateLifetimeEnd(AllocaValue, SizeVal64);
2038 
2039   if (CASExpected) {
2040     // The final result from the CAS is {load of 'expected' alloca, bool result
2041     // from call}
2042     Type *FinalResultTy = I->getType();
2043     Value *V = PoisonValue::get(FinalResultTy);
2044     Value *ExpectedOut = Builder.CreateAlignedLoad(
2045         CASExpected->getType(), AllocaCASExpected, AllocaAlignment);
2046     Builder.CreateLifetimeEnd(AllocaCASExpected, SizeVal64);
2047     V = Builder.CreateInsertValue(V, ExpectedOut, 0);
2048     V = Builder.CreateInsertValue(V, Result, 1);
2049     I->replaceAllUsesWith(V);
2050   } else if (HasResult) {
2051     Value *V;
2052     if (UseSizedLibcall)
2053       V = Builder.CreateBitOrPointerCast(Result, I->getType());
2054     else {
2055       V = Builder.CreateAlignedLoad(I->getType(), AllocaResult,
2056                                     AllocaAlignment);
2057       Builder.CreateLifetimeEnd(AllocaResult, SizeVal64);
2058     }
2059     I->replaceAllUsesWith(V);
2060   }
2061   I->eraseFromParent();
2062   return true;
2063 }
2064