xref: /freebsd-src/contrib/llvm-project/clang/lib/CodeGen/CGAtomic.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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__opencl_atomic_compare_exchange_strong:
528     emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
529                                 FailureOrder, Size, Order, Scope);
530     return;
531   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
532   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
533     emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
534                                 FailureOrder, Size, Order, Scope);
535     return;
536   case AtomicExpr::AO__atomic_compare_exchange:
537   case AtomicExpr::AO__atomic_compare_exchange_n: {
538     if (llvm::ConstantInt *IsWeakC = dyn_cast<llvm::ConstantInt>(IsWeak)) {
539       emitAtomicCmpXchgFailureSet(CGF, E, IsWeakC->getZExtValue(), Dest, Ptr,
540                                   Val1, Val2, FailureOrder, Size, Order, Scope);
541     } else {
542       // Create all the relevant BB's
543       llvm::BasicBlock *StrongBB =
544           CGF.createBasicBlock("cmpxchg.strong", CGF.CurFn);
545       llvm::BasicBlock *WeakBB = CGF.createBasicBlock("cmxchg.weak", CGF.CurFn);
546       llvm::BasicBlock *ContBB =
547           CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
548 
549       llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(IsWeak, WeakBB);
550       SI->addCase(CGF.Builder.getInt1(false), StrongBB);
551 
552       CGF.Builder.SetInsertPoint(StrongBB);
553       emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
554                                   FailureOrder, Size, Order, Scope);
555       CGF.Builder.CreateBr(ContBB);
556 
557       CGF.Builder.SetInsertPoint(WeakBB);
558       emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
559                                   FailureOrder, Size, Order, Scope);
560       CGF.Builder.CreateBr(ContBB);
561 
562       CGF.Builder.SetInsertPoint(ContBB);
563     }
564     return;
565   }
566   case AtomicExpr::AO__c11_atomic_load:
567   case AtomicExpr::AO__opencl_atomic_load:
568   case AtomicExpr::AO__atomic_load_n:
569   case AtomicExpr::AO__atomic_load: {
570     llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
571     Load->setAtomic(Order, Scope);
572     Load->setVolatile(E->isVolatile());
573     CGF.Builder.CreateStore(Load, Dest);
574     return;
575   }
576 
577   case AtomicExpr::AO__c11_atomic_store:
578   case AtomicExpr::AO__opencl_atomic_store:
579   case AtomicExpr::AO__atomic_store:
580   case AtomicExpr::AO__atomic_store_n: {
581     llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
582     llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
583     Store->setAtomic(Order, Scope);
584     Store->setVolatile(E->isVolatile());
585     return;
586   }
587 
588   case AtomicExpr::AO__c11_atomic_exchange:
589   case AtomicExpr::AO__opencl_atomic_exchange:
590   case AtomicExpr::AO__atomic_exchange_n:
591   case AtomicExpr::AO__atomic_exchange:
592     Op = llvm::AtomicRMWInst::Xchg;
593     break;
594 
595   case AtomicExpr::AO__atomic_add_fetch:
596     PostOp = E->getValueType()->isFloatingType() ? llvm::Instruction::FAdd
597                                                  : llvm::Instruction::Add;
598     LLVM_FALLTHROUGH;
599   case AtomicExpr::AO__c11_atomic_fetch_add:
600   case AtomicExpr::AO__opencl_atomic_fetch_add:
601   case AtomicExpr::AO__atomic_fetch_add:
602     Op = E->getValueType()->isFloatingType() ? llvm::AtomicRMWInst::FAdd
603                                              : llvm::AtomicRMWInst::Add;
604     break;
605 
606   case AtomicExpr::AO__atomic_sub_fetch:
607     PostOp = E->getValueType()->isFloatingType() ? llvm::Instruction::FSub
608                                                  : llvm::Instruction::Sub;
609     LLVM_FALLTHROUGH;
610   case AtomicExpr::AO__c11_atomic_fetch_sub:
611   case AtomicExpr::AO__opencl_atomic_fetch_sub:
612   case AtomicExpr::AO__atomic_fetch_sub:
613     Op = E->getValueType()->isFloatingType() ? llvm::AtomicRMWInst::FSub
614                                              : llvm::AtomicRMWInst::Sub;
615     break;
616 
617   case AtomicExpr::AO__atomic_min_fetch:
618     PostOpMinMax = true;
619     LLVM_FALLTHROUGH;
620   case AtomicExpr::AO__c11_atomic_fetch_min:
621   case AtomicExpr::AO__opencl_atomic_fetch_min:
622   case AtomicExpr::AO__atomic_fetch_min:
623     Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Min
624                                                   : llvm::AtomicRMWInst::UMin;
625     break;
626 
627   case AtomicExpr::AO__atomic_max_fetch:
628     PostOpMinMax = true;
629     LLVM_FALLTHROUGH;
630   case AtomicExpr::AO__c11_atomic_fetch_max:
631   case AtomicExpr::AO__opencl_atomic_fetch_max:
632   case AtomicExpr::AO__atomic_fetch_max:
633     Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Max
634                                                   : llvm::AtomicRMWInst::UMax;
635     break;
636 
637   case AtomicExpr::AO__atomic_and_fetch:
638     PostOp = llvm::Instruction::And;
639     LLVM_FALLTHROUGH;
640   case AtomicExpr::AO__c11_atomic_fetch_and:
641   case AtomicExpr::AO__opencl_atomic_fetch_and:
642   case AtomicExpr::AO__atomic_fetch_and:
643     Op = llvm::AtomicRMWInst::And;
644     break;
645 
646   case AtomicExpr::AO__atomic_or_fetch:
647     PostOp = llvm::Instruction::Or;
648     LLVM_FALLTHROUGH;
649   case AtomicExpr::AO__c11_atomic_fetch_or:
650   case AtomicExpr::AO__opencl_atomic_fetch_or:
651   case AtomicExpr::AO__atomic_fetch_or:
652     Op = llvm::AtomicRMWInst::Or;
653     break;
654 
655   case AtomicExpr::AO__atomic_xor_fetch:
656     PostOp = llvm::Instruction::Xor;
657     LLVM_FALLTHROUGH;
658   case AtomicExpr::AO__c11_atomic_fetch_xor:
659   case AtomicExpr::AO__opencl_atomic_fetch_xor:
660   case AtomicExpr::AO__atomic_fetch_xor:
661     Op = llvm::AtomicRMWInst::Xor;
662     break;
663 
664   case AtomicExpr::AO__atomic_nand_fetch:
665     PostOp = llvm::Instruction::And; // the NOT is special cased below
666     LLVM_FALLTHROUGH;
667   case AtomicExpr::AO__c11_atomic_fetch_nand:
668   case AtomicExpr::AO__atomic_fetch_nand:
669     Op = llvm::AtomicRMWInst::Nand;
670     break;
671   }
672 
673   llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
674   llvm::AtomicRMWInst *RMWI =
675       CGF.Builder.CreateAtomicRMW(Op, Ptr.getPointer(), LoadVal1, Order, Scope);
676   RMWI->setVolatile(E->isVolatile());
677 
678   // For __atomic_*_fetch operations, perform the operation again to
679   // determine the value which was written.
680   llvm::Value *Result = RMWI;
681   if (PostOpMinMax)
682     Result = EmitPostAtomicMinMax(CGF.Builder, E->getOp(),
683                                   E->getValueType()->isSignedIntegerType(),
684                                   RMWI, LoadVal1);
685   else if (PostOp)
686     Result = CGF.Builder.CreateBinOp((llvm::Instruction::BinaryOps)PostOp, RMWI,
687                                      LoadVal1);
688   if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
689     Result = CGF.Builder.CreateNot(Result);
690   CGF.Builder.CreateStore(Result, Dest);
691 }
692 
693 // This function emits any expression (scalar, complex, or aggregate)
694 // into a temporary alloca.
695 static Address
696 EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
697   Address DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
698   CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
699                        /*Init*/ true);
700   return DeclPtr;
701 }
702 
703 static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *Expr, Address Dest,
704                          Address Ptr, Address Val1, Address Val2,
705                          llvm::Value *IsWeak, llvm::Value *FailureOrder,
706                          uint64_t Size, llvm::AtomicOrdering Order,
707                          llvm::Value *Scope) {
708   auto ScopeModel = Expr->getScopeModel();
709 
710   // LLVM atomic instructions always have synch scope. If clang atomic
711   // expression has no scope operand, use default LLVM synch scope.
712   if (!ScopeModel) {
713     EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
714                  Order, CGF.CGM.getLLVMContext().getOrInsertSyncScopeID(""));
715     return;
716   }
717 
718   // Handle constant scope.
719   if (auto SC = dyn_cast<llvm::ConstantInt>(Scope)) {
720     auto SCID = CGF.getTargetHooks().getLLVMSyncScopeID(
721         CGF.CGM.getLangOpts(), ScopeModel->map(SC->getZExtValue()),
722         Order, CGF.CGM.getLLVMContext());
723     EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
724                  Order, SCID);
725     return;
726   }
727 
728   // Handle non-constant scope.
729   auto &Builder = CGF.Builder;
730   auto Scopes = ScopeModel->getRuntimeValues();
731   llvm::DenseMap<unsigned, llvm::BasicBlock *> BB;
732   for (auto S : Scopes)
733     BB[S] = CGF.createBasicBlock(getAsString(ScopeModel->map(S)), CGF.CurFn);
734 
735   llvm::BasicBlock *ContBB =
736       CGF.createBasicBlock("atomic.scope.continue", CGF.CurFn);
737 
738   auto *SC = Builder.CreateIntCast(Scope, Builder.getInt32Ty(), false);
739   // If unsupported synch scope is encountered at run time, assume a fallback
740   // synch scope value.
741   auto FallBack = ScopeModel->getFallBackValue();
742   llvm::SwitchInst *SI = Builder.CreateSwitch(SC, BB[FallBack]);
743   for (auto S : Scopes) {
744     auto *B = BB[S];
745     if (S != FallBack)
746       SI->addCase(Builder.getInt32(S), B);
747 
748     Builder.SetInsertPoint(B);
749     EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
750                  Order,
751                  CGF.getTargetHooks().getLLVMSyncScopeID(CGF.CGM.getLangOpts(),
752                                                          ScopeModel->map(S),
753                                                          Order,
754                                                          CGF.getLLVMContext()));
755     Builder.CreateBr(ContBB);
756   }
757 
758   Builder.SetInsertPoint(ContBB);
759 }
760 
761 static void
762 AddDirectArgument(CodeGenFunction &CGF, CallArgList &Args,
763                   bool UseOptimizedLibcall, llvm::Value *Val, QualType ValTy,
764                   SourceLocation Loc, CharUnits SizeInChars) {
765   if (UseOptimizedLibcall) {
766     // Load value and pass it to the function directly.
767     CharUnits Align = CGF.getContext().getTypeAlignInChars(ValTy);
768     int64_t SizeInBits = CGF.getContext().toBits(SizeInChars);
769     ValTy =
770         CGF.getContext().getIntTypeForBitwidth(SizeInBits, /*Signed=*/false);
771     llvm::Type *IPtrTy = llvm::IntegerType::get(CGF.getLLVMContext(),
772                                                 SizeInBits)->getPointerTo();
773     Address Ptr = Address(CGF.Builder.CreateBitCast(Val, IPtrTy), Align);
774     Val = CGF.EmitLoadOfScalar(Ptr, false,
775                                CGF.getContext().getPointerType(ValTy),
776                                Loc);
777     // Coerce the value into an appropriately sized integer type.
778     Args.add(RValue::get(Val), ValTy);
779   } else {
780     // Non-optimized functions always take a reference.
781     Args.add(RValue::get(CGF.EmitCastToVoidPtr(Val)),
782                          CGF.getContext().VoidPtrTy);
783   }
784 }
785 
786 RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
787   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
788   QualType MemTy = AtomicTy;
789   if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
790     MemTy = AT->getValueType();
791   llvm::Value *IsWeak = nullptr, *OrderFail = nullptr;
792 
793   Address Val1 = Address::invalid();
794   Address Val2 = Address::invalid();
795   Address Dest = Address::invalid();
796   Address Ptr = EmitPointerWithAlignment(E->getPtr());
797 
798   if (E->getOp() == AtomicExpr::AO__c11_atomic_init ||
799       E->getOp() == AtomicExpr::AO__opencl_atomic_init) {
800     LValue lvalue = MakeAddrLValue(Ptr, AtomicTy);
801     EmitAtomicInit(E->getVal1(), lvalue);
802     return RValue::get(nullptr);
803   }
804 
805   auto TInfo = getContext().getTypeInfoInChars(AtomicTy);
806   uint64_t Size = TInfo.Width.getQuantity();
807   unsigned MaxInlineWidthInBits = getTarget().getMaxAtomicInlineWidth();
808 
809   bool Oversized = getContext().toBits(TInfo.Width) > MaxInlineWidthInBits;
810   bool Misaligned = (Ptr.getAlignment() % TInfo.Width) != 0;
811   bool UseLibcall = Misaligned | Oversized;
812   bool ShouldCastToIntPtrTy = true;
813 
814   CharUnits MaxInlineWidth =
815       getContext().toCharUnitsFromBits(MaxInlineWidthInBits);
816 
817   DiagnosticsEngine &Diags = CGM.getDiags();
818 
819   if (Misaligned) {
820     Diags.Report(E->getBeginLoc(), diag::warn_atomic_op_misaligned)
821         << (int)TInfo.Width.getQuantity()
822         << (int)Ptr.getAlignment().getQuantity();
823   }
824 
825   if (Oversized) {
826     Diags.Report(E->getBeginLoc(), diag::warn_atomic_op_oversized)
827         << (int)TInfo.Width.getQuantity() << (int)MaxInlineWidth.getQuantity();
828   }
829 
830   llvm::Value *Order = EmitScalarExpr(E->getOrder());
831   llvm::Value *Scope =
832       E->getScopeModel() ? EmitScalarExpr(E->getScope()) : nullptr;
833 
834   switch (E->getOp()) {
835   case AtomicExpr::AO__c11_atomic_init:
836   case AtomicExpr::AO__opencl_atomic_init:
837     llvm_unreachable("Already handled above with EmitAtomicInit!");
838 
839   case AtomicExpr::AO__c11_atomic_load:
840   case AtomicExpr::AO__opencl_atomic_load:
841   case AtomicExpr::AO__atomic_load_n:
842     break;
843 
844   case AtomicExpr::AO__atomic_load:
845     Dest = EmitPointerWithAlignment(E->getVal1());
846     break;
847 
848   case AtomicExpr::AO__atomic_store:
849     Val1 = EmitPointerWithAlignment(E->getVal1());
850     break;
851 
852   case AtomicExpr::AO__atomic_exchange:
853     Val1 = EmitPointerWithAlignment(E->getVal1());
854     Dest = EmitPointerWithAlignment(E->getVal2());
855     break;
856 
857   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
858   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
859   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
860   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
861   case AtomicExpr::AO__atomic_compare_exchange_n:
862   case AtomicExpr::AO__atomic_compare_exchange:
863     Val1 = EmitPointerWithAlignment(E->getVal1());
864     if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
865       Val2 = EmitPointerWithAlignment(E->getVal2());
866     else
867       Val2 = EmitValToTemp(*this, E->getVal2());
868     OrderFail = EmitScalarExpr(E->getOrderFail());
869     if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
870         E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
871       IsWeak = EmitScalarExpr(E->getWeak());
872     break;
873 
874   case AtomicExpr::AO__c11_atomic_fetch_add:
875   case AtomicExpr::AO__c11_atomic_fetch_sub:
876   case AtomicExpr::AO__opencl_atomic_fetch_add:
877   case AtomicExpr::AO__opencl_atomic_fetch_sub:
878     if (MemTy->isPointerType()) {
879       // For pointer arithmetic, we're required to do a bit of math:
880       // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
881       // ... but only for the C11 builtins. The GNU builtins expect the
882       // user to multiply by sizeof(T).
883       QualType Val1Ty = E->getVal1()->getType();
884       llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
885       CharUnits PointeeIncAmt =
886           getContext().getTypeSizeInChars(MemTy->getPointeeType());
887       Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
888       auto Temp = CreateMemTemp(Val1Ty, ".atomictmp");
889       Val1 = Temp;
890       EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Temp, Val1Ty));
891       break;
892     }
893     LLVM_FALLTHROUGH;
894   case AtomicExpr::AO__atomic_fetch_add:
895   case AtomicExpr::AO__atomic_fetch_sub:
896   case AtomicExpr::AO__atomic_add_fetch:
897   case AtomicExpr::AO__atomic_sub_fetch:
898     ShouldCastToIntPtrTy = !MemTy->isFloatingType();
899     LLVM_FALLTHROUGH;
900 
901   case AtomicExpr::AO__c11_atomic_store:
902   case AtomicExpr::AO__c11_atomic_exchange:
903   case AtomicExpr::AO__opencl_atomic_store:
904   case AtomicExpr::AO__opencl_atomic_exchange:
905   case AtomicExpr::AO__atomic_store_n:
906   case AtomicExpr::AO__atomic_exchange_n:
907   case AtomicExpr::AO__c11_atomic_fetch_and:
908   case AtomicExpr::AO__c11_atomic_fetch_or:
909   case AtomicExpr::AO__c11_atomic_fetch_xor:
910   case AtomicExpr::AO__c11_atomic_fetch_nand:
911   case AtomicExpr::AO__c11_atomic_fetch_max:
912   case AtomicExpr::AO__c11_atomic_fetch_min:
913   case AtomicExpr::AO__opencl_atomic_fetch_and:
914   case AtomicExpr::AO__opencl_atomic_fetch_or:
915   case AtomicExpr::AO__opencl_atomic_fetch_xor:
916   case AtomicExpr::AO__opencl_atomic_fetch_min:
917   case AtomicExpr::AO__opencl_atomic_fetch_max:
918   case AtomicExpr::AO__atomic_fetch_and:
919   case AtomicExpr::AO__atomic_fetch_or:
920   case AtomicExpr::AO__atomic_fetch_xor:
921   case AtomicExpr::AO__atomic_fetch_nand:
922   case AtomicExpr::AO__atomic_and_fetch:
923   case AtomicExpr::AO__atomic_or_fetch:
924   case AtomicExpr::AO__atomic_xor_fetch:
925   case AtomicExpr::AO__atomic_nand_fetch:
926   case AtomicExpr::AO__atomic_max_fetch:
927   case AtomicExpr::AO__atomic_min_fetch:
928   case AtomicExpr::AO__atomic_fetch_max:
929   case AtomicExpr::AO__atomic_fetch_min:
930     Val1 = EmitValToTemp(*this, E->getVal1());
931     break;
932   }
933 
934   QualType RValTy = E->getType().getUnqualifiedType();
935 
936   // The inlined atomics only function on iN types, where N is a power of 2. We
937   // need to make sure (via temporaries if necessary) that all incoming values
938   // are compatible.
939   LValue AtomicVal = MakeAddrLValue(Ptr, AtomicTy);
940   AtomicInfo Atomics(*this, AtomicVal);
941 
942   if (ShouldCastToIntPtrTy) {
943     Ptr = Atomics.emitCastToAtomicIntPointer(Ptr);
944     if (Val1.isValid())
945       Val1 = Atomics.convertToAtomicIntPointer(Val1);
946     if (Val2.isValid())
947       Val2 = Atomics.convertToAtomicIntPointer(Val2);
948   }
949   if (Dest.isValid()) {
950     if (ShouldCastToIntPtrTy)
951       Dest = Atomics.emitCastToAtomicIntPointer(Dest);
952   } else if (E->isCmpXChg())
953     Dest = CreateMemTemp(RValTy, "cmpxchg.bool");
954   else if (!RValTy->isVoidType()) {
955     Dest = Atomics.CreateTempAlloca();
956     if (ShouldCastToIntPtrTy)
957       Dest = Atomics.emitCastToAtomicIntPointer(Dest);
958   }
959 
960   // Use a library call.  See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
961   if (UseLibcall) {
962     bool UseOptimizedLibcall = false;
963     switch (E->getOp()) {
964     case AtomicExpr::AO__c11_atomic_init:
965     case AtomicExpr::AO__opencl_atomic_init:
966       llvm_unreachable("Already handled above with EmitAtomicInit!");
967 
968     case AtomicExpr::AO__c11_atomic_fetch_add:
969     case AtomicExpr::AO__opencl_atomic_fetch_add:
970     case AtomicExpr::AO__atomic_fetch_add:
971     case AtomicExpr::AO__c11_atomic_fetch_and:
972     case AtomicExpr::AO__opencl_atomic_fetch_and:
973     case AtomicExpr::AO__atomic_fetch_and:
974     case AtomicExpr::AO__c11_atomic_fetch_or:
975     case AtomicExpr::AO__opencl_atomic_fetch_or:
976     case AtomicExpr::AO__atomic_fetch_or:
977     case AtomicExpr::AO__c11_atomic_fetch_nand:
978     case AtomicExpr::AO__atomic_fetch_nand:
979     case AtomicExpr::AO__c11_atomic_fetch_sub:
980     case AtomicExpr::AO__opencl_atomic_fetch_sub:
981     case AtomicExpr::AO__atomic_fetch_sub:
982     case AtomicExpr::AO__c11_atomic_fetch_xor:
983     case AtomicExpr::AO__opencl_atomic_fetch_xor:
984     case AtomicExpr::AO__opencl_atomic_fetch_min:
985     case AtomicExpr::AO__opencl_atomic_fetch_max:
986     case AtomicExpr::AO__atomic_fetch_xor:
987     case AtomicExpr::AO__c11_atomic_fetch_max:
988     case AtomicExpr::AO__c11_atomic_fetch_min:
989     case AtomicExpr::AO__atomic_add_fetch:
990     case AtomicExpr::AO__atomic_and_fetch:
991     case AtomicExpr::AO__atomic_nand_fetch:
992     case AtomicExpr::AO__atomic_or_fetch:
993     case AtomicExpr::AO__atomic_sub_fetch:
994     case AtomicExpr::AO__atomic_xor_fetch:
995     case AtomicExpr::AO__atomic_fetch_max:
996     case AtomicExpr::AO__atomic_fetch_min:
997     case AtomicExpr::AO__atomic_max_fetch:
998     case AtomicExpr::AO__atomic_min_fetch:
999       // For these, only library calls for certain sizes exist.
1000       UseOptimizedLibcall = true;
1001       break;
1002 
1003     case AtomicExpr::AO__atomic_load:
1004     case AtomicExpr::AO__atomic_store:
1005     case AtomicExpr::AO__atomic_exchange:
1006     case AtomicExpr::AO__atomic_compare_exchange:
1007       // Use the generic version if we don't know that the operand will be
1008       // suitably aligned for the optimized version.
1009       if (Misaligned)
1010         break;
1011       LLVM_FALLTHROUGH;
1012     case AtomicExpr::AO__c11_atomic_load:
1013     case AtomicExpr::AO__c11_atomic_store:
1014     case AtomicExpr::AO__c11_atomic_exchange:
1015     case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1016     case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1017     case AtomicExpr::AO__opencl_atomic_load:
1018     case AtomicExpr::AO__opencl_atomic_store:
1019     case AtomicExpr::AO__opencl_atomic_exchange:
1020     case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1021     case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
1022     case AtomicExpr::AO__atomic_load_n:
1023     case AtomicExpr::AO__atomic_store_n:
1024     case AtomicExpr::AO__atomic_exchange_n:
1025     case AtomicExpr::AO__atomic_compare_exchange_n:
1026       // Only use optimized library calls for sizes for which they exist.
1027       // FIXME: Size == 16 optimized library functions exist too.
1028       if (Size == 1 || Size == 2 || Size == 4 || Size == 8)
1029         UseOptimizedLibcall = true;
1030       break;
1031     }
1032 
1033     CallArgList Args;
1034     if (!UseOptimizedLibcall) {
1035       // For non-optimized library calls, the size is the first parameter
1036       Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
1037                getContext().getSizeType());
1038     }
1039     // Atomic address is the first or second parameter
1040     // The OpenCL atomic library functions only accept pointer arguments to
1041     // generic address space.
1042     auto CastToGenericAddrSpace = [&](llvm::Value *V, QualType PT) {
1043       if (!E->isOpenCL())
1044         return V;
1045       auto AS = PT->castAs<PointerType>()->getPointeeType().getAddressSpace();
1046       if (AS == LangAS::opencl_generic)
1047         return V;
1048       auto DestAS = getContext().getTargetAddressSpace(LangAS::opencl_generic);
1049       auto T = V->getType();
1050       auto *DestType = T->getPointerElementType()->getPointerTo(DestAS);
1051 
1052       return getTargetHooks().performAddrSpaceCast(
1053           *this, V, AS, LangAS::opencl_generic, DestType, false);
1054     };
1055 
1056     Args.add(RValue::get(CastToGenericAddrSpace(
1057                  EmitCastToVoidPtr(Ptr.getPointer()), E->getPtr()->getType())),
1058              getContext().VoidPtrTy);
1059 
1060     std::string LibCallName;
1061     QualType LoweredMemTy =
1062       MemTy->isPointerType() ? getContext().getIntPtrType() : MemTy;
1063     QualType RetTy;
1064     bool HaveRetTy = false;
1065     llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
1066     bool PostOpMinMax = false;
1067     switch (E->getOp()) {
1068     case AtomicExpr::AO__c11_atomic_init:
1069     case AtomicExpr::AO__opencl_atomic_init:
1070       llvm_unreachable("Already handled!");
1071 
1072     // There is only one libcall for compare an exchange, because there is no
1073     // optimisation benefit possible from a libcall version of a weak compare
1074     // and exchange.
1075     // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
1076     //                                void *desired, int success, int failure)
1077     // bool __atomic_compare_exchange_N(T *mem, T *expected, T desired,
1078     //                                  int success, int failure)
1079     case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1080     case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1081     case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1082     case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
1083     case AtomicExpr::AO__atomic_compare_exchange:
1084     case AtomicExpr::AO__atomic_compare_exchange_n:
1085       LibCallName = "__atomic_compare_exchange";
1086       RetTy = getContext().BoolTy;
1087       HaveRetTy = true;
1088       Args.add(
1089           RValue::get(CastToGenericAddrSpace(
1090               EmitCastToVoidPtr(Val1.getPointer()), E->getVal1()->getType())),
1091           getContext().VoidPtrTy);
1092       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val2.getPointer(),
1093                         MemTy, E->getExprLoc(), TInfo.Width);
1094       Args.add(RValue::get(Order), getContext().IntTy);
1095       Order = OrderFail;
1096       break;
1097     // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
1098     //                        int order)
1099     // T __atomic_exchange_N(T *mem, T val, int order)
1100     case AtomicExpr::AO__c11_atomic_exchange:
1101     case AtomicExpr::AO__opencl_atomic_exchange:
1102     case AtomicExpr::AO__atomic_exchange_n:
1103     case AtomicExpr::AO__atomic_exchange:
1104       LibCallName = "__atomic_exchange";
1105       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1106                         MemTy, E->getExprLoc(), TInfo.Width);
1107       break;
1108     // void __atomic_store(size_t size, void *mem, void *val, int order)
1109     // void __atomic_store_N(T *mem, T val, int order)
1110     case AtomicExpr::AO__c11_atomic_store:
1111     case AtomicExpr::AO__opencl_atomic_store:
1112     case AtomicExpr::AO__atomic_store:
1113     case AtomicExpr::AO__atomic_store_n:
1114       LibCallName = "__atomic_store";
1115       RetTy = getContext().VoidTy;
1116       HaveRetTy = true;
1117       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1118                         MemTy, E->getExprLoc(), TInfo.Width);
1119       break;
1120     // void __atomic_load(size_t size, void *mem, void *return, int order)
1121     // T __atomic_load_N(T *mem, int order)
1122     case AtomicExpr::AO__c11_atomic_load:
1123     case AtomicExpr::AO__opencl_atomic_load:
1124     case AtomicExpr::AO__atomic_load:
1125     case AtomicExpr::AO__atomic_load_n:
1126       LibCallName = "__atomic_load";
1127       break;
1128     // T __atomic_add_fetch_N(T *mem, T val, int order)
1129     // T __atomic_fetch_add_N(T *mem, T val, int order)
1130     case AtomicExpr::AO__atomic_add_fetch:
1131       PostOp = llvm::Instruction::Add;
1132       LLVM_FALLTHROUGH;
1133     case AtomicExpr::AO__c11_atomic_fetch_add:
1134     case AtomicExpr::AO__opencl_atomic_fetch_add:
1135     case AtomicExpr::AO__atomic_fetch_add:
1136       LibCallName = "__atomic_fetch_add";
1137       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1138                         LoweredMemTy, E->getExprLoc(), TInfo.Width);
1139       break;
1140     // T __atomic_and_fetch_N(T *mem, T val, int order)
1141     // T __atomic_fetch_and_N(T *mem, T val, int order)
1142     case AtomicExpr::AO__atomic_and_fetch:
1143       PostOp = llvm::Instruction::And;
1144       LLVM_FALLTHROUGH;
1145     case AtomicExpr::AO__c11_atomic_fetch_and:
1146     case AtomicExpr::AO__opencl_atomic_fetch_and:
1147     case AtomicExpr::AO__atomic_fetch_and:
1148       LibCallName = "__atomic_fetch_and";
1149       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1150                         MemTy, E->getExprLoc(), TInfo.Width);
1151       break;
1152     // T __atomic_or_fetch_N(T *mem, T val, int order)
1153     // T __atomic_fetch_or_N(T *mem, T val, int order)
1154     case AtomicExpr::AO__atomic_or_fetch:
1155       PostOp = llvm::Instruction::Or;
1156       LLVM_FALLTHROUGH;
1157     case AtomicExpr::AO__c11_atomic_fetch_or:
1158     case AtomicExpr::AO__opencl_atomic_fetch_or:
1159     case AtomicExpr::AO__atomic_fetch_or:
1160       LibCallName = "__atomic_fetch_or";
1161       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1162                         MemTy, E->getExprLoc(), TInfo.Width);
1163       break;
1164     // T __atomic_sub_fetch_N(T *mem, T val, int order)
1165     // T __atomic_fetch_sub_N(T *mem, T val, int order)
1166     case AtomicExpr::AO__atomic_sub_fetch:
1167       PostOp = llvm::Instruction::Sub;
1168       LLVM_FALLTHROUGH;
1169     case AtomicExpr::AO__c11_atomic_fetch_sub:
1170     case AtomicExpr::AO__opencl_atomic_fetch_sub:
1171     case AtomicExpr::AO__atomic_fetch_sub:
1172       LibCallName = "__atomic_fetch_sub";
1173       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1174                         LoweredMemTy, E->getExprLoc(), TInfo.Width);
1175       break;
1176     // T __atomic_xor_fetch_N(T *mem, T val, int order)
1177     // T __atomic_fetch_xor_N(T *mem, T val, int order)
1178     case AtomicExpr::AO__atomic_xor_fetch:
1179       PostOp = llvm::Instruction::Xor;
1180       LLVM_FALLTHROUGH;
1181     case AtomicExpr::AO__c11_atomic_fetch_xor:
1182     case AtomicExpr::AO__opencl_atomic_fetch_xor:
1183     case AtomicExpr::AO__atomic_fetch_xor:
1184       LibCallName = "__atomic_fetch_xor";
1185       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1186                         MemTy, E->getExprLoc(), TInfo.Width);
1187       break;
1188     case AtomicExpr::AO__atomic_min_fetch:
1189       PostOpMinMax = true;
1190       LLVM_FALLTHROUGH;
1191     case AtomicExpr::AO__c11_atomic_fetch_min:
1192     case AtomicExpr::AO__atomic_fetch_min:
1193     case AtomicExpr::AO__opencl_atomic_fetch_min:
1194       LibCallName = E->getValueType()->isSignedIntegerType()
1195                         ? "__atomic_fetch_min"
1196                         : "__atomic_fetch_umin";
1197       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1198                         LoweredMemTy, E->getExprLoc(), TInfo.Width);
1199       break;
1200     case AtomicExpr::AO__atomic_max_fetch:
1201       PostOpMinMax = true;
1202       LLVM_FALLTHROUGH;
1203     case AtomicExpr::AO__c11_atomic_fetch_max:
1204     case AtomicExpr::AO__atomic_fetch_max:
1205     case AtomicExpr::AO__opencl_atomic_fetch_max:
1206       LibCallName = E->getValueType()->isSignedIntegerType()
1207                         ? "__atomic_fetch_max"
1208                         : "__atomic_fetch_umax";
1209       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1210                         LoweredMemTy, E->getExprLoc(), TInfo.Width);
1211       break;
1212     // T __atomic_nand_fetch_N(T *mem, T val, int order)
1213     // T __atomic_fetch_nand_N(T *mem, T val, int order)
1214     case AtomicExpr::AO__atomic_nand_fetch:
1215       PostOp = llvm::Instruction::And; // the NOT is special cased below
1216       LLVM_FALLTHROUGH;
1217     case AtomicExpr::AO__c11_atomic_fetch_nand:
1218     case AtomicExpr::AO__atomic_fetch_nand:
1219       LibCallName = "__atomic_fetch_nand";
1220       AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1221                         MemTy, E->getExprLoc(), TInfo.Width);
1222       break;
1223     }
1224 
1225     if (E->isOpenCL()) {
1226       LibCallName = std::string("__opencl") +
1227           StringRef(LibCallName).drop_front(1).str();
1228 
1229     }
1230     // Optimized functions have the size in their name.
1231     if (UseOptimizedLibcall)
1232       LibCallName += "_" + llvm::utostr(Size);
1233     // By default, assume we return a value of the atomic type.
1234     if (!HaveRetTy) {
1235       if (UseOptimizedLibcall) {
1236         // Value is returned directly.
1237         // The function returns an appropriately sized integer type.
1238         RetTy = getContext().getIntTypeForBitwidth(
1239             getContext().toBits(TInfo.Width), /*Signed=*/false);
1240       } else {
1241         // Value is returned through parameter before the order.
1242         RetTy = getContext().VoidTy;
1243         Args.add(RValue::get(EmitCastToVoidPtr(Dest.getPointer())),
1244                  getContext().VoidPtrTy);
1245       }
1246     }
1247     // order is always the last parameter
1248     Args.add(RValue::get(Order),
1249              getContext().IntTy);
1250     if (E->isOpenCL())
1251       Args.add(RValue::get(Scope), getContext().IntTy);
1252 
1253     // PostOp is only needed for the atomic_*_fetch operations, and
1254     // thus is only needed for and implemented in the
1255     // UseOptimizedLibcall codepath.
1256     assert(UseOptimizedLibcall || (!PostOp && !PostOpMinMax));
1257 
1258     RValue Res = emitAtomicLibcall(*this, LibCallName, RetTy, Args);
1259     // The value is returned directly from the libcall.
1260     if (E->isCmpXChg())
1261       return Res;
1262 
1263     // The value is returned directly for optimized libcalls but the expr
1264     // provided an out-param.
1265     if (UseOptimizedLibcall && Res.getScalarVal()) {
1266       llvm::Value *ResVal = Res.getScalarVal();
1267       if (PostOpMinMax) {
1268         llvm::Value *LoadVal1 = Args[1].getRValue(*this).getScalarVal();
1269         ResVal = EmitPostAtomicMinMax(Builder, E->getOp(),
1270                                       E->getValueType()->isSignedIntegerType(),
1271                                       ResVal, LoadVal1);
1272       } else if (PostOp) {
1273         llvm::Value *LoadVal1 = Args[1].getRValue(*this).getScalarVal();
1274         ResVal = Builder.CreateBinOp(PostOp, ResVal, LoadVal1);
1275       }
1276       if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
1277         ResVal = Builder.CreateNot(ResVal);
1278 
1279       Builder.CreateStore(
1280           ResVal,
1281           Builder.CreateBitCast(Dest, ResVal->getType()->getPointerTo()));
1282     }
1283 
1284     if (RValTy->isVoidType())
1285       return RValue::get(nullptr);
1286 
1287     return convertTempToRValue(
1288         Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo()),
1289         RValTy, E->getExprLoc());
1290   }
1291 
1292   bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
1293                  E->getOp() == AtomicExpr::AO__opencl_atomic_store ||
1294                  E->getOp() == AtomicExpr::AO__atomic_store ||
1295                  E->getOp() == AtomicExpr::AO__atomic_store_n;
1296   bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
1297                 E->getOp() == AtomicExpr::AO__opencl_atomic_load ||
1298                 E->getOp() == AtomicExpr::AO__atomic_load ||
1299                 E->getOp() == AtomicExpr::AO__atomic_load_n;
1300 
1301   if (isa<llvm::ConstantInt>(Order)) {
1302     auto ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
1303     // We should not ever get to a case where the ordering isn't a valid C ABI
1304     // value, but it's hard to enforce that in general.
1305     if (llvm::isValidAtomicOrderingCABI(ord))
1306       switch ((llvm::AtomicOrderingCABI)ord) {
1307       case llvm::AtomicOrderingCABI::relaxed:
1308         EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1309                      llvm::AtomicOrdering::Monotonic, Scope);
1310         break;
1311       case llvm::AtomicOrderingCABI::consume:
1312       case llvm::AtomicOrderingCABI::acquire:
1313         if (IsStore)
1314           break; // Avoid crashing on code with undefined behavior
1315         EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1316                      llvm::AtomicOrdering::Acquire, Scope);
1317         break;
1318       case llvm::AtomicOrderingCABI::release:
1319         if (IsLoad)
1320           break; // Avoid crashing on code with undefined behavior
1321         EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1322                      llvm::AtomicOrdering::Release, Scope);
1323         break;
1324       case llvm::AtomicOrderingCABI::acq_rel:
1325         if (IsLoad || IsStore)
1326           break; // Avoid crashing on code with undefined behavior
1327         EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1328                      llvm::AtomicOrdering::AcquireRelease, Scope);
1329         break;
1330       case llvm::AtomicOrderingCABI::seq_cst:
1331         EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1332                      llvm::AtomicOrdering::SequentiallyConsistent, Scope);
1333         break;
1334       }
1335     if (RValTy->isVoidType())
1336       return RValue::get(nullptr);
1337 
1338     return convertTempToRValue(
1339         Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1340                                         Dest.getAddressSpace())),
1341         RValTy, E->getExprLoc());
1342   }
1343 
1344   // Long case, when Order isn't obviously constant.
1345 
1346   // Create all the relevant BB's
1347   llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
1348                    *ReleaseBB = nullptr, *AcqRelBB = nullptr,
1349                    *SeqCstBB = nullptr;
1350   MonotonicBB = createBasicBlock("monotonic", CurFn);
1351   if (!IsStore)
1352     AcquireBB = createBasicBlock("acquire", CurFn);
1353   if (!IsLoad)
1354     ReleaseBB = createBasicBlock("release", CurFn);
1355   if (!IsLoad && !IsStore)
1356     AcqRelBB = createBasicBlock("acqrel", CurFn);
1357   SeqCstBB = createBasicBlock("seqcst", CurFn);
1358   llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
1359 
1360   // Create the switch for the split
1361   // MonotonicBB is arbitrarily chosen as the default case; in practice, this
1362   // doesn't matter unless someone is crazy enough to use something that
1363   // doesn't fold to a constant for the ordering.
1364   Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
1365   llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
1366 
1367   // Emit all the different atomics
1368   Builder.SetInsertPoint(MonotonicBB);
1369   EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1370                llvm::AtomicOrdering::Monotonic, Scope);
1371   Builder.CreateBr(ContBB);
1372   if (!IsStore) {
1373     Builder.SetInsertPoint(AcquireBB);
1374     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1375                  llvm::AtomicOrdering::Acquire, Scope);
1376     Builder.CreateBr(ContBB);
1377     SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
1378                 AcquireBB);
1379     SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
1380                 AcquireBB);
1381   }
1382   if (!IsLoad) {
1383     Builder.SetInsertPoint(ReleaseBB);
1384     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1385                  llvm::AtomicOrdering::Release, Scope);
1386     Builder.CreateBr(ContBB);
1387     SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::release),
1388                 ReleaseBB);
1389   }
1390   if (!IsLoad && !IsStore) {
1391     Builder.SetInsertPoint(AcqRelBB);
1392     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1393                  llvm::AtomicOrdering::AcquireRelease, Scope);
1394     Builder.CreateBr(ContBB);
1395     SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acq_rel),
1396                 AcqRelBB);
1397   }
1398   Builder.SetInsertPoint(SeqCstBB);
1399   EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1400                llvm::AtomicOrdering::SequentiallyConsistent, Scope);
1401   Builder.CreateBr(ContBB);
1402   SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
1403               SeqCstBB);
1404 
1405   // Cleanup and return
1406   Builder.SetInsertPoint(ContBB);
1407   if (RValTy->isVoidType())
1408     return RValue::get(nullptr);
1409 
1410   assert(Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits());
1411   return convertTempToRValue(
1412       Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1413                                       Dest.getAddressSpace())),
1414       RValTy, E->getExprLoc());
1415 }
1416 
1417 Address AtomicInfo::emitCastToAtomicIntPointer(Address addr) const {
1418   unsigned addrspace =
1419     cast<llvm::PointerType>(addr.getPointer()->getType())->getAddressSpace();
1420   llvm::IntegerType *ty =
1421     llvm::IntegerType::get(CGF.getLLVMContext(), AtomicSizeInBits);
1422   return CGF.Builder.CreateBitCast(addr, ty->getPointerTo(addrspace));
1423 }
1424 
1425 Address AtomicInfo::convertToAtomicIntPointer(Address Addr) const {
1426   llvm::Type *Ty = Addr.getElementType();
1427   uint64_t SourceSizeInBits = CGF.CGM.getDataLayout().getTypeSizeInBits(Ty);
1428   if (SourceSizeInBits != AtomicSizeInBits) {
1429     Address Tmp = CreateTempAlloca();
1430     CGF.Builder.CreateMemCpy(Tmp, Addr,
1431                              std::min(AtomicSizeInBits, SourceSizeInBits) / 8);
1432     Addr = Tmp;
1433   }
1434 
1435   return emitCastToAtomicIntPointer(Addr);
1436 }
1437 
1438 RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
1439                                              AggValueSlot resultSlot,
1440                                              SourceLocation loc,
1441                                              bool asValue) const {
1442   if (LVal.isSimple()) {
1443     if (EvaluationKind == TEK_Aggregate)
1444       return resultSlot.asRValue();
1445 
1446     // Drill into the padding structure if we have one.
1447     if (hasPadding())
1448       addr = CGF.Builder.CreateStructGEP(addr, 0);
1449 
1450     // Otherwise, just convert the temporary to an r-value using the
1451     // normal conversion routine.
1452     return CGF.convertTempToRValue(addr, getValueType(), loc);
1453   }
1454   if (!asValue)
1455     // Get RValue from temp memory as atomic for non-simple lvalues
1456     return RValue::get(CGF.Builder.CreateLoad(addr));
1457   if (LVal.isBitField())
1458     return CGF.EmitLoadOfBitfieldLValue(
1459         LValue::MakeBitfield(addr, LVal.getBitFieldInfo(), LVal.getType(),
1460                              LVal.getBaseInfo(), TBAAAccessInfo()), loc);
1461   if (LVal.isVectorElt())
1462     return CGF.EmitLoadOfLValue(
1463         LValue::MakeVectorElt(addr, LVal.getVectorIdx(), LVal.getType(),
1464                               LVal.getBaseInfo(), TBAAAccessInfo()), loc);
1465   assert(LVal.isExtVectorElt());
1466   return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
1467       addr, LVal.getExtVectorElts(), LVal.getType(),
1468       LVal.getBaseInfo(), TBAAAccessInfo()));
1469 }
1470 
1471 RValue AtomicInfo::ConvertIntToValueOrAtomic(llvm::Value *IntVal,
1472                                              AggValueSlot ResultSlot,
1473                                              SourceLocation Loc,
1474                                              bool AsValue) const {
1475   // Try not to in some easy cases.
1476   assert(IntVal->getType()->isIntegerTy() && "Expected integer value");
1477   if (getEvaluationKind() == TEK_Scalar &&
1478       (((!LVal.isBitField() ||
1479          LVal.getBitFieldInfo().Size == ValueSizeInBits) &&
1480         !hasPadding()) ||
1481        !AsValue)) {
1482     auto *ValTy = AsValue
1483                       ? CGF.ConvertTypeForMem(ValueTy)
1484                       : getAtomicAddress().getType()->getPointerElementType();
1485     if (ValTy->isIntegerTy()) {
1486       assert(IntVal->getType() == ValTy && "Different integer types.");
1487       return RValue::get(CGF.EmitFromMemory(IntVal, ValueTy));
1488     } else if (ValTy->isPointerTy())
1489       return RValue::get(CGF.Builder.CreateIntToPtr(IntVal, ValTy));
1490     else if (llvm::CastInst::isBitCastable(IntVal->getType(), ValTy))
1491       return RValue::get(CGF.Builder.CreateBitCast(IntVal, ValTy));
1492   }
1493 
1494   // Create a temporary.  This needs to be big enough to hold the
1495   // atomic integer.
1496   Address Temp = Address::invalid();
1497   bool TempIsVolatile = false;
1498   if (AsValue && getEvaluationKind() == TEK_Aggregate) {
1499     assert(!ResultSlot.isIgnored());
1500     Temp = ResultSlot.getAddress();
1501     TempIsVolatile = ResultSlot.isVolatile();
1502   } else {
1503     Temp = CreateTempAlloca();
1504   }
1505 
1506   // Slam the integer into the temporary.
1507   Address CastTemp = emitCastToAtomicIntPointer(Temp);
1508   CGF.Builder.CreateStore(IntVal, CastTemp)
1509       ->setVolatile(TempIsVolatile);
1510 
1511   return convertAtomicTempToRValue(Temp, ResultSlot, Loc, AsValue);
1512 }
1513 
1514 void AtomicInfo::EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
1515                                        llvm::AtomicOrdering AO, bool) {
1516   // void __atomic_load(size_t size, void *mem, void *return, int order);
1517   CallArgList Args;
1518   Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
1519   Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
1520            CGF.getContext().VoidPtrTy);
1521   Args.add(RValue::get(CGF.EmitCastToVoidPtr(AddForLoaded)),
1522            CGF.getContext().VoidPtrTy);
1523   Args.add(
1524       RValue::get(llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(AO))),
1525       CGF.getContext().IntTy);
1526   emitAtomicLibcall(CGF, "__atomic_load", CGF.getContext().VoidTy, Args);
1527 }
1528 
1529 llvm::Value *AtomicInfo::EmitAtomicLoadOp(llvm::AtomicOrdering AO,
1530                                           bool IsVolatile) {
1531   // Okay, we're doing this natively.
1532   Address Addr = getAtomicAddressAsAtomicIntPointer();
1533   llvm::LoadInst *Load = CGF.Builder.CreateLoad(Addr, "atomic-load");
1534   Load->setAtomic(AO);
1535 
1536   // Other decoration.
1537   if (IsVolatile)
1538     Load->setVolatile(true);
1539   CGF.CGM.DecorateInstructionWithTBAA(Load, LVal.getTBAAInfo());
1540   return Load;
1541 }
1542 
1543 /// An LValue is a candidate for having its loads and stores be made atomic if
1544 /// we are operating under /volatile:ms *and* the LValue itself is volatile and
1545 /// performing such an operation can be performed without a libcall.
1546 bool CodeGenFunction::LValueIsSuitableForInlineAtomic(LValue LV) {
1547   if (!CGM.getCodeGenOpts().MSVolatile) return false;
1548   AtomicInfo AI(*this, LV);
1549   bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
1550   // An atomic is inline if we don't need to use a libcall.
1551   bool AtomicIsInline = !AI.shouldUseLibcall();
1552   // MSVC doesn't seem to do this for types wider than a pointer.
1553   if (getContext().getTypeSize(LV.getType()) >
1554       getContext().getTypeSize(getContext().getIntPtrType()))
1555     return false;
1556   return IsVolatile && AtomicIsInline;
1557 }
1558 
1559 RValue CodeGenFunction::EmitAtomicLoad(LValue LV, SourceLocation SL,
1560                                        AggValueSlot Slot) {
1561   llvm::AtomicOrdering AO;
1562   bool IsVolatile = LV.isVolatileQualified();
1563   if (LV.getType()->isAtomicType()) {
1564     AO = llvm::AtomicOrdering::SequentiallyConsistent;
1565   } else {
1566     AO = llvm::AtomicOrdering::Acquire;
1567     IsVolatile = true;
1568   }
1569   return EmitAtomicLoad(LV, SL, AO, IsVolatile, Slot);
1570 }
1571 
1572 RValue AtomicInfo::EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
1573                                   bool AsValue, llvm::AtomicOrdering AO,
1574                                   bool IsVolatile) {
1575   // Check whether we should use a library call.
1576   if (shouldUseLibcall()) {
1577     Address TempAddr = Address::invalid();
1578     if (LVal.isSimple() && !ResultSlot.isIgnored()) {
1579       assert(getEvaluationKind() == TEK_Aggregate);
1580       TempAddr = ResultSlot.getAddress();
1581     } else
1582       TempAddr = CreateTempAlloca();
1583 
1584     EmitAtomicLoadLibcall(TempAddr.getPointer(), AO, IsVolatile);
1585 
1586     // Okay, turn that back into the original value or whole atomic (for
1587     // non-simple lvalues) type.
1588     return convertAtomicTempToRValue(TempAddr, ResultSlot, Loc, AsValue);
1589   }
1590 
1591   // Okay, we're doing this natively.
1592   auto *Load = EmitAtomicLoadOp(AO, IsVolatile);
1593 
1594   // If we're ignoring an aggregate return, don't do anything.
1595   if (getEvaluationKind() == TEK_Aggregate && ResultSlot.isIgnored())
1596     return RValue::getAggregate(Address::invalid(), false);
1597 
1598   // Okay, turn that back into the original value or atomic (for non-simple
1599   // lvalues) type.
1600   return ConvertIntToValueOrAtomic(Load, ResultSlot, Loc, AsValue);
1601 }
1602 
1603 /// Emit a load from an l-value of atomic type.  Note that the r-value
1604 /// we produce is an r-value of the atomic *value* type.
1605 RValue CodeGenFunction::EmitAtomicLoad(LValue src, SourceLocation loc,
1606                                        llvm::AtomicOrdering AO, bool IsVolatile,
1607                                        AggValueSlot resultSlot) {
1608   AtomicInfo Atomics(*this, src);
1609   return Atomics.EmitAtomicLoad(resultSlot, loc, /*AsValue=*/true, AO,
1610                                 IsVolatile);
1611 }
1612 
1613 /// Copy an r-value into memory as part of storing to an atomic type.
1614 /// This needs to create a bit-pattern suitable for atomic operations.
1615 void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
1616   assert(LVal.isSimple());
1617   // If we have an r-value, the rvalue should be of the atomic type,
1618   // which means that the caller is responsible for having zeroed
1619   // any padding.  Just do an aggregate copy of that type.
1620   if (rvalue.isAggregate()) {
1621     LValue Dest = CGF.MakeAddrLValue(getAtomicAddress(), getAtomicType());
1622     LValue Src = CGF.MakeAddrLValue(rvalue.getAggregateAddress(),
1623                                     getAtomicType());
1624     bool IsVolatile = rvalue.isVolatileQualified() ||
1625                       LVal.isVolatileQualified();
1626     CGF.EmitAggregateCopy(Dest, Src, getAtomicType(),
1627                           AggValueSlot::DoesNotOverlap, IsVolatile);
1628     return;
1629   }
1630 
1631   // Okay, otherwise we're copying stuff.
1632 
1633   // Zero out the buffer if necessary.
1634   emitMemSetZeroIfNecessary();
1635 
1636   // Drill past the padding if present.
1637   LValue TempLVal = projectValue();
1638 
1639   // Okay, store the rvalue in.
1640   if (rvalue.isScalar()) {
1641     CGF.EmitStoreOfScalar(rvalue.getScalarVal(), TempLVal, /*init*/ true);
1642   } else {
1643     CGF.EmitStoreOfComplex(rvalue.getComplexVal(), TempLVal, /*init*/ true);
1644   }
1645 }
1646 
1647 
1648 /// Materialize an r-value into memory for the purposes of storing it
1649 /// to an atomic type.
1650 Address AtomicInfo::materializeRValue(RValue rvalue) const {
1651   // Aggregate r-values are already in memory, and EmitAtomicStore
1652   // requires them to be values of the atomic type.
1653   if (rvalue.isAggregate())
1654     return rvalue.getAggregateAddress();
1655 
1656   // Otherwise, make a temporary and materialize into it.
1657   LValue TempLV = CGF.MakeAddrLValue(CreateTempAlloca(), getAtomicType());
1658   AtomicInfo Atomics(CGF, TempLV);
1659   Atomics.emitCopyIntoMemory(rvalue);
1660   return TempLV.getAddress(CGF);
1661 }
1662 
1663 llvm::Value *AtomicInfo::convertRValueToInt(RValue RVal) const {
1664   // If we've got a scalar value of the right size, try to avoid going
1665   // through memory.
1666   if (RVal.isScalar() && (!hasPadding() || !LVal.isSimple())) {
1667     llvm::Value *Value = RVal.getScalarVal();
1668     if (isa<llvm::IntegerType>(Value->getType()))
1669       return CGF.EmitToMemory(Value, ValueTy);
1670     else {
1671       llvm::IntegerType *InputIntTy = llvm::IntegerType::get(
1672           CGF.getLLVMContext(),
1673           LVal.isSimple() ? getValueSizeInBits() : getAtomicSizeInBits());
1674       if (isa<llvm::PointerType>(Value->getType()))
1675         return CGF.Builder.CreatePtrToInt(Value, InputIntTy);
1676       else if (llvm::BitCastInst::isBitCastable(Value->getType(), InputIntTy))
1677         return CGF.Builder.CreateBitCast(Value, InputIntTy);
1678     }
1679   }
1680   // Otherwise, we need to go through memory.
1681   // Put the r-value in memory.
1682   Address Addr = materializeRValue(RVal);
1683 
1684   // Cast the temporary to the atomic int type and pull a value out.
1685   Addr = emitCastToAtomicIntPointer(Addr);
1686   return CGF.Builder.CreateLoad(Addr);
1687 }
1688 
1689 std::pair<llvm::Value *, llvm::Value *> AtomicInfo::EmitAtomicCompareExchangeOp(
1690     llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
1691     llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak) {
1692   // Do the atomic store.
1693   Address Addr = getAtomicAddressAsAtomicIntPointer();
1694   auto *Inst = CGF.Builder.CreateAtomicCmpXchg(Addr.getPointer(),
1695                                                ExpectedVal, DesiredVal,
1696                                                Success, Failure);
1697   // Other decoration.
1698   Inst->setVolatile(LVal.isVolatileQualified());
1699   Inst->setWeak(IsWeak);
1700 
1701   // Okay, turn that back into the original value type.
1702   auto *PreviousVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/0);
1703   auto *SuccessFailureVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/1);
1704   return std::make_pair(PreviousVal, SuccessFailureVal);
1705 }
1706 
1707 llvm::Value *
1708 AtomicInfo::EmitAtomicCompareExchangeLibcall(llvm::Value *ExpectedAddr,
1709                                              llvm::Value *DesiredAddr,
1710                                              llvm::AtomicOrdering Success,
1711                                              llvm::AtomicOrdering Failure) {
1712   // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
1713   // void *desired, int success, int failure);
1714   CallArgList Args;
1715   Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
1716   Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
1717            CGF.getContext().VoidPtrTy);
1718   Args.add(RValue::get(CGF.EmitCastToVoidPtr(ExpectedAddr)),
1719            CGF.getContext().VoidPtrTy);
1720   Args.add(RValue::get(CGF.EmitCastToVoidPtr(DesiredAddr)),
1721            CGF.getContext().VoidPtrTy);
1722   Args.add(RValue::get(
1723                llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Success))),
1724            CGF.getContext().IntTy);
1725   Args.add(RValue::get(
1726                llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Failure))),
1727            CGF.getContext().IntTy);
1728   auto SuccessFailureRVal = emitAtomicLibcall(CGF, "__atomic_compare_exchange",
1729                                               CGF.getContext().BoolTy, Args);
1730 
1731   return SuccessFailureRVal.getScalarVal();
1732 }
1733 
1734 std::pair<RValue, llvm::Value *> AtomicInfo::EmitAtomicCompareExchange(
1735     RValue Expected, RValue Desired, llvm::AtomicOrdering Success,
1736     llvm::AtomicOrdering Failure, bool IsWeak) {
1737   // Check whether we should use a library call.
1738   if (shouldUseLibcall()) {
1739     // Produce a source address.
1740     Address ExpectedAddr = materializeRValue(Expected);
1741     Address DesiredAddr = materializeRValue(Desired);
1742     auto *Res = EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1743                                                  DesiredAddr.getPointer(),
1744                                                  Success, Failure);
1745     return std::make_pair(
1746         convertAtomicTempToRValue(ExpectedAddr, AggValueSlot::ignored(),
1747                                   SourceLocation(), /*AsValue=*/false),
1748         Res);
1749   }
1750 
1751   // If we've got a scalar value of the right size, try to avoid going
1752   // through memory.
1753   auto *ExpectedVal = convertRValueToInt(Expected);
1754   auto *DesiredVal = convertRValueToInt(Desired);
1755   auto Res = EmitAtomicCompareExchangeOp(ExpectedVal, DesiredVal, Success,
1756                                          Failure, IsWeak);
1757   return std::make_pair(
1758       ConvertIntToValueOrAtomic(Res.first, AggValueSlot::ignored(),
1759                                 SourceLocation(), /*AsValue=*/false),
1760       Res.second);
1761 }
1762 
1763 static void
1764 EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal,
1765                       const llvm::function_ref<RValue(RValue)> &UpdateOp,
1766                       Address DesiredAddr) {
1767   RValue UpRVal;
1768   LValue AtomicLVal = Atomics.getAtomicLValue();
1769   LValue DesiredLVal;
1770   if (AtomicLVal.isSimple()) {
1771     UpRVal = OldRVal;
1772     DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
1773   } else {
1774     // Build new lvalue for temp address.
1775     Address Ptr = Atomics.materializeRValue(OldRVal);
1776     LValue UpdateLVal;
1777     if (AtomicLVal.isBitField()) {
1778       UpdateLVal =
1779           LValue::MakeBitfield(Ptr, AtomicLVal.getBitFieldInfo(),
1780                                AtomicLVal.getType(),
1781                                AtomicLVal.getBaseInfo(),
1782                                AtomicLVal.getTBAAInfo());
1783       DesiredLVal =
1784           LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
1785                                AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1786                                AtomicLVal.getTBAAInfo());
1787     } else if (AtomicLVal.isVectorElt()) {
1788       UpdateLVal = LValue::MakeVectorElt(Ptr, AtomicLVal.getVectorIdx(),
1789                                          AtomicLVal.getType(),
1790                                          AtomicLVal.getBaseInfo(),
1791                                          AtomicLVal.getTBAAInfo());
1792       DesiredLVal = LValue::MakeVectorElt(
1793           DesiredAddr, AtomicLVal.getVectorIdx(), AtomicLVal.getType(),
1794           AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1795     } else {
1796       assert(AtomicLVal.isExtVectorElt());
1797       UpdateLVal = LValue::MakeExtVectorElt(Ptr, AtomicLVal.getExtVectorElts(),
1798                                             AtomicLVal.getType(),
1799                                             AtomicLVal.getBaseInfo(),
1800                                             AtomicLVal.getTBAAInfo());
1801       DesiredLVal = LValue::MakeExtVectorElt(
1802           DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
1803           AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1804     }
1805     UpRVal = CGF.EmitLoadOfLValue(UpdateLVal, SourceLocation());
1806   }
1807   // Store new value in the corresponding memory area.
1808   RValue NewRVal = UpdateOp(UpRVal);
1809   if (NewRVal.isScalar()) {
1810     CGF.EmitStoreThroughLValue(NewRVal, DesiredLVal);
1811   } else {
1812     assert(NewRVal.isComplex());
1813     CGF.EmitStoreOfComplex(NewRVal.getComplexVal(), DesiredLVal,
1814                            /*isInit=*/false);
1815   }
1816 }
1817 
1818 void AtomicInfo::EmitAtomicUpdateLibcall(
1819     llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1820     bool IsVolatile) {
1821   auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1822 
1823   Address ExpectedAddr = CreateTempAlloca();
1824 
1825   EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
1826   auto *ContBB = CGF.createBasicBlock("atomic_cont");
1827   auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1828   CGF.EmitBlock(ContBB);
1829   Address DesiredAddr = CreateTempAlloca();
1830   if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1831       requiresMemSetZero(getAtomicAddress().getElementType())) {
1832     auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1833     CGF.Builder.CreateStore(OldVal, DesiredAddr);
1834   }
1835   auto OldRVal = convertAtomicTempToRValue(ExpectedAddr,
1836                                            AggValueSlot::ignored(),
1837                                            SourceLocation(), /*AsValue=*/false);
1838   EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, DesiredAddr);
1839   auto *Res =
1840       EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1841                                        DesiredAddr.getPointer(),
1842                                        AO, Failure);
1843   CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1844   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1845 }
1846 
1847 void AtomicInfo::EmitAtomicUpdateOp(
1848     llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1849     bool IsVolatile) {
1850   auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1851 
1852   // Do the atomic load.
1853   auto *OldVal = EmitAtomicLoadOp(Failure, IsVolatile);
1854   // For non-simple lvalues perform compare-and-swap procedure.
1855   auto *ContBB = CGF.createBasicBlock("atomic_cont");
1856   auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1857   auto *CurBB = CGF.Builder.GetInsertBlock();
1858   CGF.EmitBlock(ContBB);
1859   llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1860                                              /*NumReservedValues=*/2);
1861   PHI->addIncoming(OldVal, CurBB);
1862   Address NewAtomicAddr = CreateTempAlloca();
1863   Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
1864   if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1865       requiresMemSetZero(getAtomicAddress().getElementType())) {
1866     CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
1867   }
1868   auto OldRVal = ConvertIntToValueOrAtomic(PHI, AggValueSlot::ignored(),
1869                                            SourceLocation(), /*AsValue=*/false);
1870   EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, NewAtomicAddr);
1871   auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
1872   // Try to write new value using cmpxchg operation.
1873   auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1874   PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1875   CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1876   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1877 }
1878 
1879 static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics,
1880                                   RValue UpdateRVal, Address DesiredAddr) {
1881   LValue AtomicLVal = Atomics.getAtomicLValue();
1882   LValue DesiredLVal;
1883   // Build new lvalue for temp address.
1884   if (AtomicLVal.isBitField()) {
1885     DesiredLVal =
1886         LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
1887                              AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1888                              AtomicLVal.getTBAAInfo());
1889   } else if (AtomicLVal.isVectorElt()) {
1890     DesiredLVal =
1891         LValue::MakeVectorElt(DesiredAddr, AtomicLVal.getVectorIdx(),
1892                               AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1893                               AtomicLVal.getTBAAInfo());
1894   } else {
1895     assert(AtomicLVal.isExtVectorElt());
1896     DesiredLVal = LValue::MakeExtVectorElt(
1897         DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
1898         AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1899   }
1900   // Store new value in the corresponding memory area.
1901   assert(UpdateRVal.isScalar());
1902   CGF.EmitStoreThroughLValue(UpdateRVal, DesiredLVal);
1903 }
1904 
1905 void AtomicInfo::EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
1906                                          RValue UpdateRVal, bool IsVolatile) {
1907   auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1908 
1909   Address ExpectedAddr = CreateTempAlloca();
1910 
1911   EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
1912   auto *ContBB = CGF.createBasicBlock("atomic_cont");
1913   auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1914   CGF.EmitBlock(ContBB);
1915   Address DesiredAddr = CreateTempAlloca();
1916   if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1917       requiresMemSetZero(getAtomicAddress().getElementType())) {
1918     auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1919     CGF.Builder.CreateStore(OldVal, DesiredAddr);
1920   }
1921   EmitAtomicUpdateValue(CGF, *this, UpdateRVal, DesiredAddr);
1922   auto *Res =
1923       EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1924                                        DesiredAddr.getPointer(),
1925                                        AO, Failure);
1926   CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1927   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1928 }
1929 
1930 void AtomicInfo::EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRVal,
1931                                     bool IsVolatile) {
1932   auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1933 
1934   // Do the atomic load.
1935   auto *OldVal = EmitAtomicLoadOp(Failure, IsVolatile);
1936   // For non-simple lvalues perform compare-and-swap procedure.
1937   auto *ContBB = CGF.createBasicBlock("atomic_cont");
1938   auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1939   auto *CurBB = CGF.Builder.GetInsertBlock();
1940   CGF.EmitBlock(ContBB);
1941   llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1942                                              /*NumReservedValues=*/2);
1943   PHI->addIncoming(OldVal, CurBB);
1944   Address NewAtomicAddr = CreateTempAlloca();
1945   Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
1946   if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1947       requiresMemSetZero(getAtomicAddress().getElementType())) {
1948     CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
1949   }
1950   EmitAtomicUpdateValue(CGF, *this, UpdateRVal, NewAtomicAddr);
1951   auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
1952   // Try to write new value using cmpxchg operation.
1953   auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1954   PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1955   CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1956   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1957 }
1958 
1959 void AtomicInfo::EmitAtomicUpdate(
1960     llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1961     bool IsVolatile) {
1962   if (shouldUseLibcall()) {
1963     EmitAtomicUpdateLibcall(AO, UpdateOp, IsVolatile);
1964   } else {
1965     EmitAtomicUpdateOp(AO, UpdateOp, IsVolatile);
1966   }
1967 }
1968 
1969 void AtomicInfo::EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
1970                                   bool IsVolatile) {
1971   if (shouldUseLibcall()) {
1972     EmitAtomicUpdateLibcall(AO, UpdateRVal, IsVolatile);
1973   } else {
1974     EmitAtomicUpdateOp(AO, UpdateRVal, IsVolatile);
1975   }
1976 }
1977 
1978 void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue lvalue,
1979                                       bool isInit) {
1980   bool IsVolatile = lvalue.isVolatileQualified();
1981   llvm::AtomicOrdering AO;
1982   if (lvalue.getType()->isAtomicType()) {
1983     AO = llvm::AtomicOrdering::SequentiallyConsistent;
1984   } else {
1985     AO = llvm::AtomicOrdering::Release;
1986     IsVolatile = true;
1987   }
1988   return EmitAtomicStore(rvalue, lvalue, AO, IsVolatile, isInit);
1989 }
1990 
1991 /// Emit a store to an l-value of atomic type.
1992 ///
1993 /// Note that the r-value is expected to be an r-value *of the atomic
1994 /// type*; this means that for aggregate r-values, it should include
1995 /// storage for any padding that was necessary.
1996 void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue dest,
1997                                       llvm::AtomicOrdering AO, bool IsVolatile,
1998                                       bool isInit) {
1999   // If this is an aggregate r-value, it should agree in type except
2000   // maybe for address-space qualification.
2001   assert(!rvalue.isAggregate() ||
2002          rvalue.getAggregateAddress().getElementType() ==
2003              dest.getAddress(*this).getElementType());
2004 
2005   AtomicInfo atomics(*this, dest);
2006   LValue LVal = atomics.getAtomicLValue();
2007 
2008   // If this is an initialization, just put the value there normally.
2009   if (LVal.isSimple()) {
2010     if (isInit) {
2011       atomics.emitCopyIntoMemory(rvalue);
2012       return;
2013     }
2014 
2015     // Check whether we should use a library call.
2016     if (atomics.shouldUseLibcall()) {
2017       // Produce a source address.
2018       Address srcAddr = atomics.materializeRValue(rvalue);
2019 
2020       // void __atomic_store(size_t size, void *mem, void *val, int order)
2021       CallArgList args;
2022       args.add(RValue::get(atomics.getAtomicSizeValue()),
2023                getContext().getSizeType());
2024       args.add(RValue::get(EmitCastToVoidPtr(atomics.getAtomicPointer())),
2025                getContext().VoidPtrTy);
2026       args.add(RValue::get(EmitCastToVoidPtr(srcAddr.getPointer())),
2027                getContext().VoidPtrTy);
2028       args.add(
2029           RValue::get(llvm::ConstantInt::get(IntTy, (int)llvm::toCABI(AO))),
2030           getContext().IntTy);
2031       emitAtomicLibcall(*this, "__atomic_store", getContext().VoidTy, args);
2032       return;
2033     }
2034 
2035     // Okay, we're doing this natively.
2036     llvm::Value *intValue = atomics.convertRValueToInt(rvalue);
2037 
2038     // Do the atomic store.
2039     Address addr =
2040         atomics.emitCastToAtomicIntPointer(atomics.getAtomicAddress());
2041     intValue = Builder.CreateIntCast(
2042         intValue, addr.getElementType(), /*isSigned=*/false);
2043     llvm::StoreInst *store = Builder.CreateStore(intValue, addr);
2044 
2045     if (AO == llvm::AtomicOrdering::Acquire)
2046       AO = llvm::AtomicOrdering::Monotonic;
2047     else if (AO == llvm::AtomicOrdering::AcquireRelease)
2048       AO = llvm::AtomicOrdering::Release;
2049     // Initializations don't need to be atomic.
2050     if (!isInit)
2051       store->setAtomic(AO);
2052 
2053     // Other decoration.
2054     if (IsVolatile)
2055       store->setVolatile(true);
2056     CGM.DecorateInstructionWithTBAA(store, dest.getTBAAInfo());
2057     return;
2058   }
2059 
2060   // Emit simple atomic update operation.
2061   atomics.EmitAtomicUpdate(AO, rvalue, IsVolatile);
2062 }
2063 
2064 /// Emit a compare-and-exchange op for atomic type.
2065 ///
2066 std::pair<RValue, llvm::Value *> CodeGenFunction::EmitAtomicCompareExchange(
2067     LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2068     llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak,
2069     AggValueSlot Slot) {
2070   // If this is an aggregate r-value, it should agree in type except
2071   // maybe for address-space qualification.
2072   assert(!Expected.isAggregate() ||
2073          Expected.getAggregateAddress().getElementType() ==
2074              Obj.getAddress(*this).getElementType());
2075   assert(!Desired.isAggregate() ||
2076          Desired.getAggregateAddress().getElementType() ==
2077              Obj.getAddress(*this).getElementType());
2078   AtomicInfo Atomics(*this, Obj);
2079 
2080   return Atomics.EmitAtomicCompareExchange(Expected, Desired, Success, Failure,
2081                                            IsWeak);
2082 }
2083 
2084 void CodeGenFunction::EmitAtomicUpdate(
2085     LValue LVal, llvm::AtomicOrdering AO,
2086     const llvm::function_ref<RValue(RValue)> &UpdateOp, bool IsVolatile) {
2087   AtomicInfo Atomics(*this, LVal);
2088   Atomics.EmitAtomicUpdate(AO, UpdateOp, IsVolatile);
2089 }
2090 
2091 void CodeGenFunction::EmitAtomicInit(Expr *init, LValue dest) {
2092   AtomicInfo atomics(*this, dest);
2093 
2094   switch (atomics.getEvaluationKind()) {
2095   case TEK_Scalar: {
2096     llvm::Value *value = EmitScalarExpr(init);
2097     atomics.emitCopyIntoMemory(RValue::get(value));
2098     return;
2099   }
2100 
2101   case TEK_Complex: {
2102     ComplexPairTy value = EmitComplexExpr(init);
2103     atomics.emitCopyIntoMemory(RValue::getComplex(value));
2104     return;
2105   }
2106 
2107   case TEK_Aggregate: {
2108     // Fix up the destination if the initializer isn't an expression
2109     // of atomic type.
2110     bool Zeroed = false;
2111     if (!init->getType()->isAtomicType()) {
2112       Zeroed = atomics.emitMemSetZeroIfNecessary();
2113       dest = atomics.projectValue();
2114     }
2115 
2116     // Evaluate the expression directly into the destination.
2117     AggValueSlot slot = AggValueSlot::forLValue(
2118         dest, *this, AggValueSlot::IsNotDestructed,
2119         AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
2120         AggValueSlot::DoesNotOverlap,
2121         Zeroed ? AggValueSlot::IsZeroed : AggValueSlot::IsNotZeroed);
2122 
2123     EmitAggExpr(init, slot);
2124     return;
2125   }
2126   }
2127   llvm_unreachable("bad evaluation kind");
2128 }
2129