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