1 //===--- CGAtomic.cpp - Emit LLVM IR for atomic operations ----------------===//
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 the code for emitting atomic operations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGCall.h"
14 #include "CGRecordLayout.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/CodeGen/CGFunctionInfo.h"
20 #include "clang/Frontend/FrontendDiagnostic.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Intrinsics.h"
24 #include "llvm/IR/Operator.h"
25 
26 using namespace clang;
27 using namespace CodeGen;
28 
29 namespace {
30   class AtomicInfo {
31     CodeGenFunction &CGF;
32     QualType AtomicTy;
33     QualType ValueTy;
34     uint64_t AtomicSizeInBits;
35     uint64_t ValueSizeInBits;
36     CharUnits AtomicAlign;
37     CharUnits ValueAlign;
38     TypeEvaluationKind EvaluationKind;
39     bool UseLibcall;
40     LValue LVal;
41     CGBitFieldInfo BFI;
42   public:
43     AtomicInfo(CodeGenFunction &CGF, LValue &lvalue)
44         : CGF(CGF), AtomicSizeInBits(0), ValueSizeInBits(0),
45           EvaluationKind(TEK_Scalar), UseLibcall(true) {
46       assert(!lvalue.isGlobalReg());
47       ASTContext &C = CGF.getContext();
48       if (lvalue.isSimple()) {
49         AtomicTy = lvalue.getType();
50         if (auto *ATy = AtomicTy->getAs<AtomicType>())
51           ValueTy = ATy->getValueType();
52         else
53           ValueTy = AtomicTy;
54         EvaluationKind = CGF.getEvaluationKind(ValueTy);
55 
56         uint64_t ValueAlignInBits;
57         uint64_t AtomicAlignInBits;
58         TypeInfo ValueTI = C.getTypeInfo(ValueTy);
59         ValueSizeInBits = ValueTI.Width;
60         ValueAlignInBits = ValueTI.Align;
61 
62         TypeInfo AtomicTI = C.getTypeInfo(AtomicTy);
63         AtomicSizeInBits = AtomicTI.Width;
64         AtomicAlignInBits = AtomicTI.Align;
65 
66         assert(ValueSizeInBits <= AtomicSizeInBits);
67         assert(ValueAlignInBits <= AtomicAlignInBits);
68 
69         AtomicAlign = C.toCharUnitsFromBits(AtomicAlignInBits);
70         ValueAlign = C.toCharUnitsFromBits(ValueAlignInBits);
71         if (lvalue.getAlignment().isZero())
72           lvalue.setAlignment(AtomicAlign);
73 
74         LVal = lvalue;
75       } else if (lvalue.isBitField()) {
76         ValueTy = lvalue.getType();
77         ValueSizeInBits = C.getTypeSize(ValueTy);
78         auto &OrigBFI = lvalue.getBitFieldInfo();
79         auto Offset = OrigBFI.Offset % C.toBits(lvalue.getAlignment());
80         AtomicSizeInBits = C.toBits(
81             C.toCharUnitsFromBits(Offset + OrigBFI.Size + C.getCharWidth() - 1)
82                 .alignTo(lvalue.getAlignment()));
83         auto VoidPtrAddr = CGF.EmitCastToVoidPtr(lvalue.getBitFieldPointer());
84         auto OffsetInChars =
85             (C.toCharUnitsFromBits(OrigBFI.Offset) / lvalue.getAlignment()) *
86             lvalue.getAlignment();
87         VoidPtrAddr = CGF.Builder.CreateConstGEP1_64(
88             CGF.Int8Ty, VoidPtrAddr, OffsetInChars.getQuantity());
89         auto Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
90             VoidPtrAddr,
91             CGF.Builder.getIntNTy(AtomicSizeInBits)->getPointerTo(),
92             "atomic_bitfield_base");
93         BFI = OrigBFI;
94         BFI.Offset = Offset;
95         BFI.StorageSize = AtomicSizeInBits;
96         BFI.StorageOffset += OffsetInChars;
97         LVal = LValue::MakeBitfield(Address(Addr, lvalue.getAlignment()),
98                                     BFI, lvalue.getType(), lvalue.getBaseInfo(),
99                                     lvalue.getTBAAInfo());
100         AtomicTy = C.getIntTypeForBitwidth(AtomicSizeInBits, OrigBFI.IsSigned);
101         if (AtomicTy.isNull()) {
102           llvm::APInt Size(
103               /*numBits=*/32,
104               C.toCharUnitsFromBits(AtomicSizeInBits).getQuantity());
105           AtomicTy =
106               C.getConstantArrayType(C.CharTy, Size, nullptr, ArrayType::Normal,
107                                      /*IndexTypeQuals=*/0);
108         }
109         AtomicAlign = ValueAlign = lvalue.getAlignment();
110       } else if (lvalue.isVectorElt()) {
111         ValueTy = lvalue.getType()->castAs<VectorType>()->getElementType();
112         ValueSizeInBits = C.getTypeSize(ValueTy);
113         AtomicTy = lvalue.getType();
114         AtomicSizeInBits = C.getTypeSize(AtomicTy);
115         AtomicAlign = ValueAlign = lvalue.getAlignment();
116         LVal = lvalue;
117       } else {
118         assert(lvalue.isExtVectorElt());
119         ValueTy = lvalue.getType();
120         ValueSizeInBits = C.getTypeSize(ValueTy);
121         AtomicTy = ValueTy = CGF.getContext().getExtVectorType(
122             lvalue.getType(), cast<llvm::FixedVectorType>(
123                                   lvalue.getExtVectorAddress().getElementType())
124                                   ->getNumElements());
125         AtomicSizeInBits = C.getTypeSize(AtomicTy);
126         AtomicAlign = ValueAlign = lvalue.getAlignment();
127         LVal = lvalue;
128       }
129       UseLibcall = !C.getTargetInfo().hasBuiltinAtomic(
130           AtomicSizeInBits, C.toBits(lvalue.getAlignment()));
131     }
132 
133     QualType getAtomicType() const { return AtomicTy; }
134     QualType getValueType() const { return ValueTy; }
135     CharUnits getAtomicAlignment() const { return AtomicAlign; }
136     uint64_t getAtomicSizeInBits() const { return AtomicSizeInBits; }
137     uint64_t getValueSizeInBits() const { return ValueSizeInBits; }
138     TypeEvaluationKind getEvaluationKind() const { return EvaluationKind; }
139     bool shouldUseLibcall() const { return UseLibcall; }
140     const LValue &getAtomicLValue() const { return LVal; }
141     llvm::Value *getAtomicPointer() const {
142       if (LVal.isSimple())
143         return LVal.getPointer(CGF);
144       else if (LVal.isBitField())
145         return LVal.getBitFieldPointer();
146       else if (LVal.isVectorElt())
147         return LVal.getVectorPointer();
148       assert(LVal.isExtVectorElt());
149       return LVal.getExtVectorPointer();
150     }
151     Address getAtomicAddress() const {
152       return Address(getAtomicPointer(), getAtomicAlignment());
153     }
154 
155     Address getAtomicAddressAsAtomicIntPointer() const {
156       return emitCastToAtomicIntPointer(getAtomicAddress());
157     }
158 
159     /// Is the atomic size larger than the underlying value type?
160     ///
161     /// Note that the absence of padding does not mean that atomic
162     /// objects are completely interchangeable with non-atomic
163     /// objects: we might have promoted the alignment of a type
164     /// without making it bigger.
165     bool hasPadding() const {
166       return (ValueSizeInBits != AtomicSizeInBits);
167     }
168 
169     bool emitMemSetZeroIfNecessary() const;
170 
171     llvm::Value *getAtomicSizeValue() const {
172       CharUnits size = CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits);
173       return CGF.CGM.getSize(size);
174     }
175 
176     /// Cast the given pointer to an integer pointer suitable for atomic
177     /// operations if the source.
178     Address emitCastToAtomicIntPointer(Address Addr) const;
179 
180     /// If Addr is compatible with the iN that will be used for an atomic
181     /// operation, bitcast it. Otherwise, create a temporary that is suitable
182     /// and copy the value across.
183     Address convertToAtomicIntPointer(Address Addr) const;
184 
185     /// Turn an atomic-layout object into an r-value.
186     RValue convertAtomicTempToRValue(Address addr, AggValueSlot resultSlot,
187                                      SourceLocation loc, bool AsValue) const;
188 
189     /// Converts a rvalue to integer value.
190     llvm::Value *convertRValueToInt(RValue RVal) const;
191 
192     RValue ConvertIntToValueOrAtomic(llvm::Value *IntVal,
193                                      AggValueSlot ResultSlot,
194                                      SourceLocation Loc, bool AsValue) const;
195 
196     /// Copy an atomic r-value into atomic-layout memory.
197     void emitCopyIntoMemory(RValue rvalue) const;
198 
199     /// Project an l-value down to the value field.
200     LValue projectValue() const {
201       assert(LVal.isSimple());
202       Address addr = getAtomicAddress();
203       if (hasPadding())
204         addr = CGF.Builder.CreateStructGEP(addr, 0);
205 
206       return LValue::MakeAddr(addr, getValueType(), CGF.getContext(),
207                               LVal.getBaseInfo(), LVal.getTBAAInfo());
208     }
209 
210     /// Emits atomic load.
211     /// \returns Loaded value.
212     RValue EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
213                           bool AsValue, llvm::AtomicOrdering AO,
214                           bool IsVolatile);
215 
216     /// Emits atomic compare-and-exchange sequence.
217     /// \param Expected Expected value.
218     /// \param Desired Desired value.
219     /// \param Success Atomic ordering for success operation.
220     /// \param Failure Atomic ordering for failed operation.
221     /// \param IsWeak true if atomic operation is weak, false otherwise.
222     /// \returns Pair of values: previous value from storage (value type) and
223     /// boolean flag (i1 type) with true if success and false otherwise.
224     std::pair<RValue, llvm::Value *>
225     EmitAtomicCompareExchange(RValue Expected, RValue Desired,
226                               llvm::AtomicOrdering Success =
227                                   llvm::AtomicOrdering::SequentiallyConsistent,
228                               llvm::AtomicOrdering Failure =
229                                   llvm::AtomicOrdering::SequentiallyConsistent,
230                               bool IsWeak = false);
231 
232     /// Emits atomic update.
233     /// \param AO Atomic ordering.
234     /// \param UpdateOp Update operation for the current lvalue.
235     void EmitAtomicUpdate(llvm::AtomicOrdering AO,
236                           const llvm::function_ref<RValue(RValue)> &UpdateOp,
237                           bool IsVolatile);
238     /// Emits atomic update.
239     /// \param AO Atomic ordering.
240     void EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
241                           bool IsVolatile);
242 
243     /// Materialize an atomic r-value in atomic-layout memory.
244     Address materializeRValue(RValue rvalue) const;
245 
246     /// Creates temp alloca for intermediate operations on atomic value.
247     Address CreateTempAlloca() const;
248   private:
249     bool requiresMemSetZero(llvm::Type *type) const;
250 
251 
252     /// Emits atomic load as a libcall.
253     void EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
254                                llvm::AtomicOrdering AO, bool IsVolatile);
255     /// Emits atomic load as LLVM instruction.
256     llvm::Value *EmitAtomicLoadOp(llvm::AtomicOrdering AO, bool IsVolatile);
257     /// Emits atomic compare-and-exchange op as a libcall.
258     llvm::Value *EmitAtomicCompareExchangeLibcall(
259         llvm::Value *ExpectedAddr, llvm::Value *DesiredAddr,
260         llvm::AtomicOrdering Success =
261             llvm::AtomicOrdering::SequentiallyConsistent,
262         llvm::AtomicOrdering Failure =
263             llvm::AtomicOrdering::SequentiallyConsistent);
264     /// Emits atomic compare-and-exchange op as LLVM instruction.
265     std::pair<llvm::Value *, llvm::Value *> EmitAtomicCompareExchangeOp(
266         llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
267         llvm::AtomicOrdering Success =
268             llvm::AtomicOrdering::SequentiallyConsistent,
269         llvm::AtomicOrdering Failure =
270             llvm::AtomicOrdering::SequentiallyConsistent,
271         bool IsWeak = false);
272     /// Emit atomic update as libcalls.
273     void
274     EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
275                             const llvm::function_ref<RValue(RValue)> &UpdateOp,
276                             bool IsVolatile);
277     /// Emit atomic update as LLVM instructions.
278     void EmitAtomicUpdateOp(llvm::AtomicOrdering AO,
279                             const llvm::function_ref<RValue(RValue)> &UpdateOp,
280                             bool IsVolatile);
281     /// Emit atomic update as libcalls.
282     void EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO, RValue UpdateRVal,
283                                  bool IsVolatile);
284     /// Emit atomic update as LLVM instructions.
285     void EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRal,
286                             bool IsVolatile);
287   };
288 }
289 
290 Address AtomicInfo::CreateTempAlloca() const {
291   Address TempAlloca = CGF.CreateMemTemp(
292       (LVal.isBitField() && ValueSizeInBits > AtomicSizeInBits) ? ValueTy
293                                                                 : AtomicTy,
294       getAtomicAlignment(),
295       "atomic-temp");
296   // Cast to pointer to value type for bitfields.
297   if (LVal.isBitField())
298     return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
299         TempAlloca, getAtomicAddress().getType());
300   return TempAlloca;
301 }
302 
303 static RValue emitAtomicLibcall(CodeGenFunction &CGF,
304                                 StringRef fnName,
305                                 QualType resultType,
306                                 CallArgList &args) {
307   const CGFunctionInfo &fnInfo =
308     CGF.CGM.getTypes().arrangeBuiltinFunctionCall(resultType, args);
309   llvm::FunctionType *fnTy = CGF.CGM.getTypes().GetFunctionType(fnInfo);
310   llvm::AttrBuilder fnAttrB;
311   fnAttrB.addAttribute(llvm::Attribute::NoUnwind);
312   fnAttrB.addAttribute(llvm::Attribute::WillReturn);
313   llvm::AttributeList fnAttrs = llvm::AttributeList::get(
314       CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, fnAttrB);
315 
316   llvm::FunctionCallee fn =
317       CGF.CGM.CreateRuntimeFunction(fnTy, fnName, fnAttrs);
318   auto callee = CGCallee::forDirect(fn);
319   return CGF.EmitCall(fnInfo, callee, ReturnValueSlot(), args);
320 }
321 
322 /// Does a store of the given IR type modify the full expected width?
323 static bool isFullSizeType(CodeGenModule &CGM, llvm::Type *type,
324                            uint64_t expectedSize) {
325   return (CGM.getDataLayout().getTypeStoreSize(type) * 8 == expectedSize);
326 }
327 
328 /// Does the atomic type require memsetting to zero before initialization?
329 ///
330 /// The IR type is provided as a way of making certain queries faster.
331 bool AtomicInfo::requiresMemSetZero(llvm::Type *type) const {
332   // If the atomic type has size padding, we definitely need a memset.
333   if (hasPadding()) return true;
334 
335   // Otherwise, do some simple heuristics to try to avoid it:
336   switch (getEvaluationKind()) {
337   // For scalars and complexes, check whether the store size of the
338   // type uses the full size.
339   case TEK_Scalar:
340     return !isFullSizeType(CGF.CGM, type, AtomicSizeInBits);
341   case TEK_Complex:
342     return !isFullSizeType(CGF.CGM, type->getStructElementType(0),
343                            AtomicSizeInBits / 2);
344 
345   // Padding in structs has an undefined bit pattern.  User beware.
346   case TEK_Aggregate:
347     return false;
348   }
349   llvm_unreachable("bad evaluation kind");
350 }
351 
352 bool AtomicInfo::emitMemSetZeroIfNecessary() const {
353   assert(LVal.isSimple());
354   llvm::Value *addr = LVal.getPointer(CGF);
355   if (!requiresMemSetZero(addr->getType()->getPointerElementType()))
356     return false;
357 
358   CGF.Builder.CreateMemSet(
359       addr, llvm::ConstantInt::get(CGF.Int8Ty, 0),
360       CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits).getQuantity(),
361       LVal.getAlignment().getAsAlign());
362   return true;
363 }
364 
365 static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak,
366                               Address Dest, Address Ptr,
367                               Address Val1, Address Val2,
368                               uint64_t Size,
369                               llvm::AtomicOrdering SuccessOrder,
370                               llvm::AtomicOrdering FailureOrder,
371                               llvm::SyncScope::ID Scope) {
372   // Note that cmpxchg doesn't support weak cmpxchg, at least at the moment.
373   llvm::Value *Expected = CGF.Builder.CreateLoad(Val1);
374   llvm::Value *Desired = CGF.Builder.CreateLoad(Val2);
375 
376   llvm::AtomicCmpXchgInst *Pair = CGF.Builder.CreateAtomicCmpXchg(
377       Ptr.getPointer(), Expected, Desired, SuccessOrder, FailureOrder,
378       Scope);
379   Pair->setVolatile(E->isVolatile());
380   Pair->setWeak(IsWeak);
381 
382   // Cmp holds the result of the compare-exchange operation: true on success,
383   // false on failure.
384   llvm::Value *Old = CGF.Builder.CreateExtractValue(Pair, 0);
385   llvm::Value *Cmp = CGF.Builder.CreateExtractValue(Pair, 1);
386 
387   // This basic block is used to hold the store instruction if the operation
388   // failed.
389   llvm::BasicBlock *StoreExpectedBB =
390       CGF.createBasicBlock("cmpxchg.store_expected", CGF.CurFn);
391 
392   // This basic block is the exit point of the operation, we should end up
393   // here regardless of whether or not the operation succeeded.
394   llvm::BasicBlock *ContinueBB =
395       CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
396 
397   // Update Expected if Expected isn't equal to Old, otherwise branch to the
398   // exit point.
399   CGF.Builder.CreateCondBr(Cmp, ContinueBB, StoreExpectedBB);
400 
401   CGF.Builder.SetInsertPoint(StoreExpectedBB);
402   // Update the memory at Expected with Old's value.
403   CGF.Builder.CreateStore(Old, Val1);
404   // Finally, branch to the exit point.
405   CGF.Builder.CreateBr(ContinueBB);
406 
407   CGF.Builder.SetInsertPoint(ContinueBB);
408   // Update the memory at Dest with Cmp's value.
409   CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
410 }
411 
412 /// Given an ordering required on success, emit all possible cmpxchg
413 /// instructions to cope with the provided (but possibly only dynamically known)
414 /// FailureOrder.
415 static void emitAtomicCmpXchgFailureSet(CodeGenFunction &CGF, AtomicExpr *E,
416                                         bool IsWeak, Address Dest, Address Ptr,
417                                         Address Val1, Address Val2,
418                                         llvm::Value *FailureOrderVal,
419                                         uint64_t Size,
420                                         llvm::AtomicOrdering SuccessOrder,
421                                         llvm::SyncScope::ID Scope) {
422   llvm::AtomicOrdering FailureOrder;
423   if (llvm::ConstantInt *FO = dyn_cast<llvm::ConstantInt>(FailureOrderVal)) {
424     auto FOS = FO->getSExtValue();
425     if (!llvm::isValidAtomicOrderingCABI(FOS))
426       FailureOrder = llvm::AtomicOrdering::Monotonic;
427     else
428       switch ((llvm::AtomicOrderingCABI)FOS) {
429       case llvm::AtomicOrderingCABI::relaxed:
430       // 31.7.2.18: "The failure argument shall not be memory_order_release
431       // nor memory_order_acq_rel". Fallback to monotonic.
432       case llvm::AtomicOrderingCABI::release:
433       case llvm::AtomicOrderingCABI::acq_rel:
434         FailureOrder = llvm::AtomicOrdering::Monotonic;
435         break;
436       case llvm::AtomicOrderingCABI::consume:
437       case llvm::AtomicOrderingCABI::acquire:
438         FailureOrder = llvm::AtomicOrdering::Acquire;
439         break;
440       case llvm::AtomicOrderingCABI::seq_cst:
441         FailureOrder = llvm::AtomicOrdering::SequentiallyConsistent;
442         break;
443       }
444     // Prior to c++17, "the failure argument shall be no stronger than the
445     // success argument". This condition has been lifted and the only
446     // precondition is 31.7.2.18. Effectively treat this as a DR and skip
447     // language version checks.
448     emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
449                       FailureOrder, Scope);
450     return;
451   }
452 
453   // Create all the relevant BB's
454   auto *MonotonicBB = CGF.createBasicBlock("monotonic_fail", CGF.CurFn);
455   auto *AcquireBB = CGF.createBasicBlock("acquire_fail", CGF.CurFn);
456   auto *SeqCstBB = CGF.createBasicBlock("seqcst_fail", CGF.CurFn);
457   auto *ContBB = CGF.createBasicBlock("atomic.continue", CGF.CurFn);
458 
459   // MonotonicBB is arbitrarily chosen as the default case; in practice, this
460   // doesn't matter unless someone is crazy enough to use something that
461   // doesn't fold to a constant for the ordering.
462   llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(FailureOrderVal, MonotonicBB);
463   // Implemented as acquire, since it's the closest in LLVM.
464   SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
465               AcquireBB);
466   SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
467               AcquireBB);
468   SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
469               SeqCstBB);
470 
471   // Emit all the different atomics
472   CGF.Builder.SetInsertPoint(MonotonicBB);
473   emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
474                     Size, SuccessOrder, llvm::AtomicOrdering::Monotonic, Scope);
475   CGF.Builder.CreateBr(ContBB);
476 
477   CGF.Builder.SetInsertPoint(AcquireBB);
478   emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
479                     llvm::AtomicOrdering::Acquire, Scope);
480   CGF.Builder.CreateBr(ContBB);
481 
482   CGF.Builder.SetInsertPoint(SeqCstBB);
483   emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
484                     llvm::AtomicOrdering::SequentiallyConsistent, Scope);
485   CGF.Builder.CreateBr(ContBB);
486 
487   CGF.Builder.SetInsertPoint(ContBB);
488 }
489 
490 /// Duplicate the atomic min/max operation in conventional IR for the builtin
491 /// variants that return the new rather than the original value.
492 static llvm::Value *EmitPostAtomicMinMax(CGBuilderTy &Builder,
493                                          AtomicExpr::AtomicOp Op,
494                                          bool IsSigned,
495                                          llvm::Value *OldVal,
496                                          llvm::Value *RHS) {
497   llvm::CmpInst::Predicate Pred;
498   switch (Op) {
499   default:
500     llvm_unreachable("Unexpected min/max operation");
501   case AtomicExpr::AO__atomic_max_fetch:
502     Pred = IsSigned ? llvm::CmpInst::ICMP_SGT : llvm::CmpInst::ICMP_UGT;
503     break;
504   case AtomicExpr::AO__atomic_min_fetch:
505     Pred = IsSigned ? llvm::CmpInst::ICMP_SLT : llvm::CmpInst::ICMP_ULT;
506     break;
507   }
508   llvm::Value *Cmp = Builder.CreateICmp(Pred, OldVal, RHS, "tst");
509   return Builder.CreateSelect(Cmp, OldVal, RHS, "newval");
510 }
511 
512 static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest,
513                          Address Ptr, Address Val1, Address Val2,
514                          llvm::Value *IsWeak, llvm::Value *FailureOrder,
515                          uint64_t Size, llvm::AtomicOrdering Order,
516                          llvm::SyncScope::ID Scope) {
517   llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
518   bool PostOpMinMax = false;
519   unsigned PostOp = 0;
520 
521   switch (E->getOp()) {
522   case AtomicExpr::AO__c11_atomic_init:
523   case AtomicExpr::AO__opencl_atomic_init:
524     llvm_unreachable("Already handled!");
525 
526   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
527   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
528   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
529     emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
530                                 FailureOrder, Size, Order, Scope);
531     return;
532   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
533   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
534     emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
535                                 FailureOrder, Size, Order, Scope);
536     return;
537   case AtomicExpr::AO__atomic_compare_exchange:
538   case AtomicExpr::AO__atomic_compare_exchange_n: {
539     if (llvm::ConstantInt *IsWeakC = dyn_cast<llvm::ConstantInt>(IsWeak)) {
540       emitAtomicCmpXchgFailureSet(CGF, E, IsWeakC->getZExtValue(), Dest, Ptr,
541                                   Val1, Val2, FailureOrder, Size, Order, Scope);
542     } else {
543       // Create all the relevant BB's
544       llvm::BasicBlock *StrongBB =
545           CGF.createBasicBlock("cmpxchg.strong", CGF.CurFn);
546       llvm::BasicBlock *WeakBB = CGF.createBasicBlock("cmxchg.weak", CGF.CurFn);
547       llvm::BasicBlock *ContBB =
548           CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
549 
550       llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(IsWeak, WeakBB);
551       SI->addCase(CGF.Builder.getInt1(false), StrongBB);
552 
553       CGF.Builder.SetInsertPoint(StrongBB);
554       emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
555                                   FailureOrder, Size, Order, Scope);
556       CGF.Builder.CreateBr(ContBB);
557 
558       CGF.Builder.SetInsertPoint(WeakBB);
559       emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
560                                   FailureOrder, Size, Order, Scope);
561       CGF.Builder.CreateBr(ContBB);
562 
563       CGF.Builder.SetInsertPoint(ContBB);
564     }
565     return;
566   }
567   case AtomicExpr::AO__c11_atomic_load:
568   case AtomicExpr::AO__opencl_atomic_load:
569   case AtomicExpr::AO__atomic_load_n:
570   case AtomicExpr::AO__atomic_load: {
571     llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
572     Load->setAtomic(Order, Scope);
573     Load->setVolatile(E->isVolatile());
574     CGF.Builder.CreateStore(Load, Dest);
575     return;
576   }
577 
578   case AtomicExpr::AO__c11_atomic_store:
579   case AtomicExpr::AO__opencl_atomic_store:
580   case AtomicExpr::AO__atomic_store:
581   case AtomicExpr::AO__atomic_store_n: {
582     llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
583     llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
584     Store->setAtomic(Order, Scope);
585     Store->setVolatile(E->isVolatile());
586     return;
587   }
588 
589   case AtomicExpr::AO__c11_atomic_exchange:
590   case AtomicExpr::AO__hip_atomic_exchange:
591   case AtomicExpr::AO__opencl_atomic_exchange:
592   case AtomicExpr::AO__atomic_exchange_n:
593   case AtomicExpr::AO__atomic_exchange:
594     Op = llvm::AtomicRMWInst::Xchg;
595     break;
596 
597   case AtomicExpr::AO__atomic_add_fetch:
598     PostOp = E->getValueType()->isFloatingType() ? llvm::Instruction::FAdd
599                                                  : llvm::Instruction::Add;
600     LLVM_FALLTHROUGH;
601   case AtomicExpr::AO__c11_atomic_fetch_add:
602   case AtomicExpr::AO__hip_atomic_fetch_add:
603   case AtomicExpr::AO__opencl_atomic_fetch_add:
604   case AtomicExpr::AO__atomic_fetch_add:
605     Op = E->getValueType()->isFloatingType() ? llvm::AtomicRMWInst::FAdd
606                                              : llvm::AtomicRMWInst::Add;
607     break;
608 
609   case AtomicExpr::AO__atomic_sub_fetch:
610     PostOp = E->getValueType()->isFloatingType() ? llvm::Instruction::FSub
611                                                  : llvm::Instruction::Sub;
612     LLVM_FALLTHROUGH;
613   case AtomicExpr::AO__c11_atomic_fetch_sub:
614   case AtomicExpr::AO__opencl_atomic_fetch_sub:
615   case AtomicExpr::AO__atomic_fetch_sub:
616     Op = E->getValueType()->isFloatingType() ? llvm::AtomicRMWInst::FSub
617                                              : llvm::AtomicRMWInst::Sub;
618     break;
619 
620   case AtomicExpr::AO__atomic_min_fetch:
621     PostOpMinMax = true;
622     LLVM_FALLTHROUGH;
623   case AtomicExpr::AO__c11_atomic_fetch_min:
624   case AtomicExpr::AO__hip_atomic_fetch_min:
625   case AtomicExpr::AO__opencl_atomic_fetch_min:
626   case AtomicExpr::AO__atomic_fetch_min:
627     Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Min
628                                                   : llvm::AtomicRMWInst::UMin;
629     break;
630 
631   case AtomicExpr::AO__atomic_max_fetch:
632     PostOpMinMax = true;
633     LLVM_FALLTHROUGH;
634   case AtomicExpr::AO__c11_atomic_fetch_max:
635   case AtomicExpr::AO__hip_atomic_fetch_max:
636   case AtomicExpr::AO__opencl_atomic_fetch_max:
637   case AtomicExpr::AO__atomic_fetch_max:
638     Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Max
639                                                   : llvm::AtomicRMWInst::UMax;
640     break;
641 
642   case AtomicExpr::AO__atomic_and_fetch:
643     PostOp = llvm::Instruction::And;
644     LLVM_FALLTHROUGH;
645   case AtomicExpr::AO__c11_atomic_fetch_and:
646   case AtomicExpr::AO__hip_atomic_fetch_and:
647   case AtomicExpr::AO__opencl_atomic_fetch_and:
648   case AtomicExpr::AO__atomic_fetch_and:
649     Op = llvm::AtomicRMWInst::And;
650     break;
651 
652   case AtomicExpr::AO__atomic_or_fetch:
653     PostOp = llvm::Instruction::Or;
654     LLVM_FALLTHROUGH;
655   case AtomicExpr::AO__c11_atomic_fetch_or:
656   case AtomicExpr::AO__hip_atomic_fetch_or:
657   case AtomicExpr::AO__opencl_atomic_fetch_or:
658   case AtomicExpr::AO__atomic_fetch_or:
659     Op = llvm::AtomicRMWInst::Or;
660     break;
661 
662   case AtomicExpr::AO__atomic_xor_fetch:
663     PostOp = llvm::Instruction::Xor;
664     LLVM_FALLTHROUGH;
665   case AtomicExpr::AO__c11_atomic_fetch_xor:
666   case AtomicExpr::AO__hip_atomic_fetch_xor:
667   case AtomicExpr::AO__opencl_atomic_fetch_xor:
668   case AtomicExpr::AO__atomic_fetch_xor:
669     Op = llvm::AtomicRMWInst::Xor;
670     break;
671 
672   case AtomicExpr::AO__atomic_nand_fetch:
673     PostOp = llvm::Instruction::And; // the NOT is special cased below
674     LLVM_FALLTHROUGH;
675   case AtomicExpr::AO__c11_atomic_fetch_nand:
676   case AtomicExpr::AO__atomic_fetch_nand:
677     Op = llvm::AtomicRMWInst::Nand;
678     break;
679   }
680 
681   llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
682   llvm::AtomicRMWInst *RMWI =
683       CGF.Builder.CreateAtomicRMW(Op, Ptr.getPointer(), LoadVal1, Order, Scope);
684   RMWI->setVolatile(E->isVolatile());
685 
686   // For __atomic_*_fetch operations, perform the operation again to
687   // determine the value which was written.
688   llvm::Value *Result = RMWI;
689   if (PostOpMinMax)
690     Result = EmitPostAtomicMinMax(CGF.Builder, E->getOp(),
691                                   E->getValueType()->isSignedIntegerType(),
692                                   RMWI, LoadVal1);
693   else if (PostOp)
694     Result = CGF.Builder.CreateBinOp((llvm::Instruction::BinaryOps)PostOp, RMWI,
695                                      LoadVal1);
696   if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
697     Result = CGF.Builder.CreateNot(Result);
698   CGF.Builder.CreateStore(Result, Dest);
699 }
700 
701 // This function emits any expression (scalar, complex, or aggregate)
702 // into a temporary alloca.
703 static Address
704 EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
705   Address DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
706   CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
707                        /*Init*/ true);
708   return DeclPtr;
709 }
710 
711 static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *Expr, Address Dest,
712                          Address Ptr, Address Val1, Address Val2,
713                          llvm::Value *IsWeak, llvm::Value *FailureOrder,
714                          uint64_t Size, llvm::AtomicOrdering Order,
715                          llvm::Value *Scope) {
716   auto ScopeModel = Expr->getScopeModel();
717 
718   // LLVM atomic instructions always have synch scope. If clang atomic
719   // expression has no scope operand, use default LLVM synch scope.
720   if (!ScopeModel) {
721     EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
722                  Order, CGF.CGM.getLLVMContext().getOrInsertSyncScopeID(""));
723     return;
724   }
725 
726   // Handle constant scope.
727   if (auto SC = dyn_cast<llvm::ConstantInt>(Scope)) {
728     auto SCID = CGF.getTargetHooks().getLLVMSyncScopeID(
729         CGF.CGM.getLangOpts(), ScopeModel->map(SC->getZExtValue()),
730         Order, CGF.CGM.getLLVMContext());
731     EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
732                  Order, SCID);
733     return;
734   }
735 
736   // Handle non-constant scope.
737   auto &Builder = CGF.Builder;
738   auto Scopes = ScopeModel->getRuntimeValues();
739   llvm::DenseMap<unsigned, llvm::BasicBlock *> BB;
740   for (auto S : Scopes)
741     BB[S] = CGF.createBasicBlock(getAsString(ScopeModel->map(S)), CGF.CurFn);
742 
743   llvm::BasicBlock *ContBB =
744       CGF.createBasicBlock("atomic.scope.continue", CGF.CurFn);
745 
746   auto *SC = Builder.CreateIntCast(Scope, Builder.getInt32Ty(), false);
747   // If unsupported synch scope is encountered at run time, assume a fallback
748   // synch scope value.
749   auto FallBack = ScopeModel->getFallBackValue();
750   llvm::SwitchInst *SI = Builder.CreateSwitch(SC, BB[FallBack]);
751   for (auto S : Scopes) {
752     auto *B = BB[S];
753     if (S != FallBack)
754       SI->addCase(Builder.getInt32(S), B);
755 
756     Builder.SetInsertPoint(B);
757     EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
758                  Order,
759                  CGF.getTargetHooks().getLLVMSyncScopeID(CGF.CGM.getLangOpts(),
760                                                          ScopeModel->map(S),
761                                                          Order,
762                                                          CGF.getLLVMContext()));
763     Builder.CreateBr(ContBB);
764   }
765 
766   Builder.SetInsertPoint(ContBB);
767 }
768 
769 static void
770 AddDirectArgument(CodeGenFunction &CGF, CallArgList &Args,
771                   bool UseOptimizedLibcall, llvm::Value *Val, QualType ValTy,
772                   SourceLocation Loc, CharUnits SizeInChars) {
773   if (UseOptimizedLibcall) {
774     // Load value and pass it to the function directly.
775     CharUnits Align = CGF.getContext().getTypeAlignInChars(ValTy);
776     int64_t SizeInBits = CGF.getContext().toBits(SizeInChars);
777     ValTy =
778         CGF.getContext().getIntTypeForBitwidth(SizeInBits, /*Signed=*/false);
779     llvm::Type *IPtrTy = llvm::IntegerType::get(CGF.getLLVMContext(),
780                                                 SizeInBits)->getPointerTo();
781     Address Ptr = Address(CGF.Builder.CreateBitCast(Val, IPtrTy), Align);
782     Val = CGF.EmitLoadOfScalar(Ptr, false,
783                                CGF.getContext().getPointerType(ValTy),
784                                Loc);
785     // Coerce the value into an appropriately sized integer type.
786     Args.add(RValue::get(Val), ValTy);
787   } else {
788     // Non-optimized functions always take a reference.
789     Args.add(RValue::get(CGF.EmitCastToVoidPtr(Val)),
790                          CGF.getContext().VoidPtrTy);
791   }
792 }
793 
794 RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
795   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
796   QualType MemTy = AtomicTy;
797   if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
798     MemTy = AT->getValueType();
799   llvm::Value *IsWeak = nullptr, *OrderFail = nullptr;
800 
801   Address Val1 = Address::invalid();
802   Address Val2 = Address::invalid();
803   Address Dest = Address::invalid();
804   Address Ptr = EmitPointerWithAlignment(E->getPtr());
805 
806   if (E->getOp() == AtomicExpr::AO__c11_atomic_init ||
807       E->getOp() == AtomicExpr::AO__opencl_atomic_init) {
808     LValue lvalue = MakeAddrLValue(Ptr, AtomicTy);
809     EmitAtomicInit(E->getVal1(), lvalue);
810     return RValue::get(nullptr);
811   }
812 
813   auto TInfo = getContext().getTypeInfoInChars(AtomicTy);
814   uint64_t Size = TInfo.Width.getQuantity();
815   unsigned MaxInlineWidthInBits = getTarget().getMaxAtomicInlineWidth();
816 
817   bool Oversized = getContext().toBits(TInfo.Width) > MaxInlineWidthInBits;
818   bool Misaligned = (Ptr.getAlignment() % TInfo.Width) != 0;
819   bool UseLibcall = Misaligned | Oversized;
820   bool ShouldCastToIntPtrTy = true;
821 
822   CharUnits MaxInlineWidth =
823       getContext().toCharUnitsFromBits(MaxInlineWidthInBits);
824 
825   DiagnosticsEngine &Diags = CGM.getDiags();
826 
827   if (Misaligned) {
828     Diags.Report(E->getBeginLoc(), diag::warn_atomic_op_misaligned)
829         << (int)TInfo.Width.getQuantity()
830         << (int)Ptr.getAlignment().getQuantity();
831   }
832 
833   if (Oversized) {
834     Diags.Report(E->getBeginLoc(), diag::warn_atomic_op_oversized)
835         << (int)TInfo.Width.getQuantity() << (int)MaxInlineWidth.getQuantity();
836   }
837 
838   llvm::Value *Order = EmitScalarExpr(E->getOrder());
839   llvm::Value *Scope =
840       E->getScopeModel() ? EmitScalarExpr(E->getScope()) : nullptr;
841 
842   switch (E->getOp()) {
843   case AtomicExpr::AO__c11_atomic_init:
844   case AtomicExpr::AO__opencl_atomic_init:
845     llvm_unreachable("Already handled above with EmitAtomicInit!");
846 
847   case AtomicExpr::AO__c11_atomic_load:
848   case AtomicExpr::AO__opencl_atomic_load:
849   case AtomicExpr::AO__atomic_load_n:
850     break;
851 
852   case AtomicExpr::AO__atomic_load:
853     Dest = EmitPointerWithAlignment(E->getVal1());
854     break;
855 
856   case AtomicExpr::AO__atomic_store:
857     Val1 = EmitPointerWithAlignment(E->getVal1());
858     break;
859 
860   case AtomicExpr::AO__atomic_exchange:
861     Val1 = EmitPointerWithAlignment(E->getVal1());
862     Dest = EmitPointerWithAlignment(E->getVal2());
863     break;
864 
865   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
866   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
867   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
868   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
869   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
870   case AtomicExpr::AO__atomic_compare_exchange_n:
871   case AtomicExpr::AO__atomic_compare_exchange:
872     Val1 = EmitPointerWithAlignment(E->getVal1());
873     if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
874       Val2 = EmitPointerWithAlignment(E->getVal2());
875     else
876       Val2 = EmitValToTemp(*this, E->getVal2());
877     OrderFail = EmitScalarExpr(E->getOrderFail());
878     if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
879         E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
880       IsWeak = EmitScalarExpr(E->getWeak());
881     break;
882 
883   case AtomicExpr::AO__c11_atomic_fetch_add:
884   case AtomicExpr::AO__c11_atomic_fetch_sub:
885   case AtomicExpr::AO__hip_atomic_fetch_add:
886   case AtomicExpr::AO__opencl_atomic_fetch_add:
887   case AtomicExpr::AO__opencl_atomic_fetch_sub:
888     if (MemTy->isPointerType()) {
889       // For pointer arithmetic, we're required to do a bit of math:
890       // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
891       // ... but only for the C11 builtins. The GNU builtins expect the
892       // user to multiply by sizeof(T).
893       QualType Val1Ty = E->getVal1()->getType();
894       llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
895       CharUnits PointeeIncAmt =
896           getContext().getTypeSizeInChars(MemTy->getPointeeType());
897       Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
898       auto Temp = CreateMemTemp(Val1Ty, ".atomictmp");
899       Val1 = Temp;
900       EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Temp, Val1Ty));
901       break;
902     }
903     LLVM_FALLTHROUGH;
904   case AtomicExpr::AO__atomic_fetch_add:
905   case AtomicExpr::AO__atomic_fetch_sub:
906   case AtomicExpr::AO__atomic_add_fetch:
907   case AtomicExpr::AO__atomic_sub_fetch:
908     ShouldCastToIntPtrTy = !MemTy->isFloatingType();
909     LLVM_FALLTHROUGH;
910 
911   case AtomicExpr::AO__c11_atomic_store:
912   case AtomicExpr::AO__c11_atomic_exchange:
913   case AtomicExpr::AO__opencl_atomic_store:
914   case AtomicExpr::AO__opencl_atomic_exchange:
915   case AtomicExpr::AO__hip_atomic_exchange:
916   case AtomicExpr::AO__atomic_store_n:
917   case AtomicExpr::AO__atomic_exchange_n:
918   case AtomicExpr::AO__c11_atomic_fetch_and:
919   case AtomicExpr::AO__c11_atomic_fetch_or:
920   case AtomicExpr::AO__c11_atomic_fetch_xor:
921   case AtomicExpr::AO__c11_atomic_fetch_nand:
922   case AtomicExpr::AO__c11_atomic_fetch_max:
923   case AtomicExpr::AO__c11_atomic_fetch_min:
924   case AtomicExpr::AO__opencl_atomic_fetch_and:
925   case AtomicExpr::AO__opencl_atomic_fetch_or:
926   case AtomicExpr::AO__opencl_atomic_fetch_xor:
927   case AtomicExpr::AO__opencl_atomic_fetch_min:
928   case AtomicExpr::AO__opencl_atomic_fetch_max:
929   case AtomicExpr::AO__atomic_fetch_and:
930   case AtomicExpr::AO__hip_atomic_fetch_and:
931   case AtomicExpr::AO__atomic_fetch_or:
932   case AtomicExpr::AO__hip_atomic_fetch_or:
933   case AtomicExpr::AO__atomic_fetch_xor:
934   case AtomicExpr::AO__hip_atomic_fetch_xor:
935   case AtomicExpr::AO__atomic_fetch_nand:
936   case AtomicExpr::AO__atomic_and_fetch:
937   case AtomicExpr::AO__atomic_or_fetch:
938   case AtomicExpr::AO__atomic_xor_fetch:
939   case AtomicExpr::AO__atomic_nand_fetch:
940   case AtomicExpr::AO__atomic_max_fetch:
941   case AtomicExpr::AO__atomic_min_fetch:
942   case AtomicExpr::AO__atomic_fetch_max:
943   case AtomicExpr::AO__hip_atomic_fetch_max:
944   case AtomicExpr::AO__atomic_fetch_min:
945   case AtomicExpr::AO__hip_atomic_fetch_min:
946     Val1 = EmitValToTemp(*this, E->getVal1());
947     break;
948   }
949 
950   QualType RValTy = E->getType().getUnqualifiedType();
951 
952   // The inlined atomics only function on iN types, where N is a power of 2. We
953   // need to make sure (via temporaries if necessary) that all incoming values
954   // are compatible.
955   LValue AtomicVal = MakeAddrLValue(Ptr, AtomicTy);
956   AtomicInfo Atomics(*this, AtomicVal);
957 
958   if (ShouldCastToIntPtrTy) {
959     Ptr = Atomics.emitCastToAtomicIntPointer(Ptr);
960     if (Val1.isValid())
961       Val1 = Atomics.convertToAtomicIntPointer(Val1);
962     if (Val2.isValid())
963       Val2 = Atomics.convertToAtomicIntPointer(Val2);
964   }
965   if (Dest.isValid()) {
966     if (ShouldCastToIntPtrTy)
967       Dest = Atomics.emitCastToAtomicIntPointer(Dest);
968   } else if (E->isCmpXChg())
969     Dest = CreateMemTemp(RValTy, "cmpxchg.bool");
970   else if (!RValTy->isVoidType()) {
971     Dest = Atomics.CreateTempAlloca();
972     if (ShouldCastToIntPtrTy)
973       Dest = Atomics.emitCastToAtomicIntPointer(Dest);
974   }
975 
976   // Use a library call.  See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
977   if (UseLibcall) {
978     bool UseOptimizedLibcall = false;
979     switch (E->getOp()) {
980     case AtomicExpr::AO__c11_atomic_init:
981     case AtomicExpr::AO__opencl_atomic_init:
982       llvm_unreachable("Already handled above with EmitAtomicInit!");
983 
984     case AtomicExpr::AO__c11_atomic_fetch_add:
985     case AtomicExpr::AO__opencl_atomic_fetch_add:
986     case AtomicExpr::AO__atomic_fetch_add:
987     case AtomicExpr::AO__hip_atomic_fetch_add:
988     case AtomicExpr::AO__c11_atomic_fetch_and:
989     case AtomicExpr::AO__opencl_atomic_fetch_and:
990     case AtomicExpr::AO__hip_atomic_fetch_and:
991     case AtomicExpr::AO__atomic_fetch_and:
992     case AtomicExpr::AO__c11_atomic_fetch_or:
993     case AtomicExpr::AO__opencl_atomic_fetch_or:
994     case AtomicExpr::AO__hip_atomic_fetch_or:
995     case AtomicExpr::AO__atomic_fetch_or:
996     case AtomicExpr::AO__c11_atomic_fetch_nand:
997     case AtomicExpr::AO__atomic_fetch_nand:
998     case AtomicExpr::AO__c11_atomic_fetch_sub:
999     case AtomicExpr::AO__opencl_atomic_fetch_sub:
1000     case AtomicExpr::AO__atomic_fetch_sub:
1001     case AtomicExpr::AO__c11_atomic_fetch_xor:
1002     case AtomicExpr::AO__opencl_atomic_fetch_xor:
1003     case AtomicExpr::AO__opencl_atomic_fetch_min:
1004     case AtomicExpr::AO__opencl_atomic_fetch_max:
1005     case AtomicExpr::AO__atomic_fetch_xor:
1006     case AtomicExpr::AO__hip_atomic_fetch_xor:
1007     case AtomicExpr::AO__c11_atomic_fetch_max:
1008     case AtomicExpr::AO__c11_atomic_fetch_min:
1009     case AtomicExpr::AO__atomic_add_fetch:
1010     case AtomicExpr::AO__atomic_and_fetch:
1011     case AtomicExpr::AO__atomic_nand_fetch:
1012     case AtomicExpr::AO__atomic_or_fetch:
1013     case AtomicExpr::AO__atomic_sub_fetch:
1014     case AtomicExpr::AO__atomic_xor_fetch:
1015     case AtomicExpr::AO__atomic_fetch_max:
1016     case AtomicExpr::AO__hip_atomic_fetch_max:
1017     case AtomicExpr::AO__atomic_fetch_min:
1018     case AtomicExpr::AO__hip_atomic_fetch_min:
1019     case AtomicExpr::AO__atomic_max_fetch:
1020     case AtomicExpr::AO__atomic_min_fetch:
1021       // For these, only library calls for certain sizes exist.
1022       UseOptimizedLibcall = true;
1023       break;
1024 
1025     case AtomicExpr::AO__atomic_load:
1026     case AtomicExpr::AO__atomic_store:
1027     case AtomicExpr::AO__atomic_exchange:
1028     case AtomicExpr::AO__atomic_compare_exchange:
1029       // Use the generic version if we don't know that the operand will be
1030       // suitably aligned for the optimized version.
1031       if (Misaligned)
1032         break;
1033       LLVM_FALLTHROUGH;
1034     case AtomicExpr::AO__c11_atomic_load:
1035     case AtomicExpr::AO__c11_atomic_store:
1036     case AtomicExpr::AO__c11_atomic_exchange:
1037     case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1038     case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1039     case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
1040     case AtomicExpr::AO__opencl_atomic_load:
1041     case AtomicExpr::AO__opencl_atomic_store:
1042     case AtomicExpr::AO__opencl_atomic_exchange:
1043     case AtomicExpr::AO__hip_atomic_exchange:
1044     case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1045     case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
1046     case AtomicExpr::AO__atomic_load_n:
1047     case AtomicExpr::AO__atomic_store_n:
1048     case AtomicExpr::AO__atomic_exchange_n:
1049     case AtomicExpr::AO__atomic_compare_exchange_n:
1050       // Only use optimized library calls for sizes for which they exist.
1051       // FIXME: Size == 16 optimized library functions exist too.
1052       if (Size == 1 || Size == 2 || Size == 4 || Size == 8)
1053         UseOptimizedLibcall = true;
1054       break;
1055     }
1056 
1057     CallArgList Args;
1058     if (!UseOptimizedLibcall) {
1059       // For non-optimized library calls, the size is the first parameter
1060       Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
1061                getContext().getSizeType());
1062     }
1063     // Atomic address is the first or second parameter
1064     // The OpenCL atomic library functions only accept pointer arguments to
1065     // generic address space.
1066     auto CastToGenericAddrSpace = [&](llvm::Value *V, QualType PT) {
1067       if (!E->isOpenCL())
1068         return V;
1069       auto AS = PT->castAs<PointerType>()->getPointeeType().getAddressSpace();
1070       if (AS == LangAS::opencl_generic)
1071         return V;
1072       auto DestAS = getContext().getTargetAddressSpace(LangAS::opencl_generic);
1073       auto T = V->getType();
1074       auto *DestType = T->getPointerElementType()->getPointerTo(DestAS);
1075 
1076       return getTargetHooks().performAddrSpaceCast(
1077           *this, V, AS, LangAS::opencl_generic, DestType, false);
1078     };
1079 
1080     Args.add(RValue::get(CastToGenericAddrSpace(
1081                  EmitCastToVoidPtr(Ptr.getPointer()), E->getPtr()->getType())),
1082              getContext().VoidPtrTy);
1083 
1084     std::string LibCallName;
1085     QualType LoweredMemTy =
1086       MemTy->isPointerType() ? getContext().getIntPtrType() : MemTy;
1087     QualType RetTy;
1088     bool HaveRetTy = false;
1089     llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
1090     bool PostOpMinMax = false;
1091     switch (E->getOp()) {
1092     case AtomicExpr::AO__c11_atomic_init:
1093     case AtomicExpr::AO__opencl_atomic_init:
1094       llvm_unreachable("Already handled!");
1095 
1096     // There is only one libcall for compare an exchange, because there is no
1097     // optimisation benefit possible from a libcall version of a weak compare
1098     // and exchange.
1099     // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
1100     //                                void *desired, int success, int failure)
1101     // bool __atomic_compare_exchange_N(T *mem, T *expected, T desired,
1102     //                                  int success, int failure)
1103     case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1104     case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1105     case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1106     case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
1107     case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
1108     case AtomicExpr::AO__atomic_compare_exchange:
1109     case AtomicExpr::AO__atomic_compare_exchange_n:
1110       LibCallName = "__atomic_compare_exchange";
1111       RetTy = getContext().BoolTy;
1112       HaveRetTy = true;
1113       Args.add(
1114           RValue::get(CastToGenericAddrSpace(
1115               EmitCastToVoidPtr(Val1.getPointer()), E->getVal1()->getType())),
1116           getContext().VoidPtrTy);
1117       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val2.getPointer(),
1118                         MemTy, E->getExprLoc(), TInfo.Width);
1119       Args.add(RValue::get(Order), getContext().IntTy);
1120       Order = OrderFail;
1121       break;
1122     // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
1123     //                        int order)
1124     // T __atomic_exchange_N(T *mem, T val, int order)
1125     case AtomicExpr::AO__c11_atomic_exchange:
1126     case AtomicExpr::AO__opencl_atomic_exchange:
1127     case AtomicExpr::AO__atomic_exchange_n:
1128     case AtomicExpr::AO__atomic_exchange:
1129     case AtomicExpr::AO__hip_atomic_exchange:
1130       LibCallName = "__atomic_exchange";
1131       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1132                         MemTy, E->getExprLoc(), TInfo.Width);
1133       break;
1134     // void __atomic_store(size_t size, void *mem, void *val, int order)
1135     // void __atomic_store_N(T *mem, T val, int order)
1136     case AtomicExpr::AO__c11_atomic_store:
1137     case AtomicExpr::AO__opencl_atomic_store:
1138     case AtomicExpr::AO__atomic_store:
1139     case AtomicExpr::AO__atomic_store_n:
1140       LibCallName = "__atomic_store";
1141       RetTy = getContext().VoidTy;
1142       HaveRetTy = true;
1143       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1144                         MemTy, E->getExprLoc(), TInfo.Width);
1145       break;
1146     // void __atomic_load(size_t size, void *mem, void *return, int order)
1147     // T __atomic_load_N(T *mem, int order)
1148     case AtomicExpr::AO__c11_atomic_load:
1149     case AtomicExpr::AO__opencl_atomic_load:
1150     case AtomicExpr::AO__atomic_load:
1151     case AtomicExpr::AO__atomic_load_n:
1152       LibCallName = "__atomic_load";
1153       break;
1154     // T __atomic_add_fetch_N(T *mem, T val, int order)
1155     // T __atomic_fetch_add_N(T *mem, T val, int order)
1156     case AtomicExpr::AO__atomic_add_fetch:
1157       PostOp = llvm::Instruction::Add;
1158       LLVM_FALLTHROUGH;
1159     case AtomicExpr::AO__c11_atomic_fetch_add:
1160     case AtomicExpr::AO__opencl_atomic_fetch_add:
1161     case AtomicExpr::AO__atomic_fetch_add:
1162     case AtomicExpr::AO__hip_atomic_fetch_add:
1163       LibCallName = "__atomic_fetch_add";
1164       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1165                         LoweredMemTy, E->getExprLoc(), TInfo.Width);
1166       break;
1167     // T __atomic_and_fetch_N(T *mem, T val, int order)
1168     // T __atomic_fetch_and_N(T *mem, T val, int order)
1169     case AtomicExpr::AO__atomic_and_fetch:
1170       PostOp = llvm::Instruction::And;
1171       LLVM_FALLTHROUGH;
1172     case AtomicExpr::AO__c11_atomic_fetch_and:
1173     case AtomicExpr::AO__opencl_atomic_fetch_and:
1174     case AtomicExpr::AO__hip_atomic_fetch_and:
1175     case AtomicExpr::AO__atomic_fetch_and:
1176       LibCallName = "__atomic_fetch_and";
1177       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1178                         MemTy, E->getExprLoc(), TInfo.Width);
1179       break;
1180     // T __atomic_or_fetch_N(T *mem, T val, int order)
1181     // T __atomic_fetch_or_N(T *mem, T val, int order)
1182     case AtomicExpr::AO__atomic_or_fetch:
1183       PostOp = llvm::Instruction::Or;
1184       LLVM_FALLTHROUGH;
1185     case AtomicExpr::AO__c11_atomic_fetch_or:
1186     case AtomicExpr::AO__opencl_atomic_fetch_or:
1187     case AtomicExpr::AO__hip_atomic_fetch_or:
1188     case AtomicExpr::AO__atomic_fetch_or:
1189       LibCallName = "__atomic_fetch_or";
1190       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1191                         MemTy, E->getExprLoc(), TInfo.Width);
1192       break;
1193     // T __atomic_sub_fetch_N(T *mem, T val, int order)
1194     // T __atomic_fetch_sub_N(T *mem, T val, int order)
1195     case AtomicExpr::AO__atomic_sub_fetch:
1196       PostOp = llvm::Instruction::Sub;
1197       LLVM_FALLTHROUGH;
1198     case AtomicExpr::AO__c11_atomic_fetch_sub:
1199     case AtomicExpr::AO__opencl_atomic_fetch_sub:
1200     case AtomicExpr::AO__atomic_fetch_sub:
1201       LibCallName = "__atomic_fetch_sub";
1202       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1203                         LoweredMemTy, E->getExprLoc(), TInfo.Width);
1204       break;
1205     // T __atomic_xor_fetch_N(T *mem, T val, int order)
1206     // T __atomic_fetch_xor_N(T *mem, T val, int order)
1207     case AtomicExpr::AO__atomic_xor_fetch:
1208       PostOp = llvm::Instruction::Xor;
1209       LLVM_FALLTHROUGH;
1210     case AtomicExpr::AO__c11_atomic_fetch_xor:
1211     case AtomicExpr::AO__opencl_atomic_fetch_xor:
1212     case AtomicExpr::AO__hip_atomic_fetch_xor:
1213     case AtomicExpr::AO__atomic_fetch_xor:
1214       LibCallName = "__atomic_fetch_xor";
1215       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1216                         MemTy, E->getExprLoc(), TInfo.Width);
1217       break;
1218     case AtomicExpr::AO__atomic_min_fetch:
1219       PostOpMinMax = true;
1220       LLVM_FALLTHROUGH;
1221     case AtomicExpr::AO__c11_atomic_fetch_min:
1222     case AtomicExpr::AO__atomic_fetch_min:
1223     case AtomicExpr::AO__hip_atomic_fetch_min:
1224     case AtomicExpr::AO__opencl_atomic_fetch_min:
1225       LibCallName = E->getValueType()->isSignedIntegerType()
1226                         ? "__atomic_fetch_min"
1227                         : "__atomic_fetch_umin";
1228       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1229                         LoweredMemTy, E->getExprLoc(), TInfo.Width);
1230       break;
1231     case AtomicExpr::AO__atomic_max_fetch:
1232       PostOpMinMax = true;
1233       LLVM_FALLTHROUGH;
1234     case AtomicExpr::AO__c11_atomic_fetch_max:
1235     case AtomicExpr::AO__atomic_fetch_max:
1236     case AtomicExpr::AO__hip_atomic_fetch_max:
1237     case AtomicExpr::AO__opencl_atomic_fetch_max:
1238       LibCallName = E->getValueType()->isSignedIntegerType()
1239                         ? "__atomic_fetch_max"
1240                         : "__atomic_fetch_umax";
1241       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1242                         LoweredMemTy, E->getExprLoc(), TInfo.Width);
1243       break;
1244     // T __atomic_nand_fetch_N(T *mem, T val, int order)
1245     // T __atomic_fetch_nand_N(T *mem, T val, int order)
1246     case AtomicExpr::AO__atomic_nand_fetch:
1247       PostOp = llvm::Instruction::And; // the NOT is special cased below
1248       LLVM_FALLTHROUGH;
1249     case AtomicExpr::AO__c11_atomic_fetch_nand:
1250     case AtomicExpr::AO__atomic_fetch_nand:
1251       LibCallName = "__atomic_fetch_nand";
1252       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1253                         MemTy, E->getExprLoc(), TInfo.Width);
1254       break;
1255     }
1256 
1257     if (E->isOpenCL()) {
1258       LibCallName = std::string("__opencl") +
1259           StringRef(LibCallName).drop_front(1).str();
1260 
1261     }
1262     // Optimized functions have the size in their name.
1263     if (UseOptimizedLibcall)
1264       LibCallName += "_" + llvm::utostr(Size);
1265     // By default, assume we return a value of the atomic type.
1266     if (!HaveRetTy) {
1267       if (UseOptimizedLibcall) {
1268         // Value is returned directly.
1269         // The function returns an appropriately sized integer type.
1270         RetTy = getContext().getIntTypeForBitwidth(
1271             getContext().toBits(TInfo.Width), /*Signed=*/false);
1272       } else {
1273         // Value is returned through parameter before the order.
1274         RetTy = getContext().VoidTy;
1275         Args.add(RValue::get(EmitCastToVoidPtr(Dest.getPointer())),
1276                  getContext().VoidPtrTy);
1277       }
1278     }
1279     // order is always the last parameter
1280     Args.add(RValue::get(Order),
1281              getContext().IntTy);
1282     if (E->isOpenCL())
1283       Args.add(RValue::get(Scope), getContext().IntTy);
1284 
1285     // PostOp is only needed for the atomic_*_fetch operations, and
1286     // thus is only needed for and implemented in the
1287     // UseOptimizedLibcall codepath.
1288     assert(UseOptimizedLibcall || (!PostOp && !PostOpMinMax));
1289 
1290     RValue Res = emitAtomicLibcall(*this, LibCallName, RetTy, Args);
1291     // The value is returned directly from the libcall.
1292     if (E->isCmpXChg())
1293       return Res;
1294 
1295     // The value is returned directly for optimized libcalls but the expr
1296     // provided an out-param.
1297     if (UseOptimizedLibcall && Res.getScalarVal()) {
1298       llvm::Value *ResVal = Res.getScalarVal();
1299       if (PostOpMinMax) {
1300         llvm::Value *LoadVal1 = Args[1].getRValue(*this).getScalarVal();
1301         ResVal = EmitPostAtomicMinMax(Builder, E->getOp(),
1302                                       E->getValueType()->isSignedIntegerType(),
1303                                       ResVal, LoadVal1);
1304       } else if (PostOp) {
1305         llvm::Value *LoadVal1 = Args[1].getRValue(*this).getScalarVal();
1306         ResVal = Builder.CreateBinOp(PostOp, ResVal, LoadVal1);
1307       }
1308       if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
1309         ResVal = Builder.CreateNot(ResVal);
1310 
1311       Builder.CreateStore(
1312           ResVal,
1313           Builder.CreateBitCast(Dest, ResVal->getType()->getPointerTo()));
1314     }
1315 
1316     if (RValTy->isVoidType())
1317       return RValue::get(nullptr);
1318 
1319     return convertTempToRValue(
1320         Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo()),
1321         RValTy, E->getExprLoc());
1322   }
1323 
1324   bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
1325                  E->getOp() == AtomicExpr::AO__opencl_atomic_store ||
1326                  E->getOp() == AtomicExpr::AO__atomic_store ||
1327                  E->getOp() == AtomicExpr::AO__atomic_store_n;
1328   bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
1329                 E->getOp() == AtomicExpr::AO__opencl_atomic_load ||
1330                 E->getOp() == AtomicExpr::AO__atomic_load ||
1331                 E->getOp() == AtomicExpr::AO__atomic_load_n;
1332 
1333   if (isa<llvm::ConstantInt>(Order)) {
1334     auto ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
1335     // We should not ever get to a case where the ordering isn't a valid C ABI
1336     // value, but it's hard to enforce that in general.
1337     if (llvm::isValidAtomicOrderingCABI(ord))
1338       switch ((llvm::AtomicOrderingCABI)ord) {
1339       case llvm::AtomicOrderingCABI::relaxed:
1340         EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1341                      llvm::AtomicOrdering::Monotonic, Scope);
1342         break;
1343       case llvm::AtomicOrderingCABI::consume:
1344       case llvm::AtomicOrderingCABI::acquire:
1345         if (IsStore)
1346           break; // Avoid crashing on code with undefined behavior
1347         EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1348                      llvm::AtomicOrdering::Acquire, Scope);
1349         break;
1350       case llvm::AtomicOrderingCABI::release:
1351         if (IsLoad)
1352           break; // Avoid crashing on code with undefined behavior
1353         EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1354                      llvm::AtomicOrdering::Release, Scope);
1355         break;
1356       case llvm::AtomicOrderingCABI::acq_rel:
1357         if (IsLoad || IsStore)
1358           break; // Avoid crashing on code with undefined behavior
1359         EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1360                      llvm::AtomicOrdering::AcquireRelease, Scope);
1361         break;
1362       case llvm::AtomicOrderingCABI::seq_cst:
1363         EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1364                      llvm::AtomicOrdering::SequentiallyConsistent, Scope);
1365         break;
1366       }
1367     if (RValTy->isVoidType())
1368       return RValue::get(nullptr);
1369 
1370     return convertTempToRValue(
1371         Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1372                                         Dest.getAddressSpace())),
1373         RValTy, E->getExprLoc());
1374   }
1375 
1376   // Long case, when Order isn't obviously constant.
1377 
1378   // Create all the relevant BB's
1379   llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
1380                    *ReleaseBB = nullptr, *AcqRelBB = nullptr,
1381                    *SeqCstBB = nullptr;
1382   MonotonicBB = createBasicBlock("monotonic", CurFn);
1383   if (!IsStore)
1384     AcquireBB = createBasicBlock("acquire", CurFn);
1385   if (!IsLoad)
1386     ReleaseBB = createBasicBlock("release", CurFn);
1387   if (!IsLoad && !IsStore)
1388     AcqRelBB = createBasicBlock("acqrel", CurFn);
1389   SeqCstBB = createBasicBlock("seqcst", CurFn);
1390   llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
1391 
1392   // Create the switch for the split
1393   // MonotonicBB is arbitrarily chosen as the default case; in practice, this
1394   // doesn't matter unless someone is crazy enough to use something that
1395   // doesn't fold to a constant for the ordering.
1396   Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
1397   llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
1398 
1399   // Emit all the different atomics
1400   Builder.SetInsertPoint(MonotonicBB);
1401   EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1402                llvm::AtomicOrdering::Monotonic, Scope);
1403   Builder.CreateBr(ContBB);
1404   if (!IsStore) {
1405     Builder.SetInsertPoint(AcquireBB);
1406     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1407                  llvm::AtomicOrdering::Acquire, Scope);
1408     Builder.CreateBr(ContBB);
1409     SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
1410                 AcquireBB);
1411     SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
1412                 AcquireBB);
1413   }
1414   if (!IsLoad) {
1415     Builder.SetInsertPoint(ReleaseBB);
1416     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1417                  llvm::AtomicOrdering::Release, Scope);
1418     Builder.CreateBr(ContBB);
1419     SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::release),
1420                 ReleaseBB);
1421   }
1422   if (!IsLoad && !IsStore) {
1423     Builder.SetInsertPoint(AcqRelBB);
1424     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1425                  llvm::AtomicOrdering::AcquireRelease, Scope);
1426     Builder.CreateBr(ContBB);
1427     SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acq_rel),
1428                 AcqRelBB);
1429   }
1430   Builder.SetInsertPoint(SeqCstBB);
1431   EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1432                llvm::AtomicOrdering::SequentiallyConsistent, Scope);
1433   Builder.CreateBr(ContBB);
1434   SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
1435               SeqCstBB);
1436 
1437   // Cleanup and return
1438   Builder.SetInsertPoint(ContBB);
1439   if (RValTy->isVoidType())
1440     return RValue::get(nullptr);
1441 
1442   assert(Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits());
1443   return convertTempToRValue(
1444       Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1445                                       Dest.getAddressSpace())),
1446       RValTy, E->getExprLoc());
1447 }
1448 
1449 Address AtomicInfo::emitCastToAtomicIntPointer(Address addr) const {
1450   unsigned addrspace =
1451     cast<llvm::PointerType>(addr.getPointer()->getType())->getAddressSpace();
1452   llvm::IntegerType *ty =
1453     llvm::IntegerType::get(CGF.getLLVMContext(), AtomicSizeInBits);
1454   return CGF.Builder.CreateBitCast(addr, ty->getPointerTo(addrspace));
1455 }
1456 
1457 Address AtomicInfo::convertToAtomicIntPointer(Address Addr) const {
1458   llvm::Type *Ty = Addr.getElementType();
1459   uint64_t SourceSizeInBits = CGF.CGM.getDataLayout().getTypeSizeInBits(Ty);
1460   if (SourceSizeInBits != AtomicSizeInBits) {
1461     Address Tmp = CreateTempAlloca();
1462     CGF.Builder.CreateMemCpy(Tmp, Addr,
1463                              std::min(AtomicSizeInBits, SourceSizeInBits) / 8);
1464     Addr = Tmp;
1465   }
1466 
1467   return emitCastToAtomicIntPointer(Addr);
1468 }
1469 
1470 RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
1471                                              AggValueSlot resultSlot,
1472                                              SourceLocation loc,
1473                                              bool asValue) const {
1474   if (LVal.isSimple()) {
1475     if (EvaluationKind == TEK_Aggregate)
1476       return resultSlot.asRValue();
1477 
1478     // Drill into the padding structure if we have one.
1479     if (hasPadding())
1480       addr = CGF.Builder.CreateStructGEP(addr, 0);
1481 
1482     // Otherwise, just convert the temporary to an r-value using the
1483     // normal conversion routine.
1484     return CGF.convertTempToRValue(addr, getValueType(), loc);
1485   }
1486   if (!asValue)
1487     // Get RValue from temp memory as atomic for non-simple lvalues
1488     return RValue::get(CGF.Builder.CreateLoad(addr));
1489   if (LVal.isBitField())
1490     return CGF.EmitLoadOfBitfieldLValue(
1491         LValue::MakeBitfield(addr, LVal.getBitFieldInfo(), LVal.getType(),
1492                              LVal.getBaseInfo(), TBAAAccessInfo()), loc);
1493   if (LVal.isVectorElt())
1494     return CGF.EmitLoadOfLValue(
1495         LValue::MakeVectorElt(addr, LVal.getVectorIdx(), LVal.getType(),
1496                               LVal.getBaseInfo(), TBAAAccessInfo()), loc);
1497   assert(LVal.isExtVectorElt());
1498   return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
1499       addr, LVal.getExtVectorElts(), LVal.getType(),
1500       LVal.getBaseInfo(), TBAAAccessInfo()));
1501 }
1502 
1503 RValue AtomicInfo::ConvertIntToValueOrAtomic(llvm::Value *IntVal,
1504                                              AggValueSlot ResultSlot,
1505                                              SourceLocation Loc,
1506                                              bool AsValue) const {
1507   // Try not to in some easy cases.
1508   assert(IntVal->getType()->isIntegerTy() && "Expected integer value");
1509   if (getEvaluationKind() == TEK_Scalar &&
1510       (((!LVal.isBitField() ||
1511          LVal.getBitFieldInfo().Size == ValueSizeInBits) &&
1512         !hasPadding()) ||
1513        !AsValue)) {
1514     auto *ValTy = AsValue
1515                       ? CGF.ConvertTypeForMem(ValueTy)
1516                       : getAtomicAddress().getType()->getPointerElementType();
1517     if (ValTy->isIntegerTy()) {
1518       assert(IntVal->getType() == ValTy && "Different integer types.");
1519       return RValue::get(CGF.EmitFromMemory(IntVal, ValueTy));
1520     } else if (ValTy->isPointerTy())
1521       return RValue::get(CGF.Builder.CreateIntToPtr(IntVal, ValTy));
1522     else if (llvm::CastInst::isBitCastable(IntVal->getType(), ValTy))
1523       return RValue::get(CGF.Builder.CreateBitCast(IntVal, ValTy));
1524   }
1525 
1526   // Create a temporary.  This needs to be big enough to hold the
1527   // atomic integer.
1528   Address Temp = Address::invalid();
1529   bool TempIsVolatile = false;
1530   if (AsValue && getEvaluationKind() == TEK_Aggregate) {
1531     assert(!ResultSlot.isIgnored());
1532     Temp = ResultSlot.getAddress();
1533     TempIsVolatile = ResultSlot.isVolatile();
1534   } else {
1535     Temp = CreateTempAlloca();
1536   }
1537 
1538   // Slam the integer into the temporary.
1539   Address CastTemp = emitCastToAtomicIntPointer(Temp);
1540   CGF.Builder.CreateStore(IntVal, CastTemp)
1541       ->setVolatile(TempIsVolatile);
1542 
1543   return convertAtomicTempToRValue(Temp, ResultSlot, Loc, AsValue);
1544 }
1545 
1546 void AtomicInfo::EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
1547                                        llvm::AtomicOrdering AO, bool) {
1548   // void __atomic_load(size_t size, void *mem, void *return, int order);
1549   CallArgList Args;
1550   Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
1551   Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
1552            CGF.getContext().VoidPtrTy);
1553   Args.add(RValue::get(CGF.EmitCastToVoidPtr(AddForLoaded)),
1554            CGF.getContext().VoidPtrTy);
1555   Args.add(
1556       RValue::get(llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(AO))),
1557       CGF.getContext().IntTy);
1558   emitAtomicLibcall(CGF, "__atomic_load", CGF.getContext().VoidTy, Args);
1559 }
1560 
1561 llvm::Value *AtomicInfo::EmitAtomicLoadOp(llvm::AtomicOrdering AO,
1562                                           bool IsVolatile) {
1563   // Okay, we're doing this natively.
1564   Address Addr = getAtomicAddressAsAtomicIntPointer();
1565   llvm::LoadInst *Load = CGF.Builder.CreateLoad(Addr, "atomic-load");
1566   Load->setAtomic(AO);
1567 
1568   // Other decoration.
1569   if (IsVolatile)
1570     Load->setVolatile(true);
1571   CGF.CGM.DecorateInstructionWithTBAA(Load, LVal.getTBAAInfo());
1572   return Load;
1573 }
1574 
1575 /// An LValue is a candidate for having its loads and stores be made atomic if
1576 /// we are operating under /volatile:ms *and* the LValue itself is volatile and
1577 /// performing such an operation can be performed without a libcall.
1578 bool CodeGenFunction::LValueIsSuitableForInlineAtomic(LValue LV) {
1579   if (!CGM.getCodeGenOpts().MSVolatile) return false;
1580   AtomicInfo AI(*this, LV);
1581   bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
1582   // An atomic is inline if we don't need to use a libcall.
1583   bool AtomicIsInline = !AI.shouldUseLibcall();
1584   // MSVC doesn't seem to do this for types wider than a pointer.
1585   if (getContext().getTypeSize(LV.getType()) >
1586       getContext().getTypeSize(getContext().getIntPtrType()))
1587     return false;
1588   return IsVolatile && AtomicIsInline;
1589 }
1590 
1591 RValue CodeGenFunction::EmitAtomicLoad(LValue LV, SourceLocation SL,
1592                                        AggValueSlot Slot) {
1593   llvm::AtomicOrdering AO;
1594   bool IsVolatile = LV.isVolatileQualified();
1595   if (LV.getType()->isAtomicType()) {
1596     AO = llvm::AtomicOrdering::SequentiallyConsistent;
1597   } else {
1598     AO = llvm::AtomicOrdering::Acquire;
1599     IsVolatile = true;
1600   }
1601   return EmitAtomicLoad(LV, SL, AO, IsVolatile, Slot);
1602 }
1603 
1604 RValue AtomicInfo::EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
1605                                   bool AsValue, llvm::AtomicOrdering AO,
1606                                   bool IsVolatile) {
1607   // Check whether we should use a library call.
1608   if (shouldUseLibcall()) {
1609     Address TempAddr = Address::invalid();
1610     if (LVal.isSimple() && !ResultSlot.isIgnored()) {
1611       assert(getEvaluationKind() == TEK_Aggregate);
1612       TempAddr = ResultSlot.getAddress();
1613     } else
1614       TempAddr = CreateTempAlloca();
1615 
1616     EmitAtomicLoadLibcall(TempAddr.getPointer(), AO, IsVolatile);
1617 
1618     // Okay, turn that back into the original value or whole atomic (for
1619     // non-simple lvalues) type.
1620     return convertAtomicTempToRValue(TempAddr, ResultSlot, Loc, AsValue);
1621   }
1622 
1623   // Okay, we're doing this natively.
1624   auto *Load = EmitAtomicLoadOp(AO, IsVolatile);
1625 
1626   // If we're ignoring an aggregate return, don't do anything.
1627   if (getEvaluationKind() == TEK_Aggregate && ResultSlot.isIgnored())
1628     return RValue::getAggregate(Address::invalid(), false);
1629 
1630   // Okay, turn that back into the original value or atomic (for non-simple
1631   // lvalues) type.
1632   return ConvertIntToValueOrAtomic(Load, ResultSlot, Loc, AsValue);
1633 }
1634 
1635 /// Emit a load from an l-value of atomic type.  Note that the r-value
1636 /// we produce is an r-value of the atomic *value* type.
1637 RValue CodeGenFunction::EmitAtomicLoad(LValue src, SourceLocation loc,
1638                                        llvm::AtomicOrdering AO, bool IsVolatile,
1639                                        AggValueSlot resultSlot) {
1640   AtomicInfo Atomics(*this, src);
1641   return Atomics.EmitAtomicLoad(resultSlot, loc, /*AsValue=*/true, AO,
1642                                 IsVolatile);
1643 }
1644 
1645 /// Copy an r-value into memory as part of storing to an atomic type.
1646 /// This needs to create a bit-pattern suitable for atomic operations.
1647 void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
1648   assert(LVal.isSimple());
1649   // If we have an r-value, the rvalue should be of the atomic type,
1650   // which means that the caller is responsible for having zeroed
1651   // any padding.  Just do an aggregate copy of that type.
1652   if (rvalue.isAggregate()) {
1653     LValue Dest = CGF.MakeAddrLValue(getAtomicAddress(), getAtomicType());
1654     LValue Src = CGF.MakeAddrLValue(rvalue.getAggregateAddress(),
1655                                     getAtomicType());
1656     bool IsVolatile = rvalue.isVolatileQualified() ||
1657                       LVal.isVolatileQualified();
1658     CGF.EmitAggregateCopy(Dest, Src, getAtomicType(),
1659                           AggValueSlot::DoesNotOverlap, IsVolatile);
1660     return;
1661   }
1662 
1663   // Okay, otherwise we're copying stuff.
1664 
1665   // Zero out the buffer if necessary.
1666   emitMemSetZeroIfNecessary();
1667 
1668   // Drill past the padding if present.
1669   LValue TempLVal = projectValue();
1670 
1671   // Okay, store the rvalue in.
1672   if (rvalue.isScalar()) {
1673     CGF.EmitStoreOfScalar(rvalue.getScalarVal(), TempLVal, /*init*/ true);
1674   } else {
1675     CGF.EmitStoreOfComplex(rvalue.getComplexVal(), TempLVal, /*init*/ true);
1676   }
1677 }
1678 
1679 
1680 /// Materialize an r-value into memory for the purposes of storing it
1681 /// to an atomic type.
1682 Address AtomicInfo::materializeRValue(RValue rvalue) const {
1683   // Aggregate r-values are already in memory, and EmitAtomicStore
1684   // requires them to be values of the atomic type.
1685   if (rvalue.isAggregate())
1686     return rvalue.getAggregateAddress();
1687 
1688   // Otherwise, make a temporary and materialize into it.
1689   LValue TempLV = CGF.MakeAddrLValue(CreateTempAlloca(), getAtomicType());
1690   AtomicInfo Atomics(CGF, TempLV);
1691   Atomics.emitCopyIntoMemory(rvalue);
1692   return TempLV.getAddress(CGF);
1693 }
1694 
1695 llvm::Value *AtomicInfo::convertRValueToInt(RValue RVal) const {
1696   // If we've got a scalar value of the right size, try to avoid going
1697   // through memory.
1698   if (RVal.isScalar() && (!hasPadding() || !LVal.isSimple())) {
1699     llvm::Value *Value = RVal.getScalarVal();
1700     if (isa<llvm::IntegerType>(Value->getType()))
1701       return CGF.EmitToMemory(Value, ValueTy);
1702     else {
1703       llvm::IntegerType *InputIntTy = llvm::IntegerType::get(
1704           CGF.getLLVMContext(),
1705           LVal.isSimple() ? getValueSizeInBits() : getAtomicSizeInBits());
1706       if (isa<llvm::PointerType>(Value->getType()))
1707         return CGF.Builder.CreatePtrToInt(Value, InputIntTy);
1708       else if (llvm::BitCastInst::isBitCastable(Value->getType(), InputIntTy))
1709         return CGF.Builder.CreateBitCast(Value, InputIntTy);
1710     }
1711   }
1712   // Otherwise, we need to go through memory.
1713   // Put the r-value in memory.
1714   Address Addr = materializeRValue(RVal);
1715 
1716   // Cast the temporary to the atomic int type and pull a value out.
1717   Addr = emitCastToAtomicIntPointer(Addr);
1718   return CGF.Builder.CreateLoad(Addr);
1719 }
1720 
1721 std::pair<llvm::Value *, llvm::Value *> AtomicInfo::EmitAtomicCompareExchangeOp(
1722     llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
1723     llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak) {
1724   // Do the atomic store.
1725   Address Addr = getAtomicAddressAsAtomicIntPointer();
1726   auto *Inst = CGF.Builder.CreateAtomicCmpXchg(Addr.getPointer(),
1727                                                ExpectedVal, DesiredVal,
1728                                                Success, Failure);
1729   // Other decoration.
1730   Inst->setVolatile(LVal.isVolatileQualified());
1731   Inst->setWeak(IsWeak);
1732 
1733   // Okay, turn that back into the original value type.
1734   auto *PreviousVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/0);
1735   auto *SuccessFailureVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/1);
1736   return std::make_pair(PreviousVal, SuccessFailureVal);
1737 }
1738 
1739 llvm::Value *
1740 AtomicInfo::EmitAtomicCompareExchangeLibcall(llvm::Value *ExpectedAddr,
1741                                              llvm::Value *DesiredAddr,
1742                                              llvm::AtomicOrdering Success,
1743                                              llvm::AtomicOrdering Failure) {
1744   // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
1745   // void *desired, int success, int failure);
1746   CallArgList Args;
1747   Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
1748   Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
1749            CGF.getContext().VoidPtrTy);
1750   Args.add(RValue::get(CGF.EmitCastToVoidPtr(ExpectedAddr)),
1751            CGF.getContext().VoidPtrTy);
1752   Args.add(RValue::get(CGF.EmitCastToVoidPtr(DesiredAddr)),
1753            CGF.getContext().VoidPtrTy);
1754   Args.add(RValue::get(
1755                llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Success))),
1756            CGF.getContext().IntTy);
1757   Args.add(RValue::get(
1758                llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Failure))),
1759            CGF.getContext().IntTy);
1760   auto SuccessFailureRVal = emitAtomicLibcall(CGF, "__atomic_compare_exchange",
1761                                               CGF.getContext().BoolTy, Args);
1762 
1763   return SuccessFailureRVal.getScalarVal();
1764 }
1765 
1766 std::pair<RValue, llvm::Value *> AtomicInfo::EmitAtomicCompareExchange(
1767     RValue Expected, RValue Desired, llvm::AtomicOrdering Success,
1768     llvm::AtomicOrdering Failure, bool IsWeak) {
1769   // Check whether we should use a library call.
1770   if (shouldUseLibcall()) {
1771     // Produce a source address.
1772     Address ExpectedAddr = materializeRValue(Expected);
1773     Address DesiredAddr = materializeRValue(Desired);
1774     auto *Res = EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1775                                                  DesiredAddr.getPointer(),
1776                                                  Success, Failure);
1777     return std::make_pair(
1778         convertAtomicTempToRValue(ExpectedAddr, AggValueSlot::ignored(),
1779                                   SourceLocation(), /*AsValue=*/false),
1780         Res);
1781   }
1782 
1783   // If we've got a scalar value of the right size, try to avoid going
1784   // through memory.
1785   auto *ExpectedVal = convertRValueToInt(Expected);
1786   auto *DesiredVal = convertRValueToInt(Desired);
1787   auto Res = EmitAtomicCompareExchangeOp(ExpectedVal, DesiredVal, Success,
1788                                          Failure, IsWeak);
1789   return std::make_pair(
1790       ConvertIntToValueOrAtomic(Res.first, AggValueSlot::ignored(),
1791                                 SourceLocation(), /*AsValue=*/false),
1792       Res.second);
1793 }
1794 
1795 static void
1796 EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal,
1797                       const llvm::function_ref<RValue(RValue)> &UpdateOp,
1798                       Address DesiredAddr) {
1799   RValue UpRVal;
1800   LValue AtomicLVal = Atomics.getAtomicLValue();
1801   LValue DesiredLVal;
1802   if (AtomicLVal.isSimple()) {
1803     UpRVal = OldRVal;
1804     DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
1805   } else {
1806     // Build new lvalue for temp address.
1807     Address Ptr = Atomics.materializeRValue(OldRVal);
1808     LValue UpdateLVal;
1809     if (AtomicLVal.isBitField()) {
1810       UpdateLVal =
1811           LValue::MakeBitfield(Ptr, AtomicLVal.getBitFieldInfo(),
1812                                AtomicLVal.getType(),
1813                                AtomicLVal.getBaseInfo(),
1814                                AtomicLVal.getTBAAInfo());
1815       DesiredLVal =
1816           LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
1817                                AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1818                                AtomicLVal.getTBAAInfo());
1819     } else if (AtomicLVal.isVectorElt()) {
1820       UpdateLVal = LValue::MakeVectorElt(Ptr, AtomicLVal.getVectorIdx(),
1821                                          AtomicLVal.getType(),
1822                                          AtomicLVal.getBaseInfo(),
1823                                          AtomicLVal.getTBAAInfo());
1824       DesiredLVal = LValue::MakeVectorElt(
1825           DesiredAddr, AtomicLVal.getVectorIdx(), AtomicLVal.getType(),
1826           AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1827     } else {
1828       assert(AtomicLVal.isExtVectorElt());
1829       UpdateLVal = LValue::MakeExtVectorElt(Ptr, AtomicLVal.getExtVectorElts(),
1830                                             AtomicLVal.getType(),
1831                                             AtomicLVal.getBaseInfo(),
1832                                             AtomicLVal.getTBAAInfo());
1833       DesiredLVal = LValue::MakeExtVectorElt(
1834           DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
1835           AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1836     }
1837     UpRVal = CGF.EmitLoadOfLValue(UpdateLVal, SourceLocation());
1838   }
1839   // Store new value in the corresponding memory area.
1840   RValue NewRVal = UpdateOp(UpRVal);
1841   if (NewRVal.isScalar()) {
1842     CGF.EmitStoreThroughLValue(NewRVal, DesiredLVal);
1843   } else {
1844     assert(NewRVal.isComplex());
1845     CGF.EmitStoreOfComplex(NewRVal.getComplexVal(), DesiredLVal,
1846                            /*isInit=*/false);
1847   }
1848 }
1849 
1850 void AtomicInfo::EmitAtomicUpdateLibcall(
1851     llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1852     bool IsVolatile) {
1853   auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1854 
1855   Address ExpectedAddr = CreateTempAlloca();
1856 
1857   EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
1858   auto *ContBB = CGF.createBasicBlock("atomic_cont");
1859   auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1860   CGF.EmitBlock(ContBB);
1861   Address DesiredAddr = CreateTempAlloca();
1862   if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1863       requiresMemSetZero(getAtomicAddress().getElementType())) {
1864     auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1865     CGF.Builder.CreateStore(OldVal, DesiredAddr);
1866   }
1867   auto OldRVal = convertAtomicTempToRValue(ExpectedAddr,
1868                                            AggValueSlot::ignored(),
1869                                            SourceLocation(), /*AsValue=*/false);
1870   EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, DesiredAddr);
1871   auto *Res =
1872       EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1873                                        DesiredAddr.getPointer(),
1874                                        AO, Failure);
1875   CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1876   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1877 }
1878 
1879 void AtomicInfo::EmitAtomicUpdateOp(
1880     llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1881     bool IsVolatile) {
1882   auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1883 
1884   // Do the atomic load.
1885   auto *OldVal = EmitAtomicLoadOp(Failure, IsVolatile);
1886   // For non-simple lvalues perform compare-and-swap procedure.
1887   auto *ContBB = CGF.createBasicBlock("atomic_cont");
1888   auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1889   auto *CurBB = CGF.Builder.GetInsertBlock();
1890   CGF.EmitBlock(ContBB);
1891   llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1892                                              /*NumReservedValues=*/2);
1893   PHI->addIncoming(OldVal, CurBB);
1894   Address NewAtomicAddr = CreateTempAlloca();
1895   Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
1896   if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1897       requiresMemSetZero(getAtomicAddress().getElementType())) {
1898     CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
1899   }
1900   auto OldRVal = ConvertIntToValueOrAtomic(PHI, AggValueSlot::ignored(),
1901                                            SourceLocation(), /*AsValue=*/false);
1902   EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, NewAtomicAddr);
1903   auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
1904   // Try to write new value using cmpxchg operation.
1905   auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1906   PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1907   CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1908   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1909 }
1910 
1911 static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics,
1912                                   RValue UpdateRVal, Address DesiredAddr) {
1913   LValue AtomicLVal = Atomics.getAtomicLValue();
1914   LValue DesiredLVal;
1915   // Build new lvalue for temp address.
1916   if (AtomicLVal.isBitField()) {
1917     DesiredLVal =
1918         LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
1919                              AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1920                              AtomicLVal.getTBAAInfo());
1921   } else if (AtomicLVal.isVectorElt()) {
1922     DesiredLVal =
1923         LValue::MakeVectorElt(DesiredAddr, AtomicLVal.getVectorIdx(),
1924                               AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1925                               AtomicLVal.getTBAAInfo());
1926   } else {
1927     assert(AtomicLVal.isExtVectorElt());
1928     DesiredLVal = LValue::MakeExtVectorElt(
1929         DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
1930         AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1931   }
1932   // Store new value in the corresponding memory area.
1933   assert(UpdateRVal.isScalar());
1934   CGF.EmitStoreThroughLValue(UpdateRVal, DesiredLVal);
1935 }
1936 
1937 void AtomicInfo::EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
1938                                          RValue UpdateRVal, bool IsVolatile) {
1939   auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1940 
1941   Address ExpectedAddr = CreateTempAlloca();
1942 
1943   EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
1944   auto *ContBB = CGF.createBasicBlock("atomic_cont");
1945   auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1946   CGF.EmitBlock(ContBB);
1947   Address DesiredAddr = CreateTempAlloca();
1948   if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1949       requiresMemSetZero(getAtomicAddress().getElementType())) {
1950     auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1951     CGF.Builder.CreateStore(OldVal, DesiredAddr);
1952   }
1953   EmitAtomicUpdateValue(CGF, *this, UpdateRVal, DesiredAddr);
1954   auto *Res =
1955       EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1956                                        DesiredAddr.getPointer(),
1957                                        AO, Failure);
1958   CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1959   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1960 }
1961 
1962 void AtomicInfo::EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRVal,
1963                                     bool IsVolatile) {
1964   auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1965 
1966   // Do the atomic load.
1967   auto *OldVal = EmitAtomicLoadOp(Failure, IsVolatile);
1968   // For non-simple lvalues perform compare-and-swap procedure.
1969   auto *ContBB = CGF.createBasicBlock("atomic_cont");
1970   auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1971   auto *CurBB = CGF.Builder.GetInsertBlock();
1972   CGF.EmitBlock(ContBB);
1973   llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1974                                              /*NumReservedValues=*/2);
1975   PHI->addIncoming(OldVal, CurBB);
1976   Address NewAtomicAddr = CreateTempAlloca();
1977   Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
1978   if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1979       requiresMemSetZero(getAtomicAddress().getElementType())) {
1980     CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
1981   }
1982   EmitAtomicUpdateValue(CGF, *this, UpdateRVal, NewAtomicAddr);
1983   auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
1984   // Try to write new value using cmpxchg operation.
1985   auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1986   PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1987   CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1988   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1989 }
1990 
1991 void AtomicInfo::EmitAtomicUpdate(
1992     llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1993     bool IsVolatile) {
1994   if (shouldUseLibcall()) {
1995     EmitAtomicUpdateLibcall(AO, UpdateOp, IsVolatile);
1996   } else {
1997     EmitAtomicUpdateOp(AO, UpdateOp, IsVolatile);
1998   }
1999 }
2000 
2001 void AtomicInfo::EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
2002                                   bool IsVolatile) {
2003   if (shouldUseLibcall()) {
2004     EmitAtomicUpdateLibcall(AO, UpdateRVal, IsVolatile);
2005   } else {
2006     EmitAtomicUpdateOp(AO, UpdateRVal, IsVolatile);
2007   }
2008 }
2009 
2010 void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue lvalue,
2011                                       bool isInit) {
2012   bool IsVolatile = lvalue.isVolatileQualified();
2013   llvm::AtomicOrdering AO;
2014   if (lvalue.getType()->isAtomicType()) {
2015     AO = llvm::AtomicOrdering::SequentiallyConsistent;
2016   } else {
2017     AO = llvm::AtomicOrdering::Release;
2018     IsVolatile = true;
2019   }
2020   return EmitAtomicStore(rvalue, lvalue, AO, IsVolatile, isInit);
2021 }
2022 
2023 /// Emit a store to an l-value of atomic type.
2024 ///
2025 /// Note that the r-value is expected to be an r-value *of the atomic
2026 /// type*; this means that for aggregate r-values, it should include
2027 /// storage for any padding that was necessary.
2028 void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue dest,
2029                                       llvm::AtomicOrdering AO, bool IsVolatile,
2030                                       bool isInit) {
2031   // If this is an aggregate r-value, it should agree in type except
2032   // maybe for address-space qualification.
2033   assert(!rvalue.isAggregate() ||
2034          rvalue.getAggregateAddress().getElementType() ==
2035              dest.getAddress(*this).getElementType());
2036 
2037   AtomicInfo atomics(*this, dest);
2038   LValue LVal = atomics.getAtomicLValue();
2039 
2040   // If this is an initialization, just put the value there normally.
2041   if (LVal.isSimple()) {
2042     if (isInit) {
2043       atomics.emitCopyIntoMemory(rvalue);
2044       return;
2045     }
2046 
2047     // Check whether we should use a library call.
2048     if (atomics.shouldUseLibcall()) {
2049       // Produce a source address.
2050       Address srcAddr = atomics.materializeRValue(rvalue);
2051 
2052       // void __atomic_store(size_t size, void *mem, void *val, int order)
2053       CallArgList args;
2054       args.add(RValue::get(atomics.getAtomicSizeValue()),
2055                getContext().getSizeType());
2056       args.add(RValue::get(EmitCastToVoidPtr(atomics.getAtomicPointer())),
2057                getContext().VoidPtrTy);
2058       args.add(RValue::get(EmitCastToVoidPtr(srcAddr.getPointer())),
2059                getContext().VoidPtrTy);
2060       args.add(
2061           RValue::get(llvm::ConstantInt::get(IntTy, (int)llvm::toCABI(AO))),
2062           getContext().IntTy);
2063       emitAtomicLibcall(*this, "__atomic_store", getContext().VoidTy, args);
2064       return;
2065     }
2066 
2067     // Okay, we're doing this natively.
2068     llvm::Value *intValue = atomics.convertRValueToInt(rvalue);
2069 
2070     // Do the atomic store.
2071     Address addr =
2072         atomics.emitCastToAtomicIntPointer(atomics.getAtomicAddress());
2073     intValue = Builder.CreateIntCast(
2074         intValue, addr.getElementType(), /*isSigned=*/false);
2075     llvm::StoreInst *store = Builder.CreateStore(intValue, addr);
2076 
2077     if (AO == llvm::AtomicOrdering::Acquire)
2078       AO = llvm::AtomicOrdering::Monotonic;
2079     else if (AO == llvm::AtomicOrdering::AcquireRelease)
2080       AO = llvm::AtomicOrdering::Release;
2081     // Initializations don't need to be atomic.
2082     if (!isInit)
2083       store->setAtomic(AO);
2084 
2085     // Other decoration.
2086     if (IsVolatile)
2087       store->setVolatile(true);
2088     CGM.DecorateInstructionWithTBAA(store, dest.getTBAAInfo());
2089     return;
2090   }
2091 
2092   // Emit simple atomic update operation.
2093   atomics.EmitAtomicUpdate(AO, rvalue, IsVolatile);
2094 }
2095 
2096 /// Emit a compare-and-exchange op for atomic type.
2097 ///
2098 std::pair<RValue, llvm::Value *> CodeGenFunction::EmitAtomicCompareExchange(
2099     LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2100     llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak,
2101     AggValueSlot Slot) {
2102   // If this is an aggregate r-value, it should agree in type except
2103   // maybe for address-space qualification.
2104   assert(!Expected.isAggregate() ||
2105          Expected.getAggregateAddress().getElementType() ==
2106              Obj.getAddress(*this).getElementType());
2107   assert(!Desired.isAggregate() ||
2108          Desired.getAggregateAddress().getElementType() ==
2109              Obj.getAddress(*this).getElementType());
2110   AtomicInfo Atomics(*this, Obj);
2111 
2112   return Atomics.EmitAtomicCompareExchange(Expected, Desired, Success, Failure,
2113                                            IsWeak);
2114 }
2115 
2116 void CodeGenFunction::EmitAtomicUpdate(
2117     LValue LVal, llvm::AtomicOrdering AO,
2118     const llvm::function_ref<RValue(RValue)> &UpdateOp, bool IsVolatile) {
2119   AtomicInfo Atomics(*this, LVal);
2120   Atomics.EmitAtomicUpdate(AO, UpdateOp, IsVolatile);
2121 }
2122 
2123 void CodeGenFunction::EmitAtomicInit(Expr *init, LValue dest) {
2124   AtomicInfo atomics(*this, dest);
2125 
2126   switch (atomics.getEvaluationKind()) {
2127   case TEK_Scalar: {
2128     llvm::Value *value = EmitScalarExpr(init);
2129     atomics.emitCopyIntoMemory(RValue::get(value));
2130     return;
2131   }
2132 
2133   case TEK_Complex: {
2134     ComplexPairTy value = EmitComplexExpr(init);
2135     atomics.emitCopyIntoMemory(RValue::getComplex(value));
2136     return;
2137   }
2138 
2139   case TEK_Aggregate: {
2140     // Fix up the destination if the initializer isn't an expression
2141     // of atomic type.
2142     bool Zeroed = false;
2143     if (!init->getType()->isAtomicType()) {
2144       Zeroed = atomics.emitMemSetZeroIfNecessary();
2145       dest = atomics.projectValue();
2146     }
2147 
2148     // Evaluate the expression directly into the destination.
2149     AggValueSlot slot = AggValueSlot::forLValue(
2150         dest, *this, AggValueSlot::IsNotDestructed,
2151         AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
2152         AggValueSlot::DoesNotOverlap,
2153         Zeroed ? AggValueSlot::IsZeroed : AggValueSlot::IsNotZeroed);
2154 
2155     EmitAggExpr(init, slot);
2156     return;
2157   }
2158   }
2159   llvm_unreachable("bad evaluation kind");
2160 }
2161