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