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