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