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