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