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