xref: /llvm-project/llvm/lib/CodeGen/AtomicExpandPass.cpp (revision 735ab61ac828bd61398e6847d60e308fdf2b54ec)
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/TargetLowering.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.h"
27 #include "llvm/CodeGen/ValueTypes.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/Constant.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/MDBuilder.h"
39 #include "llvm/IR/MemoryModelRelaxationAnnotations.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/IR/User.h"
43 #include "llvm/IR/Value.h"
44 #include "llvm/InitializePasses.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/AtomicOrdering.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Transforms/Utils/LowerAtomic.h"
53 #include <cassert>
54 #include <cstdint>
55 #include <iterator>
56 
57 using namespace llvm;
58 
59 #define DEBUG_TYPE "atomic-expand"
60 
61 namespace {
62 
63 class AtomicExpandImpl {
64   const TargetLowering *TLI = nullptr;
65   const DataLayout *DL = nullptr;
66 
67 private:
68   bool bracketInstWithFences(Instruction *I, AtomicOrdering Order);
69   IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
70   LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
71   bool tryExpandAtomicLoad(LoadInst *LI);
72   bool expandAtomicLoadToLL(LoadInst *LI);
73   bool expandAtomicLoadToCmpXchg(LoadInst *LI);
74   StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
75   bool tryExpandAtomicStore(StoreInst *SI);
76   void expandAtomicStore(StoreInst *SI);
77   bool tryExpandAtomicRMW(AtomicRMWInst *AI);
78   AtomicRMWInst *convertAtomicXchgToIntegerType(AtomicRMWInst *RMWI);
79   Value *
80   insertRMWLLSCLoop(IRBuilderBase &Builder, Type *ResultTy, Value *Addr,
81                     Align AddrAlign, AtomicOrdering MemOpOrder,
82                     function_ref<Value *(IRBuilderBase &, Value *)> PerformOp);
83   void expandAtomicOpToLLSC(
84       Instruction *I, Type *ResultTy, Value *Addr, Align AddrAlign,
85       AtomicOrdering MemOpOrder,
86       function_ref<Value *(IRBuilderBase &, Value *)> PerformOp);
87   void expandPartwordAtomicRMW(
88       AtomicRMWInst *I, TargetLoweringBase::AtomicExpansionKind ExpansionKind);
89   AtomicRMWInst *widenPartwordAtomicRMW(AtomicRMWInst *AI);
90   bool expandPartwordCmpXchg(AtomicCmpXchgInst *I);
91   void expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI);
92   void expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI);
93 
94   AtomicCmpXchgInst *convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI);
95   static Value *insertRMWCmpXchgLoop(
96       IRBuilderBase &Builder, Type *ResultType, Value *Addr, Align AddrAlign,
97       AtomicOrdering MemOpOrder, SyncScope::ID SSID,
98       function_ref<Value *(IRBuilderBase &, Value *)> PerformOp,
99       CreateCmpXchgInstFun CreateCmpXchg, Instruction *MetadataSrc);
100   bool tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI);
101 
102   bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
103   bool isIdempotentRMW(AtomicRMWInst *RMWI);
104   bool simplifyIdempotentRMW(AtomicRMWInst *RMWI);
105 
106   bool expandAtomicOpToLibcall(Instruction *I, unsigned Size, Align Alignment,
107                                Value *PointerOperand, Value *ValueOperand,
108                                Value *CASExpected, AtomicOrdering Ordering,
109                                AtomicOrdering Ordering2,
110                                ArrayRef<RTLIB::Libcall> Libcalls);
111   void expandAtomicLoadToLibcall(LoadInst *LI);
112   void expandAtomicStoreToLibcall(StoreInst *LI);
113   void expandAtomicRMWToLibcall(AtomicRMWInst *I);
114   void expandAtomicCASToLibcall(AtomicCmpXchgInst *I);
115 
116   friend bool
117   llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
118                                  CreateCmpXchgInstFun CreateCmpXchg);
119 
120   bool processAtomicInstr(Instruction *I);
121 
122 public:
123   bool run(Function &F, const TargetMachine *TM);
124 };
125 
126 class AtomicExpandLegacy : public FunctionPass {
127 public:
128   static char ID; // Pass identification, replacement for typeid
129 
130   AtomicExpandLegacy() : FunctionPass(ID) {
131     initializeAtomicExpandLegacyPass(*PassRegistry::getPassRegistry());
132   }
133 
134   bool runOnFunction(Function &F) override;
135 };
136 
137 // IRBuilder to be used for replacement atomic instructions.
138 struct ReplacementIRBuilder
139     : IRBuilder<InstSimplifyFolder, IRBuilderCallbackInserter> {
140   MDNode *MMRAMD = nullptr;
141 
142   // Preserves the DebugLoc from I, and preserves still valid metadata.
143   // Enable StrictFP builder mode when appropriate.
144   explicit ReplacementIRBuilder(Instruction *I, const DataLayout &DL)
145       : IRBuilder(I->getContext(), InstSimplifyFolder(DL),
146                   IRBuilderCallbackInserter(
147                       [this](Instruction *I) { addMMRAMD(I); })) {
148     SetInsertPoint(I);
149     this->CollectMetadataToCopy(I, {LLVMContext::MD_pcsections});
150     if (BB->getParent()->getAttributes().hasFnAttr(Attribute::StrictFP))
151       this->setIsFPConstrained(true);
152 
153     MMRAMD = I->getMetadata(LLVMContext::MD_mmra);
154   }
155 
156   void addMMRAMD(Instruction *I) {
157     if (canInstructionHaveMMRAs(*I))
158       I->setMetadata(LLVMContext::MD_mmra, MMRAMD);
159   }
160 };
161 
162 } // end anonymous namespace
163 
164 char AtomicExpandLegacy::ID = 0;
165 
166 char &llvm::AtomicExpandID = AtomicExpandLegacy::ID;
167 
168 INITIALIZE_PASS_BEGIN(AtomicExpandLegacy, DEBUG_TYPE,
169                       "Expand Atomic instructions", false, false)
170 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
171 INITIALIZE_PASS_END(AtomicExpandLegacy, DEBUG_TYPE,
172                     "Expand Atomic instructions", false, false)
173 
174 // Helper functions to retrieve the size of atomic instructions.
175 static unsigned getAtomicOpSize(LoadInst *LI) {
176   const DataLayout &DL = LI->getDataLayout();
177   return DL.getTypeStoreSize(LI->getType());
178 }
179 
180 static unsigned getAtomicOpSize(StoreInst *SI) {
181   const DataLayout &DL = SI->getDataLayout();
182   return DL.getTypeStoreSize(SI->getValueOperand()->getType());
183 }
184 
185 static unsigned getAtomicOpSize(AtomicRMWInst *RMWI) {
186   const DataLayout &DL = RMWI->getDataLayout();
187   return DL.getTypeStoreSize(RMWI->getValOperand()->getType());
188 }
189 
190 static unsigned getAtomicOpSize(AtomicCmpXchgInst *CASI) {
191   const DataLayout &DL = CASI->getDataLayout();
192   return DL.getTypeStoreSize(CASI->getCompareOperand()->getType());
193 }
194 
195 /// Copy metadata that's safe to preserve when widening atomics.
196 static void copyMetadataForAtomic(Instruction &Dest,
197                                   const Instruction &Source) {
198   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
199   Source.getAllMetadata(MD);
200   LLVMContext &Ctx = Dest.getContext();
201   MDBuilder MDB(Ctx);
202 
203   for (auto [ID, N] : MD) {
204     switch (ID) {
205     case LLVMContext::MD_dbg:
206     case LLVMContext::MD_tbaa:
207     case LLVMContext::MD_tbaa_struct:
208     case LLVMContext::MD_alias_scope:
209     case LLVMContext::MD_noalias:
210     case LLVMContext::MD_noalias_addrspace:
211     case LLVMContext::MD_access_group:
212     case LLVMContext::MD_mmra:
213       Dest.setMetadata(ID, N);
214       break;
215     default:
216       if (ID == Ctx.getMDKindID("amdgpu.no.remote.memory"))
217         Dest.setMetadata(ID, N);
218       else if (ID == Ctx.getMDKindID("amdgpu.no.fine.grained.memory"))
219         Dest.setMetadata(ID, N);
220 
221       // Losing amdgpu.ignore.denormal.mode, but it doesn't matter for current
222       // uses.
223       break;
224     }
225   }
226 }
227 
228 // Determine if a particular atomic operation has a supported size,
229 // and is of appropriate alignment, to be passed through for target
230 // lowering. (Versus turning into a __atomic libcall)
231 template <typename Inst>
232 static bool atomicSizeSupported(const TargetLowering *TLI, Inst *I) {
233   unsigned Size = getAtomicOpSize(I);
234   Align Alignment = I->getAlign();
235   return Alignment >= Size &&
236          Size <= TLI->getMaxAtomicSizeInBitsSupported() / 8;
237 }
238 
239 bool AtomicExpandImpl::processAtomicInstr(Instruction *I) {
240   auto *LI = dyn_cast<LoadInst>(I);
241   auto *SI = dyn_cast<StoreInst>(I);
242   auto *RMWI = dyn_cast<AtomicRMWInst>(I);
243   auto *CASI = dyn_cast<AtomicCmpXchgInst>(I);
244 
245   bool MadeChange = false;
246 
247   // If the Size/Alignment is not supported, replace with a libcall.
248   if (LI) {
249     if (!LI->isAtomic())
250       return false;
251 
252     if (!atomicSizeSupported(TLI, LI)) {
253       expandAtomicLoadToLibcall(LI);
254       return true;
255     }
256 
257     if (TLI->shouldCastAtomicLoadInIR(LI) ==
258         TargetLoweringBase::AtomicExpansionKind::CastToInteger) {
259       I = LI = convertAtomicLoadToIntegerType(LI);
260       MadeChange = true;
261     }
262   } else if (SI) {
263     if (!SI->isAtomic())
264       return false;
265 
266     if (!atomicSizeSupported(TLI, SI)) {
267       expandAtomicStoreToLibcall(SI);
268       return true;
269     }
270 
271     if (TLI->shouldCastAtomicStoreInIR(SI) ==
272         TargetLoweringBase::AtomicExpansionKind::CastToInteger) {
273       I = SI = convertAtomicStoreToIntegerType(SI);
274       MadeChange = true;
275     }
276   } else if (RMWI) {
277     if (!atomicSizeSupported(TLI, RMWI)) {
278       expandAtomicRMWToLibcall(RMWI);
279       return true;
280     }
281 
282     if (TLI->shouldCastAtomicRMWIInIR(RMWI) ==
283         TargetLoweringBase::AtomicExpansionKind::CastToInteger) {
284       I = RMWI = convertAtomicXchgToIntegerType(RMWI);
285       MadeChange = true;
286     }
287   } else if (CASI) {
288     if (!atomicSizeSupported(TLI, CASI)) {
289       expandAtomicCASToLibcall(CASI);
290       return true;
291     }
292 
293     // TODO: when we're ready to make the change at the IR level, we can
294     // extend convertCmpXchgToInteger for floating point too.
295     if (CASI->getCompareOperand()->getType()->isPointerTy()) {
296       // TODO: add a TLI hook to control this so that each target can
297       // convert to lowering the original type one at a time.
298       I = CASI = convertCmpXchgToIntegerType(CASI);
299       MadeChange = true;
300     }
301   } else
302     return false;
303 
304   if (TLI->shouldInsertFencesForAtomic(I)) {
305     auto FenceOrdering = AtomicOrdering::Monotonic;
306     if (LI && isAcquireOrStronger(LI->getOrdering())) {
307       FenceOrdering = LI->getOrdering();
308       LI->setOrdering(AtomicOrdering::Monotonic);
309     } else if (SI && isReleaseOrStronger(SI->getOrdering())) {
310       FenceOrdering = SI->getOrdering();
311       SI->setOrdering(AtomicOrdering::Monotonic);
312     } else if (RMWI && (isReleaseOrStronger(RMWI->getOrdering()) ||
313                         isAcquireOrStronger(RMWI->getOrdering()))) {
314       FenceOrdering = RMWI->getOrdering();
315       RMWI->setOrdering(AtomicOrdering::Monotonic);
316     } else if (CASI &&
317                TLI->shouldExpandAtomicCmpXchgInIR(CASI) ==
318                    TargetLoweringBase::AtomicExpansionKind::None &&
319                (isReleaseOrStronger(CASI->getSuccessOrdering()) ||
320                 isAcquireOrStronger(CASI->getSuccessOrdering()) ||
321                 isAcquireOrStronger(CASI->getFailureOrdering()))) {
322       // If a compare and swap is lowered to LL/SC, we can do smarter fence
323       // insertion, with a stronger one on the success path than on the
324       // failure path. As a result, fence insertion is directly done by
325       // expandAtomicCmpXchg in that case.
326       FenceOrdering = CASI->getMergedOrdering();
327       CASI->setSuccessOrdering(AtomicOrdering::Monotonic);
328       CASI->setFailureOrdering(AtomicOrdering::Monotonic);
329     }
330 
331     if (FenceOrdering != AtomicOrdering::Monotonic) {
332       MadeChange |= bracketInstWithFences(I, FenceOrdering);
333     }
334   } else if (I->hasAtomicStore() &&
335              TLI->shouldInsertTrailingFenceForAtomicStore(I)) {
336     auto FenceOrdering = AtomicOrdering::Monotonic;
337     if (SI)
338       FenceOrdering = SI->getOrdering();
339     else if (RMWI)
340       FenceOrdering = RMWI->getOrdering();
341     else if (CASI && TLI->shouldExpandAtomicCmpXchgInIR(CASI) !=
342                          TargetLoweringBase::AtomicExpansionKind::LLSC)
343       // LLSC is handled in expandAtomicCmpXchg().
344       FenceOrdering = CASI->getSuccessOrdering();
345 
346     IRBuilder Builder(I);
347     if (auto TrailingFence =
348             TLI->emitTrailingFence(Builder, I, FenceOrdering)) {
349       TrailingFence->moveAfter(I);
350       MadeChange = true;
351     }
352   }
353 
354   if (LI)
355     MadeChange |= tryExpandAtomicLoad(LI);
356   else if (SI)
357     MadeChange |= tryExpandAtomicStore(SI);
358   else if (RMWI) {
359     // There are two different ways of expanding RMW instructions:
360     // - into a load if it is idempotent
361     // - into a Cmpxchg/LL-SC loop otherwise
362     // we try them in that order.
363 
364     if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
365       MadeChange = true;
366 
367     } else {
368       MadeChange |= tryExpandAtomicRMW(RMWI);
369     }
370   } else if (CASI)
371     MadeChange |= tryExpandAtomicCmpXchg(CASI);
372 
373   return MadeChange;
374 }
375 
376 bool AtomicExpandImpl::run(Function &F, const TargetMachine *TM) {
377   const auto *Subtarget = TM->getSubtargetImpl(F);
378   if (!Subtarget->enableAtomicExpand())
379     return false;
380   TLI = Subtarget->getTargetLowering();
381   DL = &F.getDataLayout();
382 
383   bool MadeChange = false;
384 
385   for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
386     BasicBlock *BB = &*BBI;
387 
388     BasicBlock::reverse_iterator Next;
389 
390     for (BasicBlock::reverse_iterator I = BB->rbegin(), E = BB->rend(); I != E;
391          I = Next) {
392       Instruction &Inst = *I;
393       Next = std::next(I);
394 
395       if (processAtomicInstr(&Inst)) {
396         MadeChange = true;
397 
398         // New blocks may have been inserted.
399         BBE = F.end();
400       }
401     }
402   }
403 
404   return MadeChange;
405 }
406 
407 bool AtomicExpandLegacy::runOnFunction(Function &F) {
408 
409   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
410   if (!TPC)
411     return false;
412   auto *TM = &TPC->getTM<TargetMachine>();
413   AtomicExpandImpl AE;
414   return AE.run(F, TM);
415 }
416 
417 FunctionPass *llvm::createAtomicExpandLegacyPass() {
418   return new AtomicExpandLegacy();
419 }
420 
421 PreservedAnalyses AtomicExpandPass::run(Function &F,
422                                         FunctionAnalysisManager &AM) {
423   AtomicExpandImpl AE;
424 
425   bool Changed = AE.run(F, TM);
426   if (!Changed)
427     return PreservedAnalyses::all();
428 
429   return PreservedAnalyses::none();
430 }
431 
432 bool AtomicExpandImpl::bracketInstWithFences(Instruction *I,
433                                              AtomicOrdering Order) {
434   ReplacementIRBuilder Builder(I, *DL);
435 
436   auto LeadingFence = TLI->emitLeadingFence(Builder, I, Order);
437 
438   auto TrailingFence = TLI->emitTrailingFence(Builder, I, Order);
439   // We have a guard here because not every atomic operation generates a
440   // trailing fence.
441   if (TrailingFence)
442     TrailingFence->moveAfter(I);
443 
444   return (LeadingFence || TrailingFence);
445 }
446 
447 /// Get the iX type with the same bitwidth as T.
448 IntegerType *
449 AtomicExpandImpl::getCorrespondingIntegerType(Type *T, const DataLayout &DL) {
450   EVT VT = TLI->getMemValueType(DL, T);
451   unsigned BitWidth = VT.getStoreSizeInBits();
452   assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
453   return IntegerType::get(T->getContext(), BitWidth);
454 }
455 
456 /// Convert an atomic load of a non-integral type to an integer load of the
457 /// equivalent bitwidth.  See the function comment on
458 /// convertAtomicStoreToIntegerType for background.
459 LoadInst *AtomicExpandImpl::convertAtomicLoadToIntegerType(LoadInst *LI) {
460   auto *M = LI->getModule();
461   Type *NewTy = getCorrespondingIntegerType(LI->getType(), M->getDataLayout());
462 
463   ReplacementIRBuilder Builder(LI, *DL);
464 
465   Value *Addr = LI->getPointerOperand();
466 
467   auto *NewLI = Builder.CreateLoad(NewTy, Addr);
468   NewLI->setAlignment(LI->getAlign());
469   NewLI->setVolatile(LI->isVolatile());
470   NewLI->setAtomic(LI->getOrdering(), LI->getSyncScopeID());
471   LLVM_DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
472 
473   Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
474   LI->replaceAllUsesWith(NewVal);
475   LI->eraseFromParent();
476   return NewLI;
477 }
478 
479 AtomicRMWInst *
480 AtomicExpandImpl::convertAtomicXchgToIntegerType(AtomicRMWInst *RMWI) {
481   assert(RMWI->getOperation() == AtomicRMWInst::Xchg);
482 
483   auto *M = RMWI->getModule();
484   Type *NewTy =
485       getCorrespondingIntegerType(RMWI->getType(), M->getDataLayout());
486 
487   ReplacementIRBuilder Builder(RMWI, *DL);
488 
489   Value *Addr = RMWI->getPointerOperand();
490   Value *Val = RMWI->getValOperand();
491   Value *NewVal = Val->getType()->isPointerTy()
492                       ? Builder.CreatePtrToInt(Val, NewTy)
493                       : Builder.CreateBitCast(Val, NewTy);
494 
495   auto *NewRMWI = Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, Addr, NewVal,
496                                           RMWI->getAlign(), RMWI->getOrdering(),
497                                           RMWI->getSyncScopeID());
498   NewRMWI->setVolatile(RMWI->isVolatile());
499   LLVM_DEBUG(dbgs() << "Replaced " << *RMWI << " with " << *NewRMWI << "\n");
500 
501   Value *NewRVal = RMWI->getType()->isPointerTy()
502                        ? Builder.CreateIntToPtr(NewRMWI, RMWI->getType())
503                        : Builder.CreateBitCast(NewRMWI, RMWI->getType());
504   RMWI->replaceAllUsesWith(NewRVal);
505   RMWI->eraseFromParent();
506   return NewRMWI;
507 }
508 
509 bool AtomicExpandImpl::tryExpandAtomicLoad(LoadInst *LI) {
510   switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
511   case TargetLoweringBase::AtomicExpansionKind::None:
512     return false;
513   case TargetLoweringBase::AtomicExpansionKind::LLSC:
514     expandAtomicOpToLLSC(
515         LI, LI->getType(), LI->getPointerOperand(), LI->getAlign(),
516         LI->getOrdering(),
517         [](IRBuilderBase &Builder, Value *Loaded) { return Loaded; });
518     return true;
519   case TargetLoweringBase::AtomicExpansionKind::LLOnly:
520     return expandAtomicLoadToLL(LI);
521   case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
522     return expandAtomicLoadToCmpXchg(LI);
523   case TargetLoweringBase::AtomicExpansionKind::NotAtomic:
524     LI->setAtomic(AtomicOrdering::NotAtomic);
525     return true;
526   default:
527     llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
528   }
529 }
530 
531 bool AtomicExpandImpl::tryExpandAtomicStore(StoreInst *SI) {
532   switch (TLI->shouldExpandAtomicStoreInIR(SI)) {
533   case TargetLoweringBase::AtomicExpansionKind::None:
534     return false;
535   case TargetLoweringBase::AtomicExpansionKind::Expand:
536     expandAtomicStore(SI);
537     return true;
538   case TargetLoweringBase::AtomicExpansionKind::NotAtomic:
539     SI->setAtomic(AtomicOrdering::NotAtomic);
540     return true;
541   default:
542     llvm_unreachable("Unhandled case in tryExpandAtomicStore");
543   }
544 }
545 
546 bool AtomicExpandImpl::expandAtomicLoadToLL(LoadInst *LI) {
547   ReplacementIRBuilder Builder(LI, *DL);
548 
549   // On some architectures, load-linked instructions are atomic for larger
550   // sizes than normal loads. For example, the only 64-bit load guaranteed
551   // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
552   Value *Val = TLI->emitLoadLinked(Builder, LI->getType(),
553                                    LI->getPointerOperand(), LI->getOrdering());
554   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
555 
556   LI->replaceAllUsesWith(Val);
557   LI->eraseFromParent();
558 
559   return true;
560 }
561 
562 bool AtomicExpandImpl::expandAtomicLoadToCmpXchg(LoadInst *LI) {
563   ReplacementIRBuilder Builder(LI, *DL);
564   AtomicOrdering Order = LI->getOrdering();
565   if (Order == AtomicOrdering::Unordered)
566     Order = AtomicOrdering::Monotonic;
567 
568   Value *Addr = LI->getPointerOperand();
569   Type *Ty = LI->getType();
570   Constant *DummyVal = Constant::getNullValue(Ty);
571 
572   Value *Pair = Builder.CreateAtomicCmpXchg(
573       Addr, DummyVal, DummyVal, LI->getAlign(), Order,
574       AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
575   Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
576 
577   LI->replaceAllUsesWith(Loaded);
578   LI->eraseFromParent();
579 
580   return true;
581 }
582 
583 /// Convert an atomic store of a non-integral type to an integer store of the
584 /// equivalent bitwidth.  We used to not support floating point or vector
585 /// atomics in the IR at all.  The backends learned to deal with the bitcast
586 /// idiom because that was the only way of expressing the notion of a atomic
587 /// float or vector store.  The long term plan is to teach each backend to
588 /// instruction select from the original atomic store, but as a migration
589 /// mechanism, we convert back to the old format which the backends understand.
590 /// Each backend will need individual work to recognize the new format.
591 StoreInst *AtomicExpandImpl::convertAtomicStoreToIntegerType(StoreInst *SI) {
592   ReplacementIRBuilder Builder(SI, *DL);
593   auto *M = SI->getModule();
594   Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
595                                             M->getDataLayout());
596   Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
597 
598   Value *Addr = SI->getPointerOperand();
599 
600   StoreInst *NewSI = Builder.CreateStore(NewVal, Addr);
601   NewSI->setAlignment(SI->getAlign());
602   NewSI->setVolatile(SI->isVolatile());
603   NewSI->setAtomic(SI->getOrdering(), SI->getSyncScopeID());
604   LLVM_DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
605   SI->eraseFromParent();
606   return NewSI;
607 }
608 
609 void AtomicExpandImpl::expandAtomicStore(StoreInst *SI) {
610   // This function is only called on atomic stores that are too large to be
611   // atomic if implemented as a native store. So we replace them by an
612   // atomic swap, that can be implemented for example as a ldrex/strex on ARM
613   // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
614   // It is the responsibility of the target to only signal expansion via
615   // shouldExpandAtomicRMW in cases where this is required and possible.
616   ReplacementIRBuilder Builder(SI, *DL);
617   AtomicOrdering Ordering = SI->getOrdering();
618   assert(Ordering != AtomicOrdering::NotAtomic);
619   AtomicOrdering RMWOrdering = Ordering == AtomicOrdering::Unordered
620                                    ? AtomicOrdering::Monotonic
621                                    : Ordering;
622   AtomicRMWInst *AI = Builder.CreateAtomicRMW(
623       AtomicRMWInst::Xchg, SI->getPointerOperand(), SI->getValueOperand(),
624       SI->getAlign(), RMWOrdering);
625   SI->eraseFromParent();
626 
627   // Now we have an appropriate swap instruction, lower it as usual.
628   tryExpandAtomicRMW(AI);
629 }
630 
631 static void createCmpXchgInstFun(IRBuilderBase &Builder, Value *Addr,
632                                  Value *Loaded, Value *NewVal, Align AddrAlign,
633                                  AtomicOrdering MemOpOrder, SyncScope::ID SSID,
634                                  Value *&Success, Value *&NewLoaded,
635                                  Instruction *MetadataSrc) {
636   Type *OrigTy = NewVal->getType();
637 
638   // This code can go away when cmpxchg supports FP and vector types.
639   assert(!OrigTy->isPointerTy());
640   bool NeedBitcast = OrigTy->isFloatingPointTy() || OrigTy->isVectorTy();
641   if (NeedBitcast) {
642     IntegerType *IntTy = Builder.getIntNTy(OrigTy->getPrimitiveSizeInBits());
643     NewVal = Builder.CreateBitCast(NewVal, IntTy);
644     Loaded = Builder.CreateBitCast(Loaded, IntTy);
645   }
646 
647   AtomicCmpXchgInst *Pair = Builder.CreateAtomicCmpXchg(
648       Addr, Loaded, NewVal, AddrAlign, MemOpOrder,
649       AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
650   if (MetadataSrc)
651     copyMetadataForAtomic(*Pair, *MetadataSrc);
652 
653   Success = Builder.CreateExtractValue(Pair, 1, "success");
654   NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
655 
656   if (NeedBitcast)
657     NewLoaded = Builder.CreateBitCast(NewLoaded, OrigTy);
658 }
659 
660 bool AtomicExpandImpl::tryExpandAtomicRMW(AtomicRMWInst *AI) {
661   LLVMContext &Ctx = AI->getModule()->getContext();
662   TargetLowering::AtomicExpansionKind Kind = TLI->shouldExpandAtomicRMWInIR(AI);
663   switch (Kind) {
664   case TargetLoweringBase::AtomicExpansionKind::None:
665     return false;
666   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
667     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
668     unsigned ValueSize = getAtomicOpSize(AI);
669     if (ValueSize < MinCASSize) {
670       expandPartwordAtomicRMW(AI,
671                               TargetLoweringBase::AtomicExpansionKind::LLSC);
672     } else {
673       auto PerformOp = [&](IRBuilderBase &Builder, Value *Loaded) {
674         return buildAtomicRMWValue(AI->getOperation(), Builder, Loaded,
675                                    AI->getValOperand());
676       };
677       expandAtomicOpToLLSC(AI, AI->getType(), AI->getPointerOperand(),
678                            AI->getAlign(), AI->getOrdering(), PerformOp);
679     }
680     return true;
681   }
682   case TargetLoweringBase::AtomicExpansionKind::CmpXChg: {
683     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
684     unsigned ValueSize = getAtomicOpSize(AI);
685     if (ValueSize < MinCASSize) {
686       expandPartwordAtomicRMW(AI,
687                               TargetLoweringBase::AtomicExpansionKind::CmpXChg);
688     } else {
689       SmallVector<StringRef> SSNs;
690       Ctx.getSyncScopeNames(SSNs);
691       auto MemScope = SSNs[AI->getSyncScopeID()].empty()
692                           ? "system"
693                           : SSNs[AI->getSyncScopeID()];
694       OptimizationRemarkEmitter ORE(AI->getFunction());
695       ORE.emit([&]() {
696         return OptimizationRemark(DEBUG_TYPE, "Passed", AI)
697                << "A compare and swap loop was generated for an atomic "
698                << AI->getOperationName(AI->getOperation()) << " operation at "
699                << MemScope << " memory scope";
700       });
701       expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
702     }
703     return true;
704   }
705   case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic: {
706     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
707     unsigned ValueSize = getAtomicOpSize(AI);
708     if (ValueSize < MinCASSize) {
709       AtomicRMWInst::BinOp Op = AI->getOperation();
710       // Widen And/Or/Xor and give the target another chance at expanding it.
711       if (Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
712           Op == AtomicRMWInst::And) {
713         tryExpandAtomicRMW(widenPartwordAtomicRMW(AI));
714         return true;
715       }
716     }
717     expandAtomicRMWToMaskedIntrinsic(AI);
718     return true;
719   }
720   case TargetLoweringBase::AtomicExpansionKind::BitTestIntrinsic: {
721     TLI->emitBitTestAtomicRMWIntrinsic(AI);
722     return true;
723   }
724   case TargetLoweringBase::AtomicExpansionKind::CmpArithIntrinsic: {
725     TLI->emitCmpArithAtomicRMWIntrinsic(AI);
726     return true;
727   }
728   case TargetLoweringBase::AtomicExpansionKind::NotAtomic:
729     return lowerAtomicRMWInst(AI);
730   case TargetLoweringBase::AtomicExpansionKind::Expand:
731     TLI->emitExpandAtomicRMW(AI);
732     return true;
733   default:
734     llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
735   }
736 }
737 
738 namespace {
739 
740 struct PartwordMaskValues {
741   // These three fields are guaranteed to be set by createMaskInstrs.
742   Type *WordType = nullptr;
743   Type *ValueType = nullptr;
744   Type *IntValueType = nullptr;
745   Value *AlignedAddr = nullptr;
746   Align AlignedAddrAlignment;
747   // The remaining fields can be null.
748   Value *ShiftAmt = nullptr;
749   Value *Mask = nullptr;
750   Value *Inv_Mask = nullptr;
751 };
752 
753 LLVM_ATTRIBUTE_UNUSED
754 raw_ostream &operator<<(raw_ostream &O, const PartwordMaskValues &PMV) {
755   auto PrintObj = [&O](auto *V) {
756     if (V)
757       O << *V;
758     else
759       O << "nullptr";
760     O << '\n';
761   };
762   O << "PartwordMaskValues {\n";
763   O << "  WordType: ";
764   PrintObj(PMV.WordType);
765   O << "  ValueType: ";
766   PrintObj(PMV.ValueType);
767   O << "  AlignedAddr: ";
768   PrintObj(PMV.AlignedAddr);
769   O << "  AlignedAddrAlignment: " << PMV.AlignedAddrAlignment.value() << '\n';
770   O << "  ShiftAmt: ";
771   PrintObj(PMV.ShiftAmt);
772   O << "  Mask: ";
773   PrintObj(PMV.Mask);
774   O << "  Inv_Mask: ";
775   PrintObj(PMV.Inv_Mask);
776   O << "}\n";
777   return O;
778 }
779 
780 } // end anonymous namespace
781 
782 /// This is a helper function which builds instructions to provide
783 /// values necessary for partword atomic operations. It takes an
784 /// incoming address, Addr, and ValueType, and constructs the address,
785 /// shift-amounts and masks needed to work with a larger value of size
786 /// WordSize.
787 ///
788 /// AlignedAddr: Addr rounded down to a multiple of WordSize
789 ///
790 /// ShiftAmt: Number of bits to right-shift a WordSize value loaded
791 ///           from AlignAddr for it to have the same value as if
792 ///           ValueType was loaded from Addr.
793 ///
794 /// Mask: Value to mask with the value loaded from AlignAddr to
795 ///       include only the part that would've been loaded from Addr.
796 ///
797 /// Inv_Mask: The inverse of Mask.
798 static PartwordMaskValues createMaskInstrs(IRBuilderBase &Builder,
799                                            Instruction *I, Type *ValueType,
800                                            Value *Addr, Align AddrAlign,
801                                            unsigned MinWordSize) {
802   PartwordMaskValues PMV;
803 
804   Module *M = I->getModule();
805   LLVMContext &Ctx = M->getContext();
806   const DataLayout &DL = M->getDataLayout();
807   unsigned ValueSize = DL.getTypeStoreSize(ValueType);
808 
809   PMV.ValueType = PMV.IntValueType = ValueType;
810   if (PMV.ValueType->isFloatingPointTy() || PMV.ValueType->isVectorTy())
811     PMV.IntValueType =
812         Type::getIntNTy(Ctx, ValueType->getPrimitiveSizeInBits());
813 
814   PMV.WordType = MinWordSize > ValueSize ? Type::getIntNTy(Ctx, MinWordSize * 8)
815                                          : ValueType;
816   if (PMV.ValueType == PMV.WordType) {
817     PMV.AlignedAddr = Addr;
818     PMV.AlignedAddrAlignment = AddrAlign;
819     PMV.ShiftAmt = ConstantInt::get(PMV.ValueType, 0);
820     PMV.Mask = ConstantInt::get(PMV.ValueType, ~0, /*isSigned*/ true);
821     return PMV;
822   }
823 
824   PMV.AlignedAddrAlignment = Align(MinWordSize);
825 
826   assert(ValueSize < MinWordSize);
827 
828   PointerType *PtrTy = cast<PointerType>(Addr->getType());
829   IntegerType *IntTy = DL.getIndexType(Ctx, PtrTy->getAddressSpace());
830   Value *PtrLSB;
831 
832   if (AddrAlign < MinWordSize) {
833     PMV.AlignedAddr = Builder.CreateIntrinsic(
834         Intrinsic::ptrmask, {PtrTy, IntTy},
835         {Addr, ConstantInt::get(IntTy, ~(uint64_t)(MinWordSize - 1))}, nullptr,
836         "AlignedAddr");
837 
838     Value *AddrInt = Builder.CreatePtrToInt(Addr, IntTy);
839     PtrLSB = Builder.CreateAnd(AddrInt, MinWordSize - 1, "PtrLSB");
840   } else {
841     // If the alignment is high enough, the LSB are known 0.
842     PMV.AlignedAddr = Addr;
843     PtrLSB = ConstantInt::getNullValue(IntTy);
844   }
845 
846   if (DL.isLittleEndian()) {
847     // turn bytes into bits
848     PMV.ShiftAmt = Builder.CreateShl(PtrLSB, 3);
849   } else {
850     // turn bytes into bits, and count from the other side.
851     PMV.ShiftAmt = Builder.CreateShl(
852         Builder.CreateXor(PtrLSB, MinWordSize - ValueSize), 3);
853   }
854 
855   PMV.ShiftAmt = Builder.CreateTrunc(PMV.ShiftAmt, PMV.WordType, "ShiftAmt");
856   PMV.Mask = Builder.CreateShl(
857       ConstantInt::get(PMV.WordType, (1 << (ValueSize * 8)) - 1), PMV.ShiftAmt,
858       "Mask");
859 
860   PMV.Inv_Mask = Builder.CreateNot(PMV.Mask, "Inv_Mask");
861 
862   return PMV;
863 }
864 
865 static Value *extractMaskedValue(IRBuilderBase &Builder, Value *WideWord,
866                                  const PartwordMaskValues &PMV) {
867   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
868   if (PMV.WordType == PMV.ValueType)
869     return WideWord;
870 
871   Value *Shift = Builder.CreateLShr(WideWord, PMV.ShiftAmt, "shifted");
872   Value *Trunc = Builder.CreateTrunc(Shift, PMV.IntValueType, "extracted");
873   return Builder.CreateBitCast(Trunc, PMV.ValueType);
874 }
875 
876 static Value *insertMaskedValue(IRBuilderBase &Builder, Value *WideWord,
877                                 Value *Updated, const PartwordMaskValues &PMV) {
878   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
879   assert(Updated->getType() == PMV.ValueType && "Value type mismatch");
880   if (PMV.WordType == PMV.ValueType)
881     return Updated;
882 
883   Updated = Builder.CreateBitCast(Updated, PMV.IntValueType);
884 
885   Value *ZExt = Builder.CreateZExt(Updated, PMV.WordType, "extended");
886   Value *Shift =
887       Builder.CreateShl(ZExt, PMV.ShiftAmt, "shifted", /*HasNUW*/ true);
888   Value *And = Builder.CreateAnd(WideWord, PMV.Inv_Mask, "unmasked");
889   Value *Or = Builder.CreateOr(And, Shift, "inserted");
890   return Or;
891 }
892 
893 /// Emit IR to implement a masked version of a given atomicrmw
894 /// operation. (That is, only the bits under the Mask should be
895 /// affected by the operation)
896 static Value *performMaskedAtomicOp(AtomicRMWInst::BinOp Op,
897                                     IRBuilderBase &Builder, Value *Loaded,
898                                     Value *Shifted_Inc, Value *Inc,
899                                     const PartwordMaskValues &PMV) {
900   // TODO: update to use
901   // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge in order
902   // to merge bits from two values without requiring PMV.Inv_Mask.
903   switch (Op) {
904   case AtomicRMWInst::Xchg: {
905     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
906     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, Shifted_Inc);
907     return FinalVal;
908   }
909   case AtomicRMWInst::Or:
910   case AtomicRMWInst::Xor:
911   case AtomicRMWInst::And:
912     llvm_unreachable("Or/Xor/And handled by widenPartwordAtomicRMW");
913   case AtomicRMWInst::Add:
914   case AtomicRMWInst::Sub:
915   case AtomicRMWInst::Nand: {
916     // The other arithmetic ops need to be masked into place.
917     Value *NewVal = buildAtomicRMWValue(Op, Builder, Loaded, Shifted_Inc);
918     Value *NewVal_Masked = Builder.CreateAnd(NewVal, PMV.Mask);
919     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
920     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Masked);
921     return FinalVal;
922   }
923   case AtomicRMWInst::Max:
924   case AtomicRMWInst::Min:
925   case AtomicRMWInst::UMax:
926   case AtomicRMWInst::UMin:
927   case AtomicRMWInst::FAdd:
928   case AtomicRMWInst::FSub:
929   case AtomicRMWInst::FMin:
930   case AtomicRMWInst::FMax:
931   case AtomicRMWInst::UIncWrap:
932   case AtomicRMWInst::UDecWrap:
933   case AtomicRMWInst::USubCond:
934   case AtomicRMWInst::USubSat: {
935     // Finally, other ops will operate on the full value, so truncate down to
936     // the original size, and expand out again after doing the
937     // operation. Bitcasts will be inserted for FP values.
938     Value *Loaded_Extract = extractMaskedValue(Builder, Loaded, PMV);
939     Value *NewVal = buildAtomicRMWValue(Op, Builder, Loaded_Extract, Inc);
940     Value *FinalVal = insertMaskedValue(Builder, Loaded, NewVal, PMV);
941     return FinalVal;
942   }
943   default:
944     llvm_unreachable("Unknown atomic op");
945   }
946 }
947 
948 /// Expand a sub-word atomicrmw operation into an appropriate
949 /// word-sized operation.
950 ///
951 /// It will create an LL/SC or cmpxchg loop, as appropriate, the same
952 /// way as a typical atomicrmw expansion. The only difference here is
953 /// that the operation inside of the loop may operate upon only a
954 /// part of the value.
955 void AtomicExpandImpl::expandPartwordAtomicRMW(
956     AtomicRMWInst *AI, TargetLoweringBase::AtomicExpansionKind ExpansionKind) {
957   // Widen And/Or/Xor and give the target another chance at expanding it.
958   AtomicRMWInst::BinOp Op = AI->getOperation();
959   if (Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
960       Op == AtomicRMWInst::And) {
961     tryExpandAtomicRMW(widenPartwordAtomicRMW(AI));
962     return;
963   }
964   AtomicOrdering MemOpOrder = AI->getOrdering();
965   SyncScope::ID SSID = AI->getSyncScopeID();
966 
967   ReplacementIRBuilder Builder(AI, *DL);
968 
969   PartwordMaskValues PMV =
970       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
971                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
972 
973   Value *ValOperand_Shifted = nullptr;
974   if (Op == AtomicRMWInst::Xchg || Op == AtomicRMWInst::Add ||
975       Op == AtomicRMWInst::Sub || Op == AtomicRMWInst::Nand) {
976     Value *ValOp = Builder.CreateBitCast(AI->getValOperand(), PMV.IntValueType);
977     ValOperand_Shifted =
978         Builder.CreateShl(Builder.CreateZExt(ValOp, PMV.WordType), PMV.ShiftAmt,
979                           "ValOperand_Shifted");
980   }
981 
982   auto PerformPartwordOp = [&](IRBuilderBase &Builder, Value *Loaded) {
983     return performMaskedAtomicOp(Op, Builder, Loaded, ValOperand_Shifted,
984                                  AI->getValOperand(), PMV);
985   };
986 
987   Value *OldResult;
988   if (ExpansionKind == TargetLoweringBase::AtomicExpansionKind::CmpXChg) {
989     OldResult = insertRMWCmpXchgLoop(
990         Builder, PMV.WordType, PMV.AlignedAddr, PMV.AlignedAddrAlignment,
991         MemOpOrder, SSID, PerformPartwordOp, createCmpXchgInstFun, AI);
992   } else {
993     assert(ExpansionKind == TargetLoweringBase::AtomicExpansionKind::LLSC);
994     OldResult = insertRMWLLSCLoop(Builder, PMV.WordType, PMV.AlignedAddr,
995                                   PMV.AlignedAddrAlignment, MemOpOrder,
996                                   PerformPartwordOp);
997   }
998 
999   Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
1000   AI->replaceAllUsesWith(FinalOldResult);
1001   AI->eraseFromParent();
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, Instruction *MetadataSrc) {
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, MetadataSrc);
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   case TargetLoweringBase::AtomicExpansionKind::Expand: {
1676     TLI->emitExpandAtomicCmpXchg(CI);
1677     return true;
1678   }
1679   }
1680 }
1681 
1682 // Note: This function is exposed externally by AtomicExpandUtils.h
1683 bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
1684                                     CreateCmpXchgInstFun CreateCmpXchg) {
1685   ReplacementIRBuilder Builder(AI, AI->getDataLayout());
1686   Builder.setIsFPConstrained(
1687       AI->getFunction()->hasFnAttribute(Attribute::StrictFP));
1688 
1689   // FIXME: If FP exceptions are observable, we should force them off for the
1690   // loop for the FP atomics.
1691   Value *Loaded = AtomicExpandImpl::insertRMWCmpXchgLoop(
1692       Builder, AI->getType(), AI->getPointerOperand(), AI->getAlign(),
1693       AI->getOrdering(), AI->getSyncScopeID(),
1694       [&](IRBuilderBase &Builder, Value *Loaded) {
1695         return buildAtomicRMWValue(AI->getOperation(), Builder, Loaded,
1696                                    AI->getValOperand());
1697       },
1698       CreateCmpXchg, /*MetadataSrc=*/AI);
1699 
1700   AI->replaceAllUsesWith(Loaded);
1701   AI->eraseFromParent();
1702   return true;
1703 }
1704 
1705 // In order to use one of the sized library calls such as
1706 // __atomic_fetch_add_4, the alignment must be sufficient, the size
1707 // must be one of the potentially-specialized sizes, and the value
1708 // type must actually exist in C on the target (otherwise, the
1709 // function wouldn't actually be defined.)
1710 static bool canUseSizedAtomicCall(unsigned Size, Align Alignment,
1711                                   const DataLayout &DL) {
1712   // TODO: "LargestSize" is an approximation for "largest type that
1713   // you can express in C". It seems to be the case that int128 is
1714   // supported on all 64-bit platforms, otherwise only up to 64-bit
1715   // integers are supported. If we get this wrong, then we'll try to
1716   // call a sized libcall that doesn't actually exist. There should
1717   // really be some more reliable way in LLVM of determining integer
1718   // sizes which are valid in the target's C ABI...
1719   unsigned LargestSize = DL.getLargestLegalIntTypeSizeInBits() >= 64 ? 16 : 8;
1720   return Alignment >= Size &&
1721          (Size == 1 || Size == 2 || Size == 4 || Size == 8 || Size == 16) &&
1722          Size <= LargestSize;
1723 }
1724 
1725 void AtomicExpandImpl::expandAtomicLoadToLibcall(LoadInst *I) {
1726   static const RTLIB::Libcall Libcalls[6] = {
1727       RTLIB::ATOMIC_LOAD,   RTLIB::ATOMIC_LOAD_1, RTLIB::ATOMIC_LOAD_2,
1728       RTLIB::ATOMIC_LOAD_4, RTLIB::ATOMIC_LOAD_8, RTLIB::ATOMIC_LOAD_16};
1729   unsigned Size = getAtomicOpSize(I);
1730 
1731   bool expanded = expandAtomicOpToLibcall(
1732       I, Size, I->getAlign(), I->getPointerOperand(), nullptr, nullptr,
1733       I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1734   if (!expanded)
1735     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Load");
1736 }
1737 
1738 void AtomicExpandImpl::expandAtomicStoreToLibcall(StoreInst *I) {
1739   static const RTLIB::Libcall Libcalls[6] = {
1740       RTLIB::ATOMIC_STORE,   RTLIB::ATOMIC_STORE_1, RTLIB::ATOMIC_STORE_2,
1741       RTLIB::ATOMIC_STORE_4, RTLIB::ATOMIC_STORE_8, RTLIB::ATOMIC_STORE_16};
1742   unsigned Size = getAtomicOpSize(I);
1743 
1744   bool expanded = expandAtomicOpToLibcall(
1745       I, Size, I->getAlign(), I->getPointerOperand(), I->getValueOperand(),
1746       nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1747   if (!expanded)
1748     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Store");
1749 }
1750 
1751 void AtomicExpandImpl::expandAtomicCASToLibcall(AtomicCmpXchgInst *I) {
1752   static const RTLIB::Libcall Libcalls[6] = {
1753       RTLIB::ATOMIC_COMPARE_EXCHANGE,   RTLIB::ATOMIC_COMPARE_EXCHANGE_1,
1754       RTLIB::ATOMIC_COMPARE_EXCHANGE_2, RTLIB::ATOMIC_COMPARE_EXCHANGE_4,
1755       RTLIB::ATOMIC_COMPARE_EXCHANGE_8, RTLIB::ATOMIC_COMPARE_EXCHANGE_16};
1756   unsigned Size = getAtomicOpSize(I);
1757 
1758   bool expanded = expandAtomicOpToLibcall(
1759       I, Size, I->getAlign(), I->getPointerOperand(), I->getNewValOperand(),
1760       I->getCompareOperand(), I->getSuccessOrdering(), I->getFailureOrdering(),
1761       Libcalls);
1762   if (!expanded)
1763     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for CAS");
1764 }
1765 
1766 static ArrayRef<RTLIB::Libcall> GetRMWLibcall(AtomicRMWInst::BinOp Op) {
1767   static const RTLIB::Libcall LibcallsXchg[6] = {
1768       RTLIB::ATOMIC_EXCHANGE,   RTLIB::ATOMIC_EXCHANGE_1,
1769       RTLIB::ATOMIC_EXCHANGE_2, RTLIB::ATOMIC_EXCHANGE_4,
1770       RTLIB::ATOMIC_EXCHANGE_8, RTLIB::ATOMIC_EXCHANGE_16};
1771   static const RTLIB::Libcall LibcallsAdd[6] = {
1772       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_ADD_1,
1773       RTLIB::ATOMIC_FETCH_ADD_2, RTLIB::ATOMIC_FETCH_ADD_4,
1774       RTLIB::ATOMIC_FETCH_ADD_8, RTLIB::ATOMIC_FETCH_ADD_16};
1775   static const RTLIB::Libcall LibcallsSub[6] = {
1776       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_SUB_1,
1777       RTLIB::ATOMIC_FETCH_SUB_2, RTLIB::ATOMIC_FETCH_SUB_4,
1778       RTLIB::ATOMIC_FETCH_SUB_8, RTLIB::ATOMIC_FETCH_SUB_16};
1779   static const RTLIB::Libcall LibcallsAnd[6] = {
1780       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_AND_1,
1781       RTLIB::ATOMIC_FETCH_AND_2, RTLIB::ATOMIC_FETCH_AND_4,
1782       RTLIB::ATOMIC_FETCH_AND_8, RTLIB::ATOMIC_FETCH_AND_16};
1783   static const RTLIB::Libcall LibcallsOr[6] = {
1784       RTLIB::UNKNOWN_LIBCALL,   RTLIB::ATOMIC_FETCH_OR_1,
1785       RTLIB::ATOMIC_FETCH_OR_2, RTLIB::ATOMIC_FETCH_OR_4,
1786       RTLIB::ATOMIC_FETCH_OR_8, RTLIB::ATOMIC_FETCH_OR_16};
1787   static const RTLIB::Libcall LibcallsXor[6] = {
1788       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_XOR_1,
1789       RTLIB::ATOMIC_FETCH_XOR_2, RTLIB::ATOMIC_FETCH_XOR_4,
1790       RTLIB::ATOMIC_FETCH_XOR_8, RTLIB::ATOMIC_FETCH_XOR_16};
1791   static const RTLIB::Libcall LibcallsNand[6] = {
1792       RTLIB::UNKNOWN_LIBCALL,     RTLIB::ATOMIC_FETCH_NAND_1,
1793       RTLIB::ATOMIC_FETCH_NAND_2, RTLIB::ATOMIC_FETCH_NAND_4,
1794       RTLIB::ATOMIC_FETCH_NAND_8, RTLIB::ATOMIC_FETCH_NAND_16};
1795 
1796   switch (Op) {
1797   case AtomicRMWInst::BAD_BINOP:
1798     llvm_unreachable("Should not have BAD_BINOP.");
1799   case AtomicRMWInst::Xchg:
1800     return ArrayRef(LibcallsXchg);
1801   case AtomicRMWInst::Add:
1802     return ArrayRef(LibcallsAdd);
1803   case AtomicRMWInst::Sub:
1804     return ArrayRef(LibcallsSub);
1805   case AtomicRMWInst::And:
1806     return ArrayRef(LibcallsAnd);
1807   case AtomicRMWInst::Or:
1808     return ArrayRef(LibcallsOr);
1809   case AtomicRMWInst::Xor:
1810     return ArrayRef(LibcallsXor);
1811   case AtomicRMWInst::Nand:
1812     return ArrayRef(LibcallsNand);
1813   case AtomicRMWInst::Max:
1814   case AtomicRMWInst::Min:
1815   case AtomicRMWInst::UMax:
1816   case AtomicRMWInst::UMin:
1817   case AtomicRMWInst::FMax:
1818   case AtomicRMWInst::FMin:
1819   case AtomicRMWInst::FAdd:
1820   case AtomicRMWInst::FSub:
1821   case AtomicRMWInst::UIncWrap:
1822   case AtomicRMWInst::UDecWrap:
1823   case AtomicRMWInst::USubCond:
1824   case AtomicRMWInst::USubSat:
1825     // No atomic libcalls are available for these.
1826     return {};
1827   }
1828   llvm_unreachable("Unexpected AtomicRMW operation.");
1829 }
1830 
1831 void AtomicExpandImpl::expandAtomicRMWToLibcall(AtomicRMWInst *I) {
1832   ArrayRef<RTLIB::Libcall> Libcalls = GetRMWLibcall(I->getOperation());
1833 
1834   unsigned Size = getAtomicOpSize(I);
1835 
1836   bool Success = false;
1837   if (!Libcalls.empty())
1838     Success = expandAtomicOpToLibcall(
1839         I, Size, I->getAlign(), I->getPointerOperand(), I->getValOperand(),
1840         nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1841 
1842   // The expansion failed: either there were no libcalls at all for
1843   // the operation (min/max), or there were only size-specialized
1844   // libcalls (add/sub/etc) and we needed a generic. So, expand to a
1845   // CAS libcall, via a CAS loop, instead.
1846   if (!Success) {
1847     expandAtomicRMWToCmpXchg(
1848         I, [this](IRBuilderBase &Builder, Value *Addr, Value *Loaded,
1849                   Value *NewVal, Align Alignment, AtomicOrdering MemOpOrder,
1850                   SyncScope::ID SSID, Value *&Success, Value *&NewLoaded,
1851                   Instruction *MetadataSrc) {
1852           // Create the CAS instruction normally...
1853           AtomicCmpXchgInst *Pair = Builder.CreateAtomicCmpXchg(
1854               Addr, Loaded, NewVal, Alignment, MemOpOrder,
1855               AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
1856           if (MetadataSrc)
1857             copyMetadataForAtomic(*Pair, *MetadataSrc);
1858 
1859           Success = Builder.CreateExtractValue(Pair, 1, "success");
1860           NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
1861 
1862           // ...and then expand the CAS into a libcall.
1863           expandAtomicCASToLibcall(Pair);
1864         });
1865   }
1866 }
1867 
1868 // A helper routine for the above expandAtomic*ToLibcall functions.
1869 //
1870 // 'Libcalls' contains an array of enum values for the particular
1871 // ATOMIC libcalls to be emitted. All of the other arguments besides
1872 // 'I' are extracted from the Instruction subclass by the
1873 // caller. Depending on the particular call, some will be null.
1874 bool AtomicExpandImpl::expandAtomicOpToLibcall(
1875     Instruction *I, unsigned Size, Align Alignment, Value *PointerOperand,
1876     Value *ValueOperand, Value *CASExpected, AtomicOrdering Ordering,
1877     AtomicOrdering Ordering2, ArrayRef<RTLIB::Libcall> Libcalls) {
1878   assert(Libcalls.size() == 6);
1879 
1880   LLVMContext &Ctx = I->getContext();
1881   Module *M = I->getModule();
1882   const DataLayout &DL = M->getDataLayout();
1883   IRBuilder<> Builder(I);
1884   IRBuilder<> AllocaBuilder(&I->getFunction()->getEntryBlock().front());
1885 
1886   bool UseSizedLibcall = canUseSizedAtomicCall(Size, Alignment, DL);
1887   Type *SizedIntTy = Type::getIntNTy(Ctx, Size * 8);
1888 
1889   const Align AllocaAlignment = DL.getPrefTypeAlign(SizedIntTy);
1890 
1891   // TODO: the "order" argument type is "int", not int32. So
1892   // getInt32Ty may be wrong if the arch uses e.g. 16-bit ints.
1893   ConstantInt *SizeVal64 = ConstantInt::get(Type::getInt64Ty(Ctx), Size);
1894   assert(Ordering != AtomicOrdering::NotAtomic && "expect atomic MO");
1895   Constant *OrderingVal =
1896       ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering));
1897   Constant *Ordering2Val = nullptr;
1898   if (CASExpected) {
1899     assert(Ordering2 != AtomicOrdering::NotAtomic && "expect atomic MO");
1900     Ordering2Val =
1901         ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering2));
1902   }
1903   bool HasResult = I->getType() != Type::getVoidTy(Ctx);
1904 
1905   RTLIB::Libcall RTLibType;
1906   if (UseSizedLibcall) {
1907     switch (Size) {
1908     case 1:
1909       RTLibType = Libcalls[1];
1910       break;
1911     case 2:
1912       RTLibType = Libcalls[2];
1913       break;
1914     case 4:
1915       RTLibType = Libcalls[3];
1916       break;
1917     case 8:
1918       RTLibType = Libcalls[4];
1919       break;
1920     case 16:
1921       RTLibType = Libcalls[5];
1922       break;
1923     }
1924   } else if (Libcalls[0] != RTLIB::UNKNOWN_LIBCALL) {
1925     RTLibType = Libcalls[0];
1926   } else {
1927     // Can't use sized function, and there's no generic for this
1928     // operation, so give up.
1929     return false;
1930   }
1931 
1932   if (!TLI->getLibcallName(RTLibType)) {
1933     // This target does not implement the requested atomic libcall so give up.
1934     return false;
1935   }
1936 
1937   // Build up the function call. There's two kinds. First, the sized
1938   // variants.  These calls are going to be one of the following (with
1939   // N=1,2,4,8,16):
1940   //  iN    __atomic_load_N(iN *ptr, int ordering)
1941   //  void  __atomic_store_N(iN *ptr, iN val, int ordering)
1942   //  iN    __atomic_{exchange|fetch_*}_N(iN *ptr, iN val, int ordering)
1943   //  bool  __atomic_compare_exchange_N(iN *ptr, iN *expected, iN desired,
1944   //                                    int success_order, int failure_order)
1945   //
1946   // Note that these functions can be used for non-integer atomic
1947   // operations, the values just need to be bitcast to integers on the
1948   // way in and out.
1949   //
1950   // And, then, the generic variants. They look like the following:
1951   //  void  __atomic_load(size_t size, void *ptr, void *ret, int ordering)
1952   //  void  __atomic_store(size_t size, void *ptr, void *val, int ordering)
1953   //  void  __atomic_exchange(size_t size, void *ptr, void *val, void *ret,
1954   //                          int ordering)
1955   //  bool  __atomic_compare_exchange(size_t size, void *ptr, void *expected,
1956   //                                  void *desired, int success_order,
1957   //                                  int failure_order)
1958   //
1959   // The different signatures are built up depending on the
1960   // 'UseSizedLibcall', 'CASExpected', 'ValueOperand', and 'HasResult'
1961   // variables.
1962 
1963   AllocaInst *AllocaCASExpected = nullptr;
1964   AllocaInst *AllocaValue = nullptr;
1965   AllocaInst *AllocaResult = nullptr;
1966 
1967   Type *ResultTy;
1968   SmallVector<Value *, 6> Args;
1969   AttributeList Attr;
1970 
1971   // 'size' argument.
1972   if (!UseSizedLibcall) {
1973     // Note, getIntPtrType is assumed equivalent to size_t.
1974     Args.push_back(ConstantInt::get(DL.getIntPtrType(Ctx), Size));
1975   }
1976 
1977   // 'ptr' argument.
1978   // note: This assumes all address spaces share a common libfunc
1979   // implementation and that addresses are convertable.  For systems without
1980   // that property, we'd need to extend this mechanism to support AS-specific
1981   // families of atomic intrinsics.
1982   Value *PtrVal = PointerOperand;
1983   PtrVal = Builder.CreateAddrSpaceCast(PtrVal, PointerType::getUnqual(Ctx));
1984   Args.push_back(PtrVal);
1985 
1986   // 'expected' argument, if present.
1987   if (CASExpected) {
1988     AllocaCASExpected = AllocaBuilder.CreateAlloca(CASExpected->getType());
1989     AllocaCASExpected->setAlignment(AllocaAlignment);
1990     Builder.CreateLifetimeStart(AllocaCASExpected, SizeVal64);
1991     Builder.CreateAlignedStore(CASExpected, AllocaCASExpected, AllocaAlignment);
1992     Args.push_back(AllocaCASExpected);
1993   }
1994 
1995   // 'val' argument ('desired' for cas), if present.
1996   if (ValueOperand) {
1997     if (UseSizedLibcall) {
1998       Value *IntValue =
1999           Builder.CreateBitOrPointerCast(ValueOperand, SizedIntTy);
2000       Args.push_back(IntValue);
2001     } else {
2002       AllocaValue = AllocaBuilder.CreateAlloca(ValueOperand->getType());
2003       AllocaValue->setAlignment(AllocaAlignment);
2004       Builder.CreateLifetimeStart(AllocaValue, SizeVal64);
2005       Builder.CreateAlignedStore(ValueOperand, AllocaValue, AllocaAlignment);
2006       Args.push_back(AllocaValue);
2007     }
2008   }
2009 
2010   // 'ret' argument.
2011   if (!CASExpected && HasResult && !UseSizedLibcall) {
2012     AllocaResult = AllocaBuilder.CreateAlloca(I->getType());
2013     AllocaResult->setAlignment(AllocaAlignment);
2014     Builder.CreateLifetimeStart(AllocaResult, SizeVal64);
2015     Args.push_back(AllocaResult);
2016   }
2017 
2018   // 'ordering' ('success_order' for cas) argument.
2019   Args.push_back(OrderingVal);
2020 
2021   // 'failure_order' argument, if present.
2022   if (Ordering2Val)
2023     Args.push_back(Ordering2Val);
2024 
2025   // Now, the return type.
2026   if (CASExpected) {
2027     ResultTy = Type::getInt1Ty(Ctx);
2028     Attr = Attr.addRetAttribute(Ctx, Attribute::ZExt);
2029   } else if (HasResult && UseSizedLibcall)
2030     ResultTy = SizedIntTy;
2031   else
2032     ResultTy = Type::getVoidTy(Ctx);
2033 
2034   // Done with setting up arguments and return types, create the call:
2035   SmallVector<Type *, 6> ArgTys;
2036   for (Value *Arg : Args)
2037     ArgTys.push_back(Arg->getType());
2038   FunctionType *FnType = FunctionType::get(ResultTy, ArgTys, false);
2039   FunctionCallee LibcallFn =
2040       M->getOrInsertFunction(TLI->getLibcallName(RTLibType), FnType, Attr);
2041   CallInst *Call = Builder.CreateCall(LibcallFn, Args);
2042   Call->setAttributes(Attr);
2043   Value *Result = Call;
2044 
2045   // And then, extract the results...
2046   if (ValueOperand && !UseSizedLibcall)
2047     Builder.CreateLifetimeEnd(AllocaValue, SizeVal64);
2048 
2049   if (CASExpected) {
2050     // The final result from the CAS is {load of 'expected' alloca, bool result
2051     // from call}
2052     Type *FinalResultTy = I->getType();
2053     Value *V = PoisonValue::get(FinalResultTy);
2054     Value *ExpectedOut = Builder.CreateAlignedLoad(
2055         CASExpected->getType(), AllocaCASExpected, AllocaAlignment);
2056     Builder.CreateLifetimeEnd(AllocaCASExpected, SizeVal64);
2057     V = Builder.CreateInsertValue(V, ExpectedOut, 0);
2058     V = Builder.CreateInsertValue(V, Result, 1);
2059     I->replaceAllUsesWith(V);
2060   } else if (HasResult) {
2061     Value *V;
2062     if (UseSizedLibcall)
2063       V = Builder.CreateBitOrPointerCast(Result, I->getType());
2064     else {
2065       V = Builder.CreateAlignedLoad(I->getType(), AllocaResult,
2066                                     AllocaAlignment);
2067       Builder.CreateLifetimeEnd(AllocaResult, SizeVal64);
2068     }
2069     I->replaceAllUsesWith(V);
2070   }
2071   I->eraseFromParent();
2072   return true;
2073 }
2074