blob: 9379c835d3dcfc6b3500ebede035fe451ef7c75f [file] [log] [blame]
John McCallfc207f22013-03-07 21:37:12 +00001//===--- CGAtomic.cpp - Emit LLVM IR for atomic operations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the code for emitting atomic operations.
11//
12//===----------------------------------------------------------------------===//
13
John McCallfc207f22013-03-07 21:37:12 +000014#include "CGCall.h"
Alexey Bataevb57056f2015-01-22 06:17:56 +000015#include "CGRecordLayout.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "CodeGenFunction.h"
John McCallfc207f22013-03-07 21:37:12 +000017#include "CodeGenModule.h"
Yaxun Liu39195062017-08-04 18:16:31 +000018#include "TargetInfo.h"
John McCallfc207f22013-03-07 21:37:12 +000019#include "clang/AST/ASTContext.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000020#include "clang/CodeGen/CGFunctionInfo.h"
Tim Northover9dc1d0c2018-04-23 08:16:24 +000021#include "clang/Sema/SemaDiagnostic.h"
Yaxun Liu30d652a2017-08-15 16:02:49 +000022#include "llvm/ADT/DenseMap.h"
John McCallfc207f22013-03-07 21:37:12 +000023#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Intrinsics.h"
John McCalla8ec7eb2013-03-07 21:37:17 +000025#include "llvm/IR/Operator.h"
John McCallfc207f22013-03-07 21:37:12 +000026
27using namespace clang;
28using namespace CodeGen;
29
John McCalla8ec7eb2013-03-07 21:37:17 +000030namespace {
31 class AtomicInfo {
32 CodeGenFunction &CGF;
33 QualType AtomicTy;
34 QualType ValueTy;
35 uint64_t AtomicSizeInBits;
36 uint64_t ValueSizeInBits;
37 CharUnits AtomicAlign;
38 CharUnits ValueAlign;
39 CharUnits LValueAlign;
40 TypeEvaluationKind EvaluationKind;
41 bool UseLibcall;
Alexey Bataevb57056f2015-01-22 06:17:56 +000042 LValue LVal;
43 CGBitFieldInfo BFI;
John McCalla8ec7eb2013-03-07 21:37:17 +000044 public:
Alexey Bataevb57056f2015-01-22 06:17:56 +000045 AtomicInfo(CodeGenFunction &CGF, LValue &lvalue)
46 : CGF(CGF), AtomicSizeInBits(0), ValueSizeInBits(0),
47 EvaluationKind(TEK_Scalar), UseLibcall(true) {
48 assert(!lvalue.isGlobalReg());
John McCalla8ec7eb2013-03-07 21:37:17 +000049 ASTContext &C = CGF.getContext();
Alexey Bataevb57056f2015-01-22 06:17:56 +000050 if (lvalue.isSimple()) {
51 AtomicTy = lvalue.getType();
52 if (auto *ATy = AtomicTy->getAs<AtomicType>())
53 ValueTy = ATy->getValueType();
54 else
55 ValueTy = AtomicTy;
56 EvaluationKind = CGF.getEvaluationKind(ValueTy);
John McCalla8ec7eb2013-03-07 21:37:17 +000057
Alexey Bataevb57056f2015-01-22 06:17:56 +000058 uint64_t ValueAlignInBits;
59 uint64_t AtomicAlignInBits;
60 TypeInfo ValueTI = C.getTypeInfo(ValueTy);
61 ValueSizeInBits = ValueTI.Width;
62 ValueAlignInBits = ValueTI.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +000063
Alexey Bataevb57056f2015-01-22 06:17:56 +000064 TypeInfo AtomicTI = C.getTypeInfo(AtomicTy);
65 AtomicSizeInBits = AtomicTI.Width;
66 AtomicAlignInBits = AtomicTI.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +000067
Alexey Bataevb57056f2015-01-22 06:17:56 +000068 assert(ValueSizeInBits <= AtomicSizeInBits);
69 assert(ValueAlignInBits <= AtomicAlignInBits);
John McCalla8ec7eb2013-03-07 21:37:17 +000070
Alexey Bataevb57056f2015-01-22 06:17:56 +000071 AtomicAlign = C.toCharUnitsFromBits(AtomicAlignInBits);
72 ValueAlign = C.toCharUnitsFromBits(ValueAlignInBits);
73 if (lvalue.getAlignment().isZero())
74 lvalue.setAlignment(AtomicAlign);
John McCalla8ec7eb2013-03-07 21:37:17 +000075
Alexey Bataevb57056f2015-01-22 06:17:56 +000076 LVal = lvalue;
77 } else if (lvalue.isBitField()) {
Alexey Bataevb8329262015-02-27 06:33:30 +000078 ValueTy = lvalue.getType();
79 ValueSizeInBits = C.getTypeSize(ValueTy);
Alexey Bataevb57056f2015-01-22 06:17:56 +000080 auto &OrigBFI = lvalue.getBitFieldInfo();
81 auto Offset = OrigBFI.Offset % C.toBits(lvalue.getAlignment());
82 AtomicSizeInBits = C.toBits(
83 C.toCharUnitsFromBits(Offset + OrigBFI.Size + C.getCharWidth() - 1)
Rui Ueyama83aa9792016-01-14 21:00:27 +000084 .alignTo(lvalue.getAlignment()));
John McCall7f416cc2015-09-08 08:05:57 +000085 auto VoidPtrAddr = CGF.EmitCastToVoidPtr(lvalue.getBitFieldPointer());
Alexey Bataevb57056f2015-01-22 06:17:56 +000086 auto OffsetInChars =
87 (C.toCharUnitsFromBits(OrigBFI.Offset) / lvalue.getAlignment()) *
88 lvalue.getAlignment();
89 VoidPtrAddr = CGF.Builder.CreateConstGEP1_64(
90 VoidPtrAddr, OffsetInChars.getQuantity());
91 auto Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
92 VoidPtrAddr,
93 CGF.Builder.getIntNTy(AtomicSizeInBits)->getPointerTo(),
94 "atomic_bitfield_base");
95 BFI = OrigBFI;
96 BFI.Offset = Offset;
97 BFI.StorageSize = AtomicSizeInBits;
Ulrich Weigand03ce2a12015-07-10 17:30:00 +000098 BFI.StorageOffset += OffsetInChars;
John McCall7f416cc2015-09-08 08:05:57 +000099 LVal = LValue::MakeBitfield(Address(Addr, lvalue.getAlignment()),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +0000100 BFI, lvalue.getType(), lvalue.getBaseInfo(),
101 lvalue.getTBAAInfo());
Alexey Bataevb8329262015-02-27 06:33:30 +0000102 AtomicTy = C.getIntTypeForBitwidth(AtomicSizeInBits, OrigBFI.IsSigned);
103 if (AtomicTy.isNull()) {
104 llvm::APInt Size(
105 /*numBits=*/32,
106 C.toCharUnitsFromBits(AtomicSizeInBits).getQuantity());
107 AtomicTy = C.getConstantArrayType(C.CharTy, Size, ArrayType::Normal,
108 /*IndexTypeQuals=*/0);
109 }
110 AtomicAlign = ValueAlign = lvalue.getAlignment();
Alexey Bataevb57056f2015-01-22 06:17:56 +0000111 } else if (lvalue.isVectorElt()) {
Alexey Bataevb8329262015-02-27 06:33:30 +0000112 ValueTy = lvalue.getType()->getAs<VectorType>()->getElementType();
113 ValueSizeInBits = C.getTypeSize(ValueTy);
114 AtomicTy = lvalue.getType();
115 AtomicSizeInBits = C.getTypeSize(AtomicTy);
116 AtomicAlign = ValueAlign = lvalue.getAlignment();
Alexey Bataevb57056f2015-01-22 06:17:56 +0000117 LVal = lvalue;
118 } else {
119 assert(lvalue.isExtVectorElt());
Alexey Bataevb8329262015-02-27 06:33:30 +0000120 ValueTy = lvalue.getType();
121 ValueSizeInBits = C.getTypeSize(ValueTy);
122 AtomicTy = ValueTy = CGF.getContext().getExtVectorType(
John McCall7f416cc2015-09-08 08:05:57 +0000123 lvalue.getType(), lvalue.getExtVectorAddress()
124 .getElementType()->getVectorNumElements());
Alexey Bataevb8329262015-02-27 06:33:30 +0000125 AtomicSizeInBits = C.getTypeSize(AtomicTy);
126 AtomicAlign = ValueAlign = lvalue.getAlignment();
Alexey Bataevb57056f2015-01-22 06:17:56 +0000127 LVal = lvalue;
128 }
Alexey Bataev452d8e12014-12-15 05:25:25 +0000129 UseLibcall = !C.getTargetInfo().hasBuiltinAtomic(
130 AtomicSizeInBits, C.toBits(lvalue.getAlignment()));
John McCalla8ec7eb2013-03-07 21:37:17 +0000131 }
132
133 QualType getAtomicType() const { return AtomicTy; }
134 QualType getValueType() const { return ValueTy; }
135 CharUnits getAtomicAlignment() const { return AtomicAlign; }
136 CharUnits getValueAlignment() const { return ValueAlign; }
137 uint64_t getAtomicSizeInBits() const { return AtomicSizeInBits; }
Alexey Bataev452d8e12014-12-15 05:25:25 +0000138 uint64_t getValueSizeInBits() const { return ValueSizeInBits; }
John McCalla8ec7eb2013-03-07 21:37:17 +0000139 TypeEvaluationKind getEvaluationKind() const { return EvaluationKind; }
140 bool shouldUseLibcall() const { return UseLibcall; }
Alexey Bataevb57056f2015-01-22 06:17:56 +0000141 const LValue &getAtomicLValue() const { return LVal; }
John McCall7f416cc2015-09-08 08:05:57 +0000142 llvm::Value *getAtomicPointer() const {
Alexey Bataevb8329262015-02-27 06:33:30 +0000143 if (LVal.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000144 return LVal.getPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000145 else if (LVal.isBitField())
John McCall7f416cc2015-09-08 08:05:57 +0000146 return LVal.getBitFieldPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000147 else if (LVal.isVectorElt())
John McCall7f416cc2015-09-08 08:05:57 +0000148 return LVal.getVectorPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000149 assert(LVal.isExtVectorElt());
John McCall7f416cc2015-09-08 08:05:57 +0000150 return LVal.getExtVectorPointer();
151 }
152 Address getAtomicAddress() const {
153 return Address(getAtomicPointer(), getAtomicAlignment());
154 }
155
156 Address getAtomicAddressAsAtomicIntPointer() const {
157 return emitCastToAtomicIntPointer(getAtomicAddress());
Alexey Bataevb8329262015-02-27 06:33:30 +0000158 }
John McCalla8ec7eb2013-03-07 21:37:17 +0000159
160 /// Is the atomic size larger than the underlying value type?
161 ///
162 /// Note that the absence of padding does not mean that atomic
163 /// objects are completely interchangeable with non-atomic
164 /// objects: we might have promoted the alignment of a type
165 /// without making it bigger.
166 bool hasPadding() const {
167 return (ValueSizeInBits != AtomicSizeInBits);
168 }
169
Alexey Bataevb57056f2015-01-22 06:17:56 +0000170 bool emitMemSetZeroIfNecessary() const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000171
172 llvm::Value *getAtomicSizeValue() const {
173 CharUnits size = CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits);
174 return CGF.CGM.getSize(size);
175 }
176
Tim Northovercc2a6e02015-11-09 19:56:35 +0000177 /// Cast the given pointer to an integer pointer suitable for atomic
178 /// operations if the source.
179 Address emitCastToAtomicIntPointer(Address Addr) const;
180
181 /// If Addr is compatible with the iN that will be used for an atomic
182 /// operation, bitcast it. Otherwise, create a temporary that is suitable
183 /// and copy the value across.
184 Address convertToAtomicIntPointer(Address Addr) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000185
186 /// Turn an atomic-layout object into an r-value.
John McCall7f416cc2015-09-08 08:05:57 +0000187 RValue convertAtomicTempToRValue(Address addr, AggValueSlot resultSlot,
188 SourceLocation loc, bool AsValue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000189
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000190 /// Converts a rvalue to integer value.
Alexey Bataev452d8e12014-12-15 05:25:25 +0000191 llvm::Value *convertRValueToInt(RValue RVal) const;
192
Alexey Bataevb8329262015-02-27 06:33:30 +0000193 RValue ConvertIntToValueOrAtomic(llvm::Value *IntVal,
194 AggValueSlot ResultSlot,
195 SourceLocation Loc, bool AsValue) const;
Alexey Bataev452d8e12014-12-15 05:25:25 +0000196
John McCalla8ec7eb2013-03-07 21:37:17 +0000197 /// Copy an atomic r-value into atomic-layout memory.
Alexey Bataevb57056f2015-01-22 06:17:56 +0000198 void emitCopyIntoMemory(RValue rvalue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000199
200 /// Project an l-value down to the value field.
Alexey Bataevb57056f2015-01-22 06:17:56 +0000201 LValue projectValue() const {
202 assert(LVal.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000203 Address addr = getAtomicAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +0000204 if (hasPadding())
John McCall7f416cc2015-09-08 08:05:57 +0000205 addr = CGF.Builder.CreateStructGEP(addr, 0, CharUnits());
John McCalla8ec7eb2013-03-07 21:37:17 +0000206
John McCall7f416cc2015-09-08 08:05:57 +0000207 return LValue::MakeAddr(addr, getValueType(), CGF.getContext(),
Ivan A. Kosarev383890b2017-10-06 08:17:48 +0000208 LVal.getBaseInfo(), LVal.getTBAAInfo());
John McCalla8ec7eb2013-03-07 21:37:17 +0000209 }
210
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000211 /// Emits atomic load.
Alexey Bataevb8329262015-02-27 06:33:30 +0000212 /// \returns Loaded value.
213 RValue EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
214 bool AsValue, llvm::AtomicOrdering AO,
215 bool IsVolatile);
216
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000217 /// Emits atomic compare-and-exchange sequence.
Alexey Bataevb8329262015-02-27 06:33:30 +0000218 /// \param Expected Expected value.
219 /// \param Desired Desired value.
220 /// \param Success Atomic ordering for success operation.
221 /// \param Failure Atomic ordering for failed operation.
222 /// \param IsWeak true if atomic operation is weak, false otherwise.
223 /// \returns Pair of values: previous value from storage (value type) and
224 /// boolean flag (i1 type) with true if success and false otherwise.
JF Bastien92f4ef12016-04-06 17:26:42 +0000225 std::pair<RValue, llvm::Value *>
226 EmitAtomicCompareExchange(RValue Expected, RValue Desired,
227 llvm::AtomicOrdering Success =
228 llvm::AtomicOrdering::SequentiallyConsistent,
229 llvm::AtomicOrdering Failure =
230 llvm::AtomicOrdering::SequentiallyConsistent,
231 bool IsWeak = false);
Alexey Bataevb8329262015-02-27 06:33:30 +0000232
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000233 /// Emits atomic update.
NAKAMURA Takumid16af5d2015-05-15 13:47:52 +0000234 /// \param AO Atomic ordering.
235 /// \param UpdateOp Update operation for the current lvalue.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000236 void EmitAtomicUpdate(llvm::AtomicOrdering AO,
237 const llvm::function_ref<RValue(RValue)> &UpdateOp,
238 bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000239 /// Emits atomic update.
NAKAMURA Takumid16af5d2015-05-15 13:47:52 +0000240 /// \param AO Atomic ordering.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000241 void EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
242 bool IsVolatile);
243
John McCalla8ec7eb2013-03-07 21:37:17 +0000244 /// Materialize an atomic r-value in atomic-layout memory.
John McCall7f416cc2015-09-08 08:05:57 +0000245 Address materializeRValue(RValue rvalue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000246
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000247 /// Creates temp alloca for intermediate operations on atomic value.
Tim Northovercc2a6e02015-11-09 19:56:35 +0000248 Address CreateTempAlloca() const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000249 private:
250 bool requiresMemSetZero(llvm::Type *type) const;
Alexey Bataevb8329262015-02-27 06:33:30 +0000251
Alexey Bataevb8329262015-02-27 06:33:30 +0000252
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000253 /// Emits atomic load as a libcall.
Alexey Bataevb8329262015-02-27 06:33:30 +0000254 void EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
255 llvm::AtomicOrdering AO, bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000256 /// Emits atomic load as LLVM instruction.
Alexey Bataevb8329262015-02-27 06:33:30 +0000257 llvm::Value *EmitAtomicLoadOp(llvm::AtomicOrdering AO, bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000258 /// Emits atomic compare-and-exchange op as a libcall.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000259 llvm::Value *EmitAtomicCompareExchangeLibcall(
260 llvm::Value *ExpectedAddr, llvm::Value *DesiredAddr,
JF Bastien92f4ef12016-04-06 17:26:42 +0000261 llvm::AtomicOrdering Success =
262 llvm::AtomicOrdering::SequentiallyConsistent,
263 llvm::AtomicOrdering Failure =
264 llvm::AtomicOrdering::SequentiallyConsistent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000265 /// Emits atomic compare-and-exchange op as LLVM instruction.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000266 std::pair<llvm::Value *, llvm::Value *> EmitAtomicCompareExchangeOp(
267 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
JF Bastien92f4ef12016-04-06 17:26:42 +0000268 llvm::AtomicOrdering Success =
269 llvm::AtomicOrdering::SequentiallyConsistent,
270 llvm::AtomicOrdering Failure =
271 llvm::AtomicOrdering::SequentiallyConsistent,
Alexey Bataevb8329262015-02-27 06:33:30 +0000272 bool IsWeak = false);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000273 /// Emit atomic update as libcalls.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000274 void
275 EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
276 const llvm::function_ref<RValue(RValue)> &UpdateOp,
277 bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000278 /// Emit atomic update as LLVM instructions.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000279 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO,
280 const llvm::function_ref<RValue(RValue)> &UpdateOp,
281 bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000282 /// Emit atomic update as libcalls.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000283 void EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO, RValue UpdateRVal,
284 bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000285 /// Emit atomic update as LLVM instructions.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000286 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRal,
287 bool IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +0000288 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000289}
John McCalla8ec7eb2013-03-07 21:37:17 +0000290
John McCall7f416cc2015-09-08 08:05:57 +0000291Address AtomicInfo::CreateTempAlloca() const {
292 Address TempAlloca = CGF.CreateMemTemp(
Alexey Bataevb8329262015-02-27 06:33:30 +0000293 (LVal.isBitField() && ValueSizeInBits > AtomicSizeInBits) ? ValueTy
294 : AtomicTy,
John McCall7f416cc2015-09-08 08:05:57 +0000295 getAtomicAlignment(),
Alexey Bataevb8329262015-02-27 06:33:30 +0000296 "atomic-temp");
Alexey Bataevb8329262015-02-27 06:33:30 +0000297 // Cast to pointer to value type for bitfields.
298 if (LVal.isBitField())
299 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +0000300 TempAlloca, getAtomicAddress().getType());
Alexey Bataevb8329262015-02-27 06:33:30 +0000301 return TempAlloca;
302}
303
John McCalla8ec7eb2013-03-07 21:37:17 +0000304static RValue emitAtomicLibcall(CodeGenFunction &CGF,
305 StringRef fnName,
306 QualType resultType,
307 CallArgList &args) {
308 const CGFunctionInfo &fnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000309 CGF.CGM.getTypes().arrangeBuiltinFunctionCall(resultType, args);
John McCalla8ec7eb2013-03-07 21:37:17 +0000310 llvm::FunctionType *fnTy = CGF.CGM.getTypes().GetFunctionType(fnInfo);
311 llvm::Constant *fn = CGF.CGM.CreateRuntimeFunction(fnTy, fnName);
John McCallb92ab1a2016-10-26 23:46:34 +0000312 auto callee = CGCallee::forDirect(fn);
313 return CGF.EmitCall(fnInfo, callee, ReturnValueSlot(), args);
John McCalla8ec7eb2013-03-07 21:37:17 +0000314}
315
316/// Does a store of the given IR type modify the full expected width?
317static bool isFullSizeType(CodeGenModule &CGM, llvm::Type *type,
318 uint64_t expectedSize) {
319 return (CGM.getDataLayout().getTypeStoreSize(type) * 8 == expectedSize);
320}
321
322/// Does the atomic type require memsetting to zero before initialization?
323///
324/// The IR type is provided as a way of making certain queries faster.
325bool AtomicInfo::requiresMemSetZero(llvm::Type *type) const {
326 // If the atomic type has size padding, we definitely need a memset.
327 if (hasPadding()) return true;
328
329 // Otherwise, do some simple heuristics to try to avoid it:
330 switch (getEvaluationKind()) {
331 // For scalars and complexes, check whether the store size of the
332 // type uses the full size.
333 case TEK_Scalar:
334 return !isFullSizeType(CGF.CGM, type, AtomicSizeInBits);
335 case TEK_Complex:
336 return !isFullSizeType(CGF.CGM, type->getStructElementType(0),
337 AtomicSizeInBits / 2);
338
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000339 // Padding in structs has an undefined bit pattern. User beware.
John McCalla8ec7eb2013-03-07 21:37:17 +0000340 case TEK_Aggregate:
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000341 return false;
John McCalla8ec7eb2013-03-07 21:37:17 +0000342 }
343 llvm_unreachable("bad evaluation kind");
344}
345
Alexey Bataevb57056f2015-01-22 06:17:56 +0000346bool AtomicInfo::emitMemSetZeroIfNecessary() const {
347 assert(LVal.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000348 llvm::Value *addr = LVal.getPointer();
John McCalla8ec7eb2013-03-07 21:37:17 +0000349 if (!requiresMemSetZero(addr->getType()->getPointerElementType()))
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000350 return false;
John McCalla8ec7eb2013-03-07 21:37:17 +0000351
Alexey Bataevb8329262015-02-27 06:33:30 +0000352 CGF.Builder.CreateMemSet(
353 addr, llvm::ConstantInt::get(CGF.Int8Ty, 0),
354 CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits).getQuantity(),
355 LVal.getAlignment().getQuantity());
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000356 return true;
John McCalla8ec7eb2013-03-07 21:37:17 +0000357}
358
Tim Northovercadbbe12014-06-13 19:43:04 +0000359static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak,
John McCall7f416cc2015-09-08 08:05:57 +0000360 Address Dest, Address Ptr,
361 Address Val1, Address Val2,
362 uint64_t Size,
Tim Northover9c177222014-03-13 19:25:48 +0000363 llvm::AtomicOrdering SuccessOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000364 llvm::AtomicOrdering FailureOrder,
365 llvm::SyncScope::ID Scope) {
Tim Northover9c177222014-03-13 19:25:48 +0000366 // Note that cmpxchg doesn't support weak cmpxchg, at least at the moment.
John McCall7f416cc2015-09-08 08:05:57 +0000367 llvm::Value *Expected = CGF.Builder.CreateLoad(Val1);
368 llvm::Value *Desired = CGF.Builder.CreateLoad(Val2);
Tim Northover9c177222014-03-13 19:25:48 +0000369
Tim Northoverb49b04b2014-06-13 14:24:59 +0000370 llvm::AtomicCmpXchgInst *Pair = CGF.Builder.CreateAtomicCmpXchg(
Yaxun Liu39195062017-08-04 18:16:31 +0000371 Ptr.getPointer(), Expected, Desired, SuccessOrder, FailureOrder,
372 Scope);
Tim Northoverb49b04b2014-06-13 14:24:59 +0000373 Pair->setVolatile(E->isVolatile());
Tim Northovercadbbe12014-06-13 19:43:04 +0000374 Pair->setWeak(IsWeak);
Tim Northover9c177222014-03-13 19:25:48 +0000375
376 // Cmp holds the result of the compare-exchange operation: true on success,
377 // false on failure.
Tim Northoverb49b04b2014-06-13 14:24:59 +0000378 llvm::Value *Old = CGF.Builder.CreateExtractValue(Pair, 0);
379 llvm::Value *Cmp = CGF.Builder.CreateExtractValue(Pair, 1);
Tim Northover9c177222014-03-13 19:25:48 +0000380
381 // This basic block is used to hold the store instruction if the operation
382 // failed.
383 llvm::BasicBlock *StoreExpectedBB =
384 CGF.createBasicBlock("cmpxchg.store_expected", CGF.CurFn);
385
386 // This basic block is the exit point of the operation, we should end up
387 // here regardless of whether or not the operation succeeded.
388 llvm::BasicBlock *ContinueBB =
389 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
390
391 // Update Expected if Expected isn't equal to Old, otherwise branch to the
392 // exit point.
393 CGF.Builder.CreateCondBr(Cmp, ContinueBB, StoreExpectedBB);
394
395 CGF.Builder.SetInsertPoint(StoreExpectedBB);
396 // Update the memory at Expected with Old's value.
John McCall7f416cc2015-09-08 08:05:57 +0000397 CGF.Builder.CreateStore(Old, Val1);
Tim Northover9c177222014-03-13 19:25:48 +0000398 // Finally, branch to the exit point.
399 CGF.Builder.CreateBr(ContinueBB);
400
401 CGF.Builder.SetInsertPoint(ContinueBB);
402 // Update the memory at Dest with Cmp's value.
403 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
Tim Northover9c177222014-03-13 19:25:48 +0000404}
405
406/// Given an ordering required on success, emit all possible cmpxchg
407/// instructions to cope with the provided (but possibly only dynamically known)
408/// FailureOrder.
409static void emitAtomicCmpXchgFailureSet(CodeGenFunction &CGF, AtomicExpr *E,
JF Bastiendda2cb12016-04-18 18:01:49 +0000410 bool IsWeak, Address Dest, Address Ptr,
411 Address Val1, Address Val2,
Tim Northover9c177222014-03-13 19:25:48 +0000412 llvm::Value *FailureOrderVal,
John McCall7f416cc2015-09-08 08:05:57 +0000413 uint64_t Size,
Yaxun Liu39195062017-08-04 18:16:31 +0000414 llvm::AtomicOrdering SuccessOrder,
415 llvm::SyncScope::ID Scope) {
Tim Northover9c177222014-03-13 19:25:48 +0000416 llvm::AtomicOrdering FailureOrder;
417 if (llvm::ConstantInt *FO = dyn_cast<llvm::ConstantInt>(FailureOrderVal)) {
JF Bastiendda2cb12016-04-18 18:01:49 +0000418 auto FOS = FO->getSExtValue();
419 if (!llvm::isValidAtomicOrderingCABI(FOS))
JF Bastien92f4ef12016-04-06 17:26:42 +0000420 FailureOrder = llvm::AtomicOrdering::Monotonic;
JF Bastiendda2cb12016-04-18 18:01:49 +0000421 else
422 switch ((llvm::AtomicOrderingCABI)FOS) {
423 case llvm::AtomicOrderingCABI::relaxed:
424 case llvm::AtomicOrderingCABI::release:
425 case llvm::AtomicOrderingCABI::acq_rel:
426 FailureOrder = llvm::AtomicOrdering::Monotonic;
427 break;
428 case llvm::AtomicOrderingCABI::consume:
429 case llvm::AtomicOrderingCABI::acquire:
430 FailureOrder = llvm::AtomicOrdering::Acquire;
431 break;
432 case llvm::AtomicOrderingCABI::seq_cst:
433 FailureOrder = llvm::AtomicOrdering::SequentiallyConsistent;
434 break;
435 }
JF Bastiendd11ee72016-04-06 23:37:36 +0000436 if (isStrongerThan(FailureOrder, SuccessOrder)) {
437 // Don't assert on undefined behavior "failure argument shall be no
438 // stronger than the success argument".
Tim Northover9c177222014-03-13 19:25:48 +0000439 FailureOrder =
JF Bastiendda2cb12016-04-18 18:01:49 +0000440 llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrder);
Tim Northover9c177222014-03-13 19:25:48 +0000441 }
JF Bastiendda2cb12016-04-18 18:01:49 +0000442 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000443 FailureOrder, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000444 return;
445 }
446
447 // Create all the relevant BB's
Craig Topper8a13c412014-05-21 05:09:00 +0000448 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
449 *SeqCstBB = nullptr;
Tim Northover9c177222014-03-13 19:25:48 +0000450 MonotonicBB = CGF.createBasicBlock("monotonic_fail", CGF.CurFn);
JF Bastien92f4ef12016-04-06 17:26:42 +0000451 if (SuccessOrder != llvm::AtomicOrdering::Monotonic &&
452 SuccessOrder != llvm::AtomicOrdering::Release)
Tim Northover9c177222014-03-13 19:25:48 +0000453 AcquireBB = CGF.createBasicBlock("acquire_fail", CGF.CurFn);
JF Bastien92f4ef12016-04-06 17:26:42 +0000454 if (SuccessOrder == llvm::AtomicOrdering::SequentiallyConsistent)
Tim Northover9c177222014-03-13 19:25:48 +0000455 SeqCstBB = CGF.createBasicBlock("seqcst_fail", CGF.CurFn);
456
457 llvm::BasicBlock *ContBB = CGF.createBasicBlock("atomic.continue", CGF.CurFn);
458
459 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(FailureOrderVal, MonotonicBB);
460
461 // Emit all the different atomics
462
463 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
464 // doesn't matter unless someone is crazy enough to use something that
465 // doesn't fold to a constant for the ordering.
466 CGF.Builder.SetInsertPoint(MonotonicBB);
Tim Northovercadbbe12014-06-13 19:43:04 +0000467 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000468 Size, SuccessOrder, llvm::AtomicOrdering::Monotonic, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000469 CGF.Builder.CreateBr(ContBB);
470
471 if (AcquireBB) {
472 CGF.Builder.SetInsertPoint(AcquireBB);
Tim Northovercadbbe12014-06-13 19:43:04 +0000473 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000474 Size, SuccessOrder, llvm::AtomicOrdering::Acquire, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000475 CGF.Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +0000476 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
Tim Northover9c177222014-03-13 19:25:48 +0000477 AcquireBB);
JF Bastiendda2cb12016-04-18 18:01:49 +0000478 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
Tim Northover9c177222014-03-13 19:25:48 +0000479 AcquireBB);
480 }
481 if (SeqCstBB) {
482 CGF.Builder.SetInsertPoint(SeqCstBB);
JF Bastien92f4ef12016-04-06 17:26:42 +0000483 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000484 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000485 CGF.Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +0000486 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
Tim Northover9c177222014-03-13 19:25:48 +0000487 SeqCstBB);
488 }
489
490 CGF.Builder.SetInsertPoint(ContBB);
491}
492
John McCall7f416cc2015-09-08 08:05:57 +0000493static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest,
494 Address Ptr, Address Val1, Address Val2,
Tim Northovercadbbe12014-06-13 19:43:04 +0000495 llvm::Value *IsWeak, llvm::Value *FailureOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000496 uint64_t Size, llvm::AtomicOrdering Order,
497 llvm::SyncScope::ID Scope) {
John McCallfc207f22013-03-07 21:37:12 +0000498 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
499 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
500
501 switch (E->getOp()) {
502 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000503 case AtomicExpr::AO__opencl_atomic_init:
John McCallfc207f22013-03-07 21:37:12 +0000504 llvm_unreachable("Already handled!");
505
506 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +0000507 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
Tim Northovercadbbe12014-06-13 19:43:04 +0000508 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000509 FailureOrder, Size, Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000510 return;
Tim Northovercadbbe12014-06-13 19:43:04 +0000511 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +0000512 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Tim Northovercadbbe12014-06-13 19:43:04 +0000513 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000514 FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000515 return;
516 case AtomicExpr::AO__atomic_compare_exchange:
517 case AtomicExpr::AO__atomic_compare_exchange_n: {
518 if (llvm::ConstantInt *IsWeakC = dyn_cast<llvm::ConstantInt>(IsWeak)) {
519 emitAtomicCmpXchgFailureSet(CGF, E, IsWeakC->getZExtValue(), Dest, Ptr,
Yaxun Liu39195062017-08-04 18:16:31 +0000520 Val1, Val2, FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000521 } else {
522 // Create all the relevant BB's
523 llvm::BasicBlock *StrongBB =
524 CGF.createBasicBlock("cmpxchg.strong", CGF.CurFn);
525 llvm::BasicBlock *WeakBB = CGF.createBasicBlock("cmxchg.weak", CGF.CurFn);
526 llvm::BasicBlock *ContBB =
527 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
528
529 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(IsWeak, WeakBB);
530 SI->addCase(CGF.Builder.getInt1(false), StrongBB);
531
532 CGF.Builder.SetInsertPoint(StrongBB);
533 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000534 FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000535 CGF.Builder.CreateBr(ContBB);
536
537 CGF.Builder.SetInsertPoint(WeakBB);
538 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000539 FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000540 CGF.Builder.CreateBr(ContBB);
541
542 CGF.Builder.SetInsertPoint(ContBB);
543 }
544 return;
545 }
John McCallfc207f22013-03-07 21:37:12 +0000546 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +0000547 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +0000548 case AtomicExpr::AO__atomic_load_n:
549 case AtomicExpr::AO__atomic_load: {
550 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
Yaxun Liu39195062017-08-04 18:16:31 +0000551 Load->setAtomic(Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000552 Load->setVolatile(E->isVolatile());
John McCall7f416cc2015-09-08 08:05:57 +0000553 CGF.Builder.CreateStore(Load, Dest);
John McCallfc207f22013-03-07 21:37:12 +0000554 return;
555 }
556
557 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +0000558 case AtomicExpr::AO__opencl_atomic_store:
John McCallfc207f22013-03-07 21:37:12 +0000559 case AtomicExpr::AO__atomic_store:
560 case AtomicExpr::AO__atomic_store_n: {
John McCall7f416cc2015-09-08 08:05:57 +0000561 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
John McCallfc207f22013-03-07 21:37:12 +0000562 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
Yaxun Liu39195062017-08-04 18:16:31 +0000563 Store->setAtomic(Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000564 Store->setVolatile(E->isVolatile());
565 return;
566 }
567
568 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +0000569 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +0000570 case AtomicExpr::AO__atomic_exchange_n:
571 case AtomicExpr::AO__atomic_exchange:
572 Op = llvm::AtomicRMWInst::Xchg;
573 break;
574
575 case AtomicExpr::AO__atomic_add_fetch:
576 PostOp = llvm::Instruction::Add;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000577 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000578 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +0000579 case AtomicExpr::AO__opencl_atomic_fetch_add:
John McCallfc207f22013-03-07 21:37:12 +0000580 case AtomicExpr::AO__atomic_fetch_add:
581 Op = llvm::AtomicRMWInst::Add;
582 break;
583
584 case AtomicExpr::AO__atomic_sub_fetch:
585 PostOp = llvm::Instruction::Sub;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000586 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000587 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000588 case AtomicExpr::AO__opencl_atomic_fetch_sub:
John McCallfc207f22013-03-07 21:37:12 +0000589 case AtomicExpr::AO__atomic_fetch_sub:
590 Op = llvm::AtomicRMWInst::Sub;
591 break;
592
Yaxun Liu39195062017-08-04 18:16:31 +0000593 case AtomicExpr::AO__opencl_atomic_fetch_min:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +0000594 case AtomicExpr::AO__atomic_fetch_min:
Yaxun Liu39195062017-08-04 18:16:31 +0000595 Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Min
596 : llvm::AtomicRMWInst::UMin;
597 break;
598
599 case AtomicExpr::AO__opencl_atomic_fetch_max:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +0000600 case AtomicExpr::AO__atomic_fetch_max:
Yaxun Liu39195062017-08-04 18:16:31 +0000601 Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Max
602 : llvm::AtomicRMWInst::UMax;
603 break;
604
John McCallfc207f22013-03-07 21:37:12 +0000605 case AtomicExpr::AO__atomic_and_fetch:
606 PostOp = llvm::Instruction::And;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000607 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000608 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +0000609 case AtomicExpr::AO__opencl_atomic_fetch_and:
John McCallfc207f22013-03-07 21:37:12 +0000610 case AtomicExpr::AO__atomic_fetch_and:
611 Op = llvm::AtomicRMWInst::And;
612 break;
613
614 case AtomicExpr::AO__atomic_or_fetch:
615 PostOp = llvm::Instruction::Or;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000616 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000617 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +0000618 case AtomicExpr::AO__opencl_atomic_fetch_or:
John McCallfc207f22013-03-07 21:37:12 +0000619 case AtomicExpr::AO__atomic_fetch_or:
620 Op = llvm::AtomicRMWInst::Or;
621 break;
622
623 case AtomicExpr::AO__atomic_xor_fetch:
624 PostOp = llvm::Instruction::Xor;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000625 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000626 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +0000627 case AtomicExpr::AO__opencl_atomic_fetch_xor:
John McCallfc207f22013-03-07 21:37:12 +0000628 case AtomicExpr::AO__atomic_fetch_xor:
629 Op = llvm::AtomicRMWInst::Xor;
630 break;
631
632 case AtomicExpr::AO__atomic_nand_fetch:
James Y Knight7aefb5b2015-11-12 18:37:29 +0000633 PostOp = llvm::Instruction::And; // the NOT is special cased below
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000634 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000635 case AtomicExpr::AO__atomic_fetch_nand:
636 Op = llvm::AtomicRMWInst::Nand;
637 break;
638 }
639
John McCall7f416cc2015-09-08 08:05:57 +0000640 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
John McCallfc207f22013-03-07 21:37:12 +0000641 llvm::AtomicRMWInst *RMWI =
Yaxun Liu39195062017-08-04 18:16:31 +0000642 CGF.Builder.CreateAtomicRMW(Op, Ptr.getPointer(), LoadVal1, Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000643 RMWI->setVolatile(E->isVolatile());
644
645 // For __atomic_*_fetch operations, perform the operation again to
646 // determine the value which was written.
647 llvm::Value *Result = RMWI;
648 if (PostOp)
649 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
650 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
651 Result = CGF.Builder.CreateNot(Result);
John McCall7f416cc2015-09-08 08:05:57 +0000652 CGF.Builder.CreateStore(Result, Dest);
John McCallfc207f22013-03-07 21:37:12 +0000653}
654
655// This function emits any expression (scalar, complex, or aggregate)
656// into a temporary alloca.
John McCall7f416cc2015-09-08 08:05:57 +0000657static Address
John McCallfc207f22013-03-07 21:37:12 +0000658EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
John McCall7f416cc2015-09-08 08:05:57 +0000659 Address DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
John McCallfc207f22013-03-07 21:37:12 +0000660 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
661 /*Init*/ true);
662 return DeclPtr;
663}
664
Yaxun Liu30d652a2017-08-15 16:02:49 +0000665static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *Expr, Address Dest,
666 Address Ptr, Address Val1, Address Val2,
667 llvm::Value *IsWeak, llvm::Value *FailureOrder,
668 uint64_t Size, llvm::AtomicOrdering Order,
669 llvm::Value *Scope) {
670 auto ScopeModel = Expr->getScopeModel();
671
672 // LLVM atomic instructions always have synch scope. If clang atomic
673 // expression has no scope operand, use default LLVM synch scope.
674 if (!ScopeModel) {
675 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
676 Order, CGF.CGM.getLLVMContext().getOrInsertSyncScopeID(""));
677 return;
678 }
679
680 // Handle constant scope.
681 if (auto SC = dyn_cast<llvm::ConstantInt>(Scope)) {
682 auto SCID = CGF.getTargetHooks().getLLVMSyncScopeID(
683 ScopeModel->map(SC->getZExtValue()), CGF.CGM.getLLVMContext());
684 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
685 Order, SCID);
686 return;
687 }
688
689 // Handle non-constant scope.
690 auto &Builder = CGF.Builder;
691 auto Scopes = ScopeModel->getRuntimeValues();
692 llvm::DenseMap<unsigned, llvm::BasicBlock *> BB;
693 for (auto S : Scopes)
694 BB[S] = CGF.createBasicBlock(getAsString(ScopeModel->map(S)), CGF.CurFn);
695
696 llvm::BasicBlock *ContBB =
697 CGF.createBasicBlock("atomic.scope.continue", CGF.CurFn);
698
699 auto *SC = Builder.CreateIntCast(Scope, Builder.getInt32Ty(), false);
700 // If unsupported synch scope is encountered at run time, assume a fallback
701 // synch scope value.
702 auto FallBack = ScopeModel->getFallBackValue();
703 llvm::SwitchInst *SI = Builder.CreateSwitch(SC, BB[FallBack]);
704 for (auto S : Scopes) {
705 auto *B = BB[S];
706 if (S != FallBack)
707 SI->addCase(Builder.getInt32(S), B);
708
709 Builder.SetInsertPoint(B);
710 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
711 Order,
712 CGF.getTargetHooks().getLLVMSyncScopeID(ScopeModel->map(S),
713 CGF.getLLVMContext()));
714 Builder.CreateBr(ContBB);
715 }
716
717 Builder.SetInsertPoint(ContBB);
718}
719
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000720static void
721AddDirectArgument(CodeGenFunction &CGF, CallArgList &Args,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000722 bool UseOptimizedLibcall, llvm::Value *Val, QualType ValTy,
David Majnemer0392cf82014-08-29 07:27:49 +0000723 SourceLocation Loc, CharUnits SizeInChars) {
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000724 if (UseOptimizedLibcall) {
725 // Load value and pass it to the function directly.
John McCall7f416cc2015-09-08 08:05:57 +0000726 CharUnits Align = CGF.getContext().getTypeAlignInChars(ValTy);
David Majnemer0392cf82014-08-29 07:27:49 +0000727 int64_t SizeInBits = CGF.getContext().toBits(SizeInChars);
728 ValTy =
729 CGF.getContext().getIntTypeForBitwidth(SizeInBits, /*Signed=*/false);
730 llvm::Type *IPtrTy = llvm::IntegerType::get(CGF.getLLVMContext(),
731 SizeInBits)->getPointerTo();
John McCall7f416cc2015-09-08 08:05:57 +0000732 Address Ptr = Address(CGF.Builder.CreateBitCast(Val, IPtrTy), Align);
733 Val = CGF.EmitLoadOfScalar(Ptr, false,
734 CGF.getContext().getPointerType(ValTy),
David Majnemer0392cf82014-08-29 07:27:49 +0000735 Loc);
736 // Coerce the value into an appropriately sized integer type.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000737 Args.add(RValue::get(Val), ValTy);
738 } else {
739 // Non-optimized functions always take a reference.
740 Args.add(RValue::get(CGF.EmitCastToVoidPtr(Val)),
741 CGF.getContext().VoidPtrTy);
742 }
743}
744
Tim Northovercc2a6e02015-11-09 19:56:35 +0000745RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
John McCallfc207f22013-03-07 21:37:12 +0000746 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
747 QualType MemTy = AtomicTy;
748 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
749 MemTy = AT->getValueType();
John McCall7f416cc2015-09-08 08:05:57 +0000750 llvm::Value *IsWeak = nullptr, *OrderFail = nullptr;
751
752 Address Val1 = Address::invalid();
753 Address Val2 = Address::invalid();
Tim Northovercc2a6e02015-11-09 19:56:35 +0000754 Address Dest = Address::invalid();
Wei Mi01414bd2017-09-25 19:57:59 +0000755 Address Ptr = EmitPointerWithAlignment(E->getPtr());
756
Tim Northover9dc1d0c2018-04-23 08:16:24 +0000757 if (E->getOp() == AtomicExpr::AO__c11_atomic_init ||
758 E->getOp() == AtomicExpr::AO__opencl_atomic_init) {
759 LValue lvalue = MakeAddrLValue(Ptr, AtomicTy);
760 EmitAtomicInit(E->getVal1(), lvalue);
761 return RValue::get(nullptr);
762 }
763
Wei Mi01414bd2017-09-25 19:57:59 +0000764 CharUnits sizeChars, alignChars;
765 std::tie(sizeChars, alignChars) = getContext().getTypeInfoInChars(AtomicTy);
766 uint64_t Size = sizeChars.getQuantity();
767 unsigned MaxInlineWidthInBits = getTarget().getMaxAtomicInlineWidth();
John McCallfc207f22013-03-07 21:37:12 +0000768
Richard Smithedb9fbb2018-09-07 21:24:27 +0000769 bool Oversized = getContext().toBits(sizeChars) > MaxInlineWidthInBits;
770 bool Misaligned = (Ptr.getAlignment() % sizeChars) != 0;
771 bool UseLibcall = Misaligned | Oversized;
772
773 if (UseLibcall) {
774 CGM.getDiags().Report(E->getBeginLoc(), diag::warn_atomic_op_misaligned)
775 << !Oversized;
776 }
John McCallfc207f22013-03-07 21:37:12 +0000777
Craig Topper8a13c412014-05-21 05:09:00 +0000778 llvm::Value *Order = EmitScalarExpr(E->getOrder());
Yaxun Liu30d652a2017-08-15 16:02:49 +0000779 llvm::Value *Scope =
780 E->getScopeModel() ? EmitScalarExpr(E->getScope()) : nullptr;
John McCallfc207f22013-03-07 21:37:12 +0000781
782 switch (E->getOp()) {
783 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000784 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000785 llvm_unreachable("Already handled above with EmitAtomicInit!");
John McCallfc207f22013-03-07 21:37:12 +0000786
787 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +0000788 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +0000789 case AtomicExpr::AO__atomic_load_n:
790 break;
791
792 case AtomicExpr::AO__atomic_load:
John McCall7f416cc2015-09-08 08:05:57 +0000793 Dest = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000794 break;
795
796 case AtomicExpr::AO__atomic_store:
John McCall7f416cc2015-09-08 08:05:57 +0000797 Val1 = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000798 break;
799
800 case AtomicExpr::AO__atomic_exchange:
John McCall7f416cc2015-09-08 08:05:57 +0000801 Val1 = EmitPointerWithAlignment(E->getVal1());
802 Dest = EmitPointerWithAlignment(E->getVal2());
John McCallfc207f22013-03-07 21:37:12 +0000803 break;
804
805 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
806 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +0000807 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
808 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
John McCallfc207f22013-03-07 21:37:12 +0000809 case AtomicExpr::AO__atomic_compare_exchange_n:
810 case AtomicExpr::AO__atomic_compare_exchange:
John McCall7f416cc2015-09-08 08:05:57 +0000811 Val1 = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000812 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
John McCall7f416cc2015-09-08 08:05:57 +0000813 Val2 = EmitPointerWithAlignment(E->getVal2());
John McCallfc207f22013-03-07 21:37:12 +0000814 else
815 Val2 = EmitValToTemp(*this, E->getVal2());
816 OrderFail = EmitScalarExpr(E->getOrderFail());
Yaxun Liu39195062017-08-04 18:16:31 +0000817 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
818 E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
Tim Northovercadbbe12014-06-13 19:43:04 +0000819 IsWeak = EmitScalarExpr(E->getWeak());
John McCallfc207f22013-03-07 21:37:12 +0000820 break;
821
822 case AtomicExpr::AO__c11_atomic_fetch_add:
823 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000824 case AtomicExpr::AO__opencl_atomic_fetch_add:
825 case AtomicExpr::AO__opencl_atomic_fetch_sub:
John McCallfc207f22013-03-07 21:37:12 +0000826 if (MemTy->isPointerType()) {
827 // For pointer arithmetic, we're required to do a bit of math:
828 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
829 // ... but only for the C11 builtins. The GNU builtins expect the
830 // user to multiply by sizeof(T).
831 QualType Val1Ty = E->getVal1()->getType();
832 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
833 CharUnits PointeeIncAmt =
834 getContext().getTypeSizeInChars(MemTy->getPointeeType());
835 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
John McCall7f416cc2015-09-08 08:05:57 +0000836 auto Temp = CreateMemTemp(Val1Ty, ".atomictmp");
837 Val1 = Temp;
838 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Temp, Val1Ty));
John McCallfc207f22013-03-07 21:37:12 +0000839 break;
840 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000841 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000842 case AtomicExpr::AO__atomic_fetch_add:
843 case AtomicExpr::AO__atomic_fetch_sub:
844 case AtomicExpr::AO__atomic_add_fetch:
845 case AtomicExpr::AO__atomic_sub_fetch:
846 case AtomicExpr::AO__c11_atomic_store:
847 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +0000848 case AtomicExpr::AO__opencl_atomic_store:
849 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +0000850 case AtomicExpr::AO__atomic_store_n:
851 case AtomicExpr::AO__atomic_exchange_n:
852 case AtomicExpr::AO__c11_atomic_fetch_and:
853 case AtomicExpr::AO__c11_atomic_fetch_or:
854 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +0000855 case AtomicExpr::AO__opencl_atomic_fetch_and:
856 case AtomicExpr::AO__opencl_atomic_fetch_or:
857 case AtomicExpr::AO__opencl_atomic_fetch_xor:
858 case AtomicExpr::AO__opencl_atomic_fetch_min:
859 case AtomicExpr::AO__opencl_atomic_fetch_max:
John McCallfc207f22013-03-07 21:37:12 +0000860 case AtomicExpr::AO__atomic_fetch_and:
861 case AtomicExpr::AO__atomic_fetch_or:
862 case AtomicExpr::AO__atomic_fetch_xor:
863 case AtomicExpr::AO__atomic_fetch_nand:
864 case AtomicExpr::AO__atomic_and_fetch:
865 case AtomicExpr::AO__atomic_or_fetch:
866 case AtomicExpr::AO__atomic_xor_fetch:
867 case AtomicExpr::AO__atomic_nand_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +0000868 case AtomicExpr::AO__atomic_fetch_min:
869 case AtomicExpr::AO__atomic_fetch_max:
John McCallfc207f22013-03-07 21:37:12 +0000870 Val1 = EmitValToTemp(*this, E->getVal1());
871 break;
872 }
873
David Majnemeree8d04d2014-12-12 08:16:09 +0000874 QualType RValTy = E->getType().getUnqualifiedType();
875
Tim Northovercc2a6e02015-11-09 19:56:35 +0000876 // The inlined atomics only function on iN types, where N is a power of 2. We
877 // need to make sure (via temporaries if necessary) that all incoming values
878 // are compatible.
879 LValue AtomicVal = MakeAddrLValue(Ptr, AtomicTy);
880 AtomicInfo Atomics(*this, AtomicVal);
881
882 Ptr = Atomics.emitCastToAtomicIntPointer(Ptr);
883 if (Val1.isValid()) Val1 = Atomics.convertToAtomicIntPointer(Val1);
884 if (Val2.isValid()) Val2 = Atomics.convertToAtomicIntPointer(Val2);
885 if (Dest.isValid())
886 Dest = Atomics.emitCastToAtomicIntPointer(Dest);
887 else if (E->isCmpXChg())
888 Dest = CreateMemTemp(RValTy, "cmpxchg.bool");
889 else if (!RValTy->isVoidType())
890 Dest = Atomics.emitCastToAtomicIntPointer(Atomics.CreateTempAlloca());
John McCallfc207f22013-03-07 21:37:12 +0000891
892 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
893 if (UseLibcall) {
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000894 bool UseOptimizedLibcall = false;
895 switch (E->getOp()) {
James Y Knight81167fb2015-08-05 16:57:36 +0000896 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000897 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000898 llvm_unreachable("Already handled above with EmitAtomicInit!");
899
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000900 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +0000901 case AtomicExpr::AO__opencl_atomic_fetch_add:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000902 case AtomicExpr::AO__atomic_fetch_add:
903 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +0000904 case AtomicExpr::AO__opencl_atomic_fetch_and:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000905 case AtomicExpr::AO__atomic_fetch_and:
906 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +0000907 case AtomicExpr::AO__opencl_atomic_fetch_or:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000908 case AtomicExpr::AO__atomic_fetch_or:
James Y Knight81167fb2015-08-05 16:57:36 +0000909 case AtomicExpr::AO__atomic_fetch_nand:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000910 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000911 case AtomicExpr::AO__opencl_atomic_fetch_sub:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000912 case AtomicExpr::AO__atomic_fetch_sub:
913 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +0000914 case AtomicExpr::AO__opencl_atomic_fetch_xor:
915 case AtomicExpr::AO__opencl_atomic_fetch_min:
916 case AtomicExpr::AO__opencl_atomic_fetch_max:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000917 case AtomicExpr::AO__atomic_fetch_xor:
James Y Knight81167fb2015-08-05 16:57:36 +0000918 case AtomicExpr::AO__atomic_add_fetch:
919 case AtomicExpr::AO__atomic_and_fetch:
920 case AtomicExpr::AO__atomic_nand_fetch:
921 case AtomicExpr::AO__atomic_or_fetch:
922 case AtomicExpr::AO__atomic_sub_fetch:
923 case AtomicExpr::AO__atomic_xor_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +0000924 case AtomicExpr::AO__atomic_fetch_min:
925 case AtomicExpr::AO__atomic_fetch_max:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000926 // For these, only library calls for certain sizes exist.
927 UseOptimizedLibcall = true;
928 break;
James Y Knight81167fb2015-08-05 16:57:36 +0000929
Richard Smithda3729d2018-09-07 23:57:54 +0000930 case AtomicExpr::AO__atomic_load:
931 case AtomicExpr::AO__atomic_store:
932 case AtomicExpr::AO__atomic_exchange:
933 case AtomicExpr::AO__atomic_compare_exchange:
934 // Use the generic version if we don't know that the operand will be
935 // suitably aligned for the optimized version.
936 if (Misaligned)
937 break;
938 LLVM_FALLTHROUGH;
James Y Knight81167fb2015-08-05 16:57:36 +0000939 case AtomicExpr::AO__c11_atomic_load:
940 case AtomicExpr::AO__c11_atomic_store:
941 case AtomicExpr::AO__c11_atomic_exchange:
942 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
943 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +0000944 case AtomicExpr::AO__opencl_atomic_load:
945 case AtomicExpr::AO__opencl_atomic_store:
946 case AtomicExpr::AO__opencl_atomic_exchange:
947 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
948 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
James Y Knight81167fb2015-08-05 16:57:36 +0000949 case AtomicExpr::AO__atomic_load_n:
James Y Knight81167fb2015-08-05 16:57:36 +0000950 case AtomicExpr::AO__atomic_store_n:
James Y Knight81167fb2015-08-05 16:57:36 +0000951 case AtomicExpr::AO__atomic_exchange_n:
James Y Knight81167fb2015-08-05 16:57:36 +0000952 case AtomicExpr::AO__atomic_compare_exchange_n:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000953 // Only use optimized library calls for sizes for which they exist.
Richard Smithda3729d2018-09-07 23:57:54 +0000954 // FIXME: Size == 16 optimized library functions exist too.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000955 if (Size == 1 || Size == 2 || Size == 4 || Size == 8)
956 UseOptimizedLibcall = true;
957 break;
958 }
John McCallfc207f22013-03-07 21:37:12 +0000959
John McCallfc207f22013-03-07 21:37:12 +0000960 CallArgList Args;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000961 if (!UseOptimizedLibcall) {
962 // For non-optimized library calls, the size is the first parameter
963 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
964 getContext().getSizeType());
965 }
966 // Atomic address is the first or second parameter
Yaxun Liu39195062017-08-04 18:16:31 +0000967 // The OpenCL atomic library functions only accept pointer arguments to
968 // generic address space.
969 auto CastToGenericAddrSpace = [&](llvm::Value *V, QualType PT) {
970 if (!E->isOpenCL())
971 return V;
972 auto AS = PT->getAs<PointerType>()->getPointeeType().getAddressSpace();
973 if (AS == LangAS::opencl_generic)
974 return V;
975 auto DestAS = getContext().getTargetAddressSpace(LangAS::opencl_generic);
976 auto T = V->getType();
977 auto *DestType = T->getPointerElementType()->getPointerTo(DestAS);
978
979 return getTargetHooks().performAddrSpaceCast(
980 *this, V, AS, LangAS::opencl_generic, DestType, false);
981 };
982
983 Args.add(RValue::get(CastToGenericAddrSpace(
984 EmitCastToVoidPtr(Ptr.getPointer()), E->getPtr()->getType())),
John McCall7f416cc2015-09-08 08:05:57 +0000985 getContext().VoidPtrTy);
John McCallfc207f22013-03-07 21:37:12 +0000986
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000987 std::string LibCallName;
Logan Chien74798a32014-03-26 17:35:01 +0000988 QualType LoweredMemTy =
989 MemTy->isPointerType() ? getContext().getIntPtrType() : MemTy;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000990 QualType RetTy;
991 bool HaveRetTy = false;
James Y Knight7aefb5b2015-11-12 18:37:29 +0000992 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
John McCallfc207f22013-03-07 21:37:12 +0000993 switch (E->getOp()) {
James Y Knight81167fb2015-08-05 16:57:36 +0000994 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000995 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000996 llvm_unreachable("Already handled!");
997
John McCallfc207f22013-03-07 21:37:12 +0000998 // There is only one libcall for compare an exchange, because there is no
999 // optimisation benefit possible from a libcall version of a weak compare
1000 // and exchange.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001001 // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
John McCallfc207f22013-03-07 21:37:12 +00001002 // void *desired, int success, int failure)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001003 // bool __atomic_compare_exchange_N(T *mem, T *expected, T desired,
1004 // int success, int failure)
John McCallfc207f22013-03-07 21:37:12 +00001005 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1006 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +00001007 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1008 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
John McCallfc207f22013-03-07 21:37:12 +00001009 case AtomicExpr::AO__atomic_compare_exchange:
1010 case AtomicExpr::AO__atomic_compare_exchange_n:
1011 LibCallName = "__atomic_compare_exchange";
1012 RetTy = getContext().BoolTy;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001013 HaveRetTy = true;
Yaxun Liu39195062017-08-04 18:16:31 +00001014 Args.add(
1015 RValue::get(CastToGenericAddrSpace(
1016 EmitCastToVoidPtr(Val1.getPointer()), E->getVal1()->getType())),
1017 getContext().VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001018 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val2.getPointer(),
1019 MemTy, E->getExprLoc(), sizeChars);
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001020 Args.add(RValue::get(Order), getContext().IntTy);
John McCallfc207f22013-03-07 21:37:12 +00001021 Order = OrderFail;
1022 break;
1023 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
1024 // int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001025 // T __atomic_exchange_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +00001026 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00001027 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +00001028 case AtomicExpr::AO__atomic_exchange_n:
1029 case AtomicExpr::AO__atomic_exchange:
1030 LibCallName = "__atomic_exchange";
John McCall7f416cc2015-09-08 08:05:57 +00001031 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1032 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001033 break;
1034 // void __atomic_store(size_t size, void *mem, void *val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001035 // void __atomic_store_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +00001036 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00001037 case AtomicExpr::AO__opencl_atomic_store:
John McCallfc207f22013-03-07 21:37:12 +00001038 case AtomicExpr::AO__atomic_store:
1039 case AtomicExpr::AO__atomic_store_n:
1040 LibCallName = "__atomic_store";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001041 RetTy = getContext().VoidTy;
1042 HaveRetTy = true;
John McCall7f416cc2015-09-08 08:05:57 +00001043 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1044 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001045 break;
1046 // void __atomic_load(size_t size, void *mem, void *return, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001047 // T __atomic_load_N(T *mem, int order)
John McCallfc207f22013-03-07 21:37:12 +00001048 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00001049 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +00001050 case AtomicExpr::AO__atomic_load:
1051 case AtomicExpr::AO__atomic_load_n:
1052 LibCallName = "__atomic_load";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001053 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001054 // T __atomic_add_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001055 // T __atomic_fetch_add_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001056 case AtomicExpr::AO__atomic_add_fetch:
1057 PostOp = llvm::Instruction::Add;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001058 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001059 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +00001060 case AtomicExpr::AO__opencl_atomic_fetch_add:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001061 case AtomicExpr::AO__atomic_fetch_add:
1062 LibCallName = "__atomic_fetch_add";
John McCall7f416cc2015-09-08 08:05:57 +00001063 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1064 LoweredMemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001065 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001066 // T __atomic_and_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001067 // T __atomic_fetch_and_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001068 case AtomicExpr::AO__atomic_and_fetch:
1069 PostOp = llvm::Instruction::And;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001070 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001071 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +00001072 case AtomicExpr::AO__opencl_atomic_fetch_and:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001073 case AtomicExpr::AO__atomic_fetch_and:
1074 LibCallName = "__atomic_fetch_and";
John McCall7f416cc2015-09-08 08:05:57 +00001075 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1076 MemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001077 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001078 // T __atomic_or_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001079 // T __atomic_fetch_or_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001080 case AtomicExpr::AO__atomic_or_fetch:
1081 PostOp = llvm::Instruction::Or;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001082 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001083 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +00001084 case AtomicExpr::AO__opencl_atomic_fetch_or:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001085 case AtomicExpr::AO__atomic_fetch_or:
1086 LibCallName = "__atomic_fetch_or";
John McCall7f416cc2015-09-08 08:05:57 +00001087 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1088 MemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001089 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001090 // T __atomic_sub_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001091 // T __atomic_fetch_sub_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001092 case AtomicExpr::AO__atomic_sub_fetch:
1093 PostOp = llvm::Instruction::Sub;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001094 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001095 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00001096 case AtomicExpr::AO__opencl_atomic_fetch_sub:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001097 case AtomicExpr::AO__atomic_fetch_sub:
1098 LibCallName = "__atomic_fetch_sub";
John McCall7f416cc2015-09-08 08:05:57 +00001099 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1100 LoweredMemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001101 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001102 // T __atomic_xor_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001103 // T __atomic_fetch_xor_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001104 case AtomicExpr::AO__atomic_xor_fetch:
1105 PostOp = llvm::Instruction::Xor;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001106 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001107 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00001108 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001109 case AtomicExpr::AO__atomic_fetch_xor:
1110 LibCallName = "__atomic_fetch_xor";
John McCall7f416cc2015-09-08 08:05:57 +00001111 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1112 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001113 break;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00001114 case AtomicExpr::AO__atomic_fetch_min:
Yaxun Liu39195062017-08-04 18:16:31 +00001115 case AtomicExpr::AO__opencl_atomic_fetch_min:
1116 LibCallName = E->getValueType()->isSignedIntegerType()
1117 ? "__atomic_fetch_min"
1118 : "__atomic_fetch_umin";
1119 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1120 LoweredMemTy, E->getExprLoc(), sizeChars);
1121 break;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00001122 case AtomicExpr::AO__atomic_fetch_max:
Yaxun Liu39195062017-08-04 18:16:31 +00001123 case AtomicExpr::AO__opencl_atomic_fetch_max:
1124 LibCallName = E->getValueType()->isSignedIntegerType()
1125 ? "__atomic_fetch_max"
1126 : "__atomic_fetch_umax";
1127 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1128 LoweredMemTy, E->getExprLoc(), sizeChars);
1129 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001130 // T __atomic_nand_fetch_N(T *mem, T val, int order)
James Y Knight81167fb2015-08-05 16:57:36 +00001131 // T __atomic_fetch_nand_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001132 case AtomicExpr::AO__atomic_nand_fetch:
1133 PostOp = llvm::Instruction::And; // the NOT is special cased below
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001134 LLVM_FALLTHROUGH;
James Y Knight81167fb2015-08-05 16:57:36 +00001135 case AtomicExpr::AO__atomic_fetch_nand:
1136 LibCallName = "__atomic_fetch_nand";
John McCall7f416cc2015-09-08 08:05:57 +00001137 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1138 MemTy, E->getExprLoc(), sizeChars);
James Y Knight81167fb2015-08-05 16:57:36 +00001139 break;
John McCallfc207f22013-03-07 21:37:12 +00001140 }
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001141
Yaxun Liu39195062017-08-04 18:16:31 +00001142 if (E->isOpenCL()) {
1143 LibCallName = std::string("__opencl") +
1144 StringRef(LibCallName).drop_front(1).str();
1145
1146 }
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001147 // Optimized functions have the size in their name.
1148 if (UseOptimizedLibcall)
1149 LibCallName += "_" + llvm::utostr(Size);
1150 // By default, assume we return a value of the atomic type.
1151 if (!HaveRetTy) {
1152 if (UseOptimizedLibcall) {
1153 // Value is returned directly.
David Majnemer0392cf82014-08-29 07:27:49 +00001154 // The function returns an appropriately sized integer type.
1155 RetTy = getContext().getIntTypeForBitwidth(
1156 getContext().toBits(sizeChars), /*Signed=*/false);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001157 } else {
1158 // Value is returned through parameter before the order.
1159 RetTy = getContext().VoidTy;
John McCall7f416cc2015-09-08 08:05:57 +00001160 Args.add(RValue::get(EmitCastToVoidPtr(Dest.getPointer())),
1161 getContext().VoidPtrTy);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001162 }
1163 }
John McCallfc207f22013-03-07 21:37:12 +00001164 // order is always the last parameter
1165 Args.add(RValue::get(Order),
1166 getContext().IntTy);
Yaxun Liu39195062017-08-04 18:16:31 +00001167 if (E->isOpenCL())
1168 Args.add(RValue::get(Scope), getContext().IntTy);
John McCallfc207f22013-03-07 21:37:12 +00001169
James Y Knight7aefb5b2015-11-12 18:37:29 +00001170 // PostOp is only needed for the atomic_*_fetch operations, and
1171 // thus is only needed for and implemented in the
1172 // UseOptimizedLibcall codepath.
1173 assert(UseOptimizedLibcall || !PostOp);
1174
David Majnemer659be552014-11-25 23:44:32 +00001175 RValue Res = emitAtomicLibcall(*this, LibCallName, RetTy, Args);
1176 // The value is returned directly from the libcall.
Tim Northovercc2a6e02015-11-09 19:56:35 +00001177 if (E->isCmpXChg())
David Majnemer659be552014-11-25 23:44:32 +00001178 return Res;
Tim Northovercc2a6e02015-11-09 19:56:35 +00001179
1180 // The value is returned directly for optimized libcalls but the expr
1181 // provided an out-param.
1182 if (UseOptimizedLibcall && Res.getScalarVal()) {
David Majnemer659be552014-11-25 23:44:32 +00001183 llvm::Value *ResVal = Res.getScalarVal();
James Y Knight7aefb5b2015-11-12 18:37:29 +00001184 if (PostOp) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00001185 llvm::Value *LoadVal1 = Args[1].getRValue(*this).getScalarVal();
James Y Knight7aefb5b2015-11-12 18:37:29 +00001186 ResVal = Builder.CreateBinOp(PostOp, ResVal, LoadVal1);
1187 }
1188 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
1189 ResVal = Builder.CreateNot(ResVal);
1190
Tim Northovercc2a6e02015-11-09 19:56:35 +00001191 Builder.CreateStore(
1192 ResVal,
1193 Builder.CreateBitCast(Dest, ResVal->getType()->getPointerTo()));
David Majnemer659be552014-11-25 23:44:32 +00001194 }
Tim Northovercc2a6e02015-11-09 19:56:35 +00001195
1196 if (RValTy->isVoidType())
1197 return RValue::get(nullptr);
1198
1199 return convertTempToRValue(
1200 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo()),
1201 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001202 }
1203
1204 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
Yaxun Liu39195062017-08-04 18:16:31 +00001205 E->getOp() == AtomicExpr::AO__opencl_atomic_store ||
John McCallfc207f22013-03-07 21:37:12 +00001206 E->getOp() == AtomicExpr::AO__atomic_store ||
1207 E->getOp() == AtomicExpr::AO__atomic_store_n;
1208 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00001209 E->getOp() == AtomicExpr::AO__opencl_atomic_load ||
John McCallfc207f22013-03-07 21:37:12 +00001210 E->getOp() == AtomicExpr::AO__atomic_load ||
1211 E->getOp() == AtomicExpr::AO__atomic_load_n;
1212
John McCallfc207f22013-03-07 21:37:12 +00001213 if (isa<llvm::ConstantInt>(Order)) {
JF Bastiendda2cb12016-04-18 18:01:49 +00001214 auto ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
1215 // We should not ever get to a case where the ordering isn't a valid C ABI
1216 // value, but it's hard to enforce that in general.
1217 if (llvm::isValidAtomicOrderingCABI(ord))
1218 switch ((llvm::AtomicOrderingCABI)ord) {
1219 case llvm::AtomicOrderingCABI::relaxed:
1220 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001221 llvm::AtomicOrdering::Monotonic, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001222 break;
1223 case llvm::AtomicOrderingCABI::consume:
1224 case llvm::AtomicOrderingCABI::acquire:
1225 if (IsStore)
1226 break; // Avoid crashing on code with undefined behavior
1227 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001228 llvm::AtomicOrdering::Acquire, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001229 break;
1230 case llvm::AtomicOrderingCABI::release:
1231 if (IsLoad)
1232 break; // Avoid crashing on code with undefined behavior
1233 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001234 llvm::AtomicOrdering::Release, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001235 break;
1236 case llvm::AtomicOrderingCABI::acq_rel:
1237 if (IsLoad || IsStore)
1238 break; // Avoid crashing on code with undefined behavior
1239 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001240 llvm::AtomicOrdering::AcquireRelease, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001241 break;
1242 case llvm::AtomicOrderingCABI::seq_cst:
1243 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001244 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001245 break;
1246 }
David Majnemeree8d04d2014-12-12 08:16:09 +00001247 if (RValTy->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001248 return RValue::get(nullptr);
Tim Northovercc2a6e02015-11-09 19:56:35 +00001249
1250 return convertTempToRValue(
Yaxun Liu8ab5ab02017-10-17 14:19:29 +00001251 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1252 Dest.getAddressSpace())),
Tim Northovercc2a6e02015-11-09 19:56:35 +00001253 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001254 }
1255
1256 // Long case, when Order isn't obviously constant.
1257
1258 // Create all the relevant BB's
Craig Topper8a13c412014-05-21 05:09:00 +00001259 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
1260 *ReleaseBB = nullptr, *AcqRelBB = nullptr,
1261 *SeqCstBB = nullptr;
John McCallfc207f22013-03-07 21:37:12 +00001262 MonotonicBB = createBasicBlock("monotonic", CurFn);
1263 if (!IsStore)
1264 AcquireBB = createBasicBlock("acquire", CurFn);
1265 if (!IsLoad)
1266 ReleaseBB = createBasicBlock("release", CurFn);
1267 if (!IsLoad && !IsStore)
1268 AcqRelBB = createBasicBlock("acqrel", CurFn);
1269 SeqCstBB = createBasicBlock("seqcst", CurFn);
1270 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
1271
1272 // Create the switch for the split
1273 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
1274 // doesn't matter unless someone is crazy enough to use something that
1275 // doesn't fold to a constant for the ordering.
1276 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
1277 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
1278
1279 // Emit all the different atomics
1280 Builder.SetInsertPoint(MonotonicBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001281 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001282 llvm::AtomicOrdering::Monotonic, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001283 Builder.CreateBr(ContBB);
1284 if (!IsStore) {
1285 Builder.SetInsertPoint(AcquireBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001286 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001287 llvm::AtomicOrdering::Acquire, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001288 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001289 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
Tim Northover514fc612014-03-13 19:25:52 +00001290 AcquireBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001291 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
Tim Northover514fc612014-03-13 19:25:52 +00001292 AcquireBB);
John McCallfc207f22013-03-07 21:37:12 +00001293 }
1294 if (!IsLoad) {
1295 Builder.SetInsertPoint(ReleaseBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001296 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001297 llvm::AtomicOrdering::Release, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001298 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001299 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::release),
Tim Northover514fc612014-03-13 19:25:52 +00001300 ReleaseBB);
John McCallfc207f22013-03-07 21:37:12 +00001301 }
1302 if (!IsLoad && !IsStore) {
1303 Builder.SetInsertPoint(AcqRelBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001304 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001305 llvm::AtomicOrdering::AcquireRelease, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001306 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001307 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acq_rel),
Tim Northover514fc612014-03-13 19:25:52 +00001308 AcqRelBB);
John McCallfc207f22013-03-07 21:37:12 +00001309 }
1310 Builder.SetInsertPoint(SeqCstBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001311 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001312 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001313 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001314 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
Tim Northover514fc612014-03-13 19:25:52 +00001315 SeqCstBB);
John McCallfc207f22013-03-07 21:37:12 +00001316
1317 // Cleanup and return
1318 Builder.SetInsertPoint(ContBB);
David Majnemeree8d04d2014-12-12 08:16:09 +00001319 if (RValTy->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001320 return RValue::get(nullptr);
Tim Northovercc2a6e02015-11-09 19:56:35 +00001321
1322 assert(Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits());
1323 return convertTempToRValue(
Yaxun Liu8ab5ab02017-10-17 14:19:29 +00001324 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1325 Dest.getAddressSpace())),
Tim Northovercc2a6e02015-11-09 19:56:35 +00001326 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001327}
John McCalla8ec7eb2013-03-07 21:37:17 +00001328
John McCall7f416cc2015-09-08 08:05:57 +00001329Address AtomicInfo::emitCastToAtomicIntPointer(Address addr) const {
John McCalla8ec7eb2013-03-07 21:37:17 +00001330 unsigned addrspace =
John McCall7f416cc2015-09-08 08:05:57 +00001331 cast<llvm::PointerType>(addr.getPointer()->getType())->getAddressSpace();
John McCalla8ec7eb2013-03-07 21:37:17 +00001332 llvm::IntegerType *ty =
1333 llvm::IntegerType::get(CGF.getLLVMContext(), AtomicSizeInBits);
1334 return CGF.Builder.CreateBitCast(addr, ty->getPointerTo(addrspace));
1335}
1336
Tim Northovercc2a6e02015-11-09 19:56:35 +00001337Address AtomicInfo::convertToAtomicIntPointer(Address Addr) const {
1338 llvm::Type *Ty = Addr.getElementType();
1339 uint64_t SourceSizeInBits = CGF.CGM.getDataLayout().getTypeSizeInBits(Ty);
1340 if (SourceSizeInBits != AtomicSizeInBits) {
1341 Address Tmp = CreateTempAlloca();
1342 CGF.Builder.CreateMemCpy(Tmp, Addr,
1343 std::min(AtomicSizeInBits, SourceSizeInBits) / 8);
1344 Addr = Tmp;
1345 }
1346
1347 return emitCastToAtomicIntPointer(Addr);
1348}
1349
John McCall7f416cc2015-09-08 08:05:57 +00001350RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
1351 AggValueSlot resultSlot,
1352 SourceLocation loc,
1353 bool asValue) const {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001354 if (LVal.isSimple()) {
1355 if (EvaluationKind == TEK_Aggregate)
1356 return resultSlot.asRValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001357
Alexey Bataevb57056f2015-01-22 06:17:56 +00001358 // Drill into the padding structure if we have one.
1359 if (hasPadding())
John McCall7f416cc2015-09-08 08:05:57 +00001360 addr = CGF.Builder.CreateStructGEP(addr, 0, CharUnits());
John McCalla8ec7eb2013-03-07 21:37:17 +00001361
Alexey Bataevb57056f2015-01-22 06:17:56 +00001362 // Otherwise, just convert the temporary to an r-value using the
1363 // normal conversion routine.
1364 return CGF.convertTempToRValue(addr, getValueType(), loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001365 }
John McCall7f416cc2015-09-08 08:05:57 +00001366 if (!asValue)
Alexey Bataevb8329262015-02-27 06:33:30 +00001367 // Get RValue from temp memory as atomic for non-simple lvalues
John McCall7f416cc2015-09-08 08:05:57 +00001368 return RValue::get(CGF.Builder.CreateLoad(addr));
David Blaikie1ed728c2015-04-05 22:45:47 +00001369 if (LVal.isBitField())
John McCall7f416cc2015-09-08 08:05:57 +00001370 return CGF.EmitLoadOfBitfieldLValue(
1371 LValue::MakeBitfield(addr, LVal.getBitFieldInfo(), LVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001372 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001373 if (LVal.isVectorElt())
John McCall7f416cc2015-09-08 08:05:57 +00001374 return CGF.EmitLoadOfLValue(
1375 LValue::MakeVectorElt(addr, LVal.getVectorIdx(), LVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001376 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001377 assert(LVal.isExtVectorElt());
1378 return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
John McCall7f416cc2015-09-08 08:05:57 +00001379 addr, LVal.getExtVectorElts(), LVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001380 LVal.getBaseInfo(), TBAAAccessInfo()));
John McCalla8ec7eb2013-03-07 21:37:17 +00001381}
1382
Alexey Bataevb8329262015-02-27 06:33:30 +00001383RValue AtomicInfo::ConvertIntToValueOrAtomic(llvm::Value *IntVal,
1384 AggValueSlot ResultSlot,
1385 SourceLocation Loc,
1386 bool AsValue) const {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001387 // Try not to in some easy cases.
1388 assert(IntVal->getType()->isIntegerTy() && "Expected integer value");
Alexey Bataevb8329262015-02-27 06:33:30 +00001389 if (getEvaluationKind() == TEK_Scalar &&
1390 (((!LVal.isBitField() ||
1391 LVal.getBitFieldInfo().Size == ValueSizeInBits) &&
1392 !hasPadding()) ||
1393 !AsValue)) {
1394 auto *ValTy = AsValue
1395 ? CGF.ConvertTypeForMem(ValueTy)
John McCall7f416cc2015-09-08 08:05:57 +00001396 : getAtomicAddress().getType()->getPointerElementType();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001397 if (ValTy->isIntegerTy()) {
1398 assert(IntVal->getType() == ValTy && "Different integer types.");
David Majnemereeaec262015-02-14 02:18:14 +00001399 return RValue::get(CGF.EmitFromMemory(IntVal, ValueTy));
Alexey Bataev452d8e12014-12-15 05:25:25 +00001400 } else if (ValTy->isPointerTy())
1401 return RValue::get(CGF.Builder.CreateIntToPtr(IntVal, ValTy));
1402 else if (llvm::CastInst::isBitCastable(IntVal->getType(), ValTy))
1403 return RValue::get(CGF.Builder.CreateBitCast(IntVal, ValTy));
1404 }
1405
1406 // Create a temporary. This needs to be big enough to hold the
1407 // atomic integer.
John McCall7f416cc2015-09-08 08:05:57 +00001408 Address Temp = Address::invalid();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001409 bool TempIsVolatile = false;
Alexey Bataevb8329262015-02-27 06:33:30 +00001410 if (AsValue && getEvaluationKind() == TEK_Aggregate) {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001411 assert(!ResultSlot.isIgnored());
John McCall7f416cc2015-09-08 08:05:57 +00001412 Temp = ResultSlot.getAddress();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001413 TempIsVolatile = ResultSlot.isVolatile();
1414 } else {
Alexey Bataevb8329262015-02-27 06:33:30 +00001415 Temp = CreateTempAlloca();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001416 }
1417
1418 // Slam the integer into the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00001419 Address CastTemp = emitCastToAtomicIntPointer(Temp);
1420 CGF.Builder.CreateStore(IntVal, CastTemp)
Alexey Bataev452d8e12014-12-15 05:25:25 +00001421 ->setVolatile(TempIsVolatile);
1422
John McCall7f416cc2015-09-08 08:05:57 +00001423 return convertAtomicTempToRValue(Temp, ResultSlot, Loc, AsValue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001424}
1425
1426void AtomicInfo::EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
1427 llvm::AtomicOrdering AO, bool) {
1428 // void __atomic_load(size_t size, void *mem, void *return, int order);
1429 CallArgList Args;
1430 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001431 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001432 CGF.getContext().VoidPtrTy);
1433 Args.add(RValue::get(CGF.EmitCastToVoidPtr(AddForLoaded)),
1434 CGF.getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001435 Args.add(
1436 RValue::get(llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(AO))),
1437 CGF.getContext().IntTy);
Alexey Bataevb8329262015-02-27 06:33:30 +00001438 emitAtomicLibcall(CGF, "__atomic_load", CGF.getContext().VoidTy, Args);
1439}
1440
1441llvm::Value *AtomicInfo::EmitAtomicLoadOp(llvm::AtomicOrdering AO,
1442 bool IsVolatile) {
1443 // Okay, we're doing this natively.
John McCall7f416cc2015-09-08 08:05:57 +00001444 Address Addr = getAtomicAddressAsAtomicIntPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +00001445 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Addr, "atomic-load");
1446 Load->setAtomic(AO);
1447
1448 // Other decoration.
Alexey Bataevb8329262015-02-27 06:33:30 +00001449 if (IsVolatile)
1450 Load->setVolatile(true);
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001451 CGF.CGM.DecorateInstructionWithTBAA(Load, LVal.getTBAAInfo());
Alexey Bataevb8329262015-02-27 06:33:30 +00001452 return Load;
Alexey Bataev452d8e12014-12-15 05:25:25 +00001453}
1454
David Majnemera5b195a2015-02-14 01:35:12 +00001455/// An LValue is a candidate for having its loads and stores be made atomic if
1456/// we are operating under /volatile:ms *and* the LValue itself is volatile and
1457/// performing such an operation can be performed without a libcall.
1458bool CodeGenFunction::LValueIsSuitableForInlineAtomic(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001459 if (!CGM.getCodeGenOpts().MSVolatile) return false;
David Majnemera5b195a2015-02-14 01:35:12 +00001460 AtomicInfo AI(*this, LV);
1461 bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
1462 // An atomic is inline if we don't need to use a libcall.
1463 bool AtomicIsInline = !AI.shouldUseLibcall();
David Majnemerfc80b6e2016-01-22 16:36:44 +00001464 // MSVC doesn't seem to do this for types wider than a pointer.
David Majnemera38c9f12016-05-24 16:09:25 +00001465 if (getContext().getTypeSize(LV.getType()) >
David Majnemerfc80b6e2016-01-22 16:36:44 +00001466 getContext().getTypeSize(getContext().getIntPtrType()))
1467 return false;
David Majnemera38c9f12016-05-24 16:09:25 +00001468 return IsVolatile && AtomicIsInline;
David Majnemera5b195a2015-02-14 01:35:12 +00001469}
1470
1471RValue CodeGenFunction::EmitAtomicLoad(LValue LV, SourceLocation SL,
1472 AggValueSlot Slot) {
1473 llvm::AtomicOrdering AO;
1474 bool IsVolatile = LV.isVolatileQualified();
1475 if (LV.getType()->isAtomicType()) {
JF Bastien92f4ef12016-04-06 17:26:42 +00001476 AO = llvm::AtomicOrdering::SequentiallyConsistent;
David Majnemera5b195a2015-02-14 01:35:12 +00001477 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00001478 AO = llvm::AtomicOrdering::Acquire;
David Majnemera5b195a2015-02-14 01:35:12 +00001479 IsVolatile = true;
1480 }
1481 return EmitAtomicLoad(LV, SL, AO, IsVolatile, Slot);
1482}
1483
Alexey Bataevb8329262015-02-27 06:33:30 +00001484RValue AtomicInfo::EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
1485 bool AsValue, llvm::AtomicOrdering AO,
1486 bool IsVolatile) {
1487 // Check whether we should use a library call.
1488 if (shouldUseLibcall()) {
John McCall7f416cc2015-09-08 08:05:57 +00001489 Address TempAddr = Address::invalid();
Alexey Bataevb8329262015-02-27 06:33:30 +00001490 if (LVal.isSimple() && !ResultSlot.isIgnored()) {
1491 assert(getEvaluationKind() == TEK_Aggregate);
John McCall7f416cc2015-09-08 08:05:57 +00001492 TempAddr = ResultSlot.getAddress();
Alexey Bataevb8329262015-02-27 06:33:30 +00001493 } else
1494 TempAddr = CreateTempAlloca();
1495
John McCall7f416cc2015-09-08 08:05:57 +00001496 EmitAtomicLoadLibcall(TempAddr.getPointer(), AO, IsVolatile);
Alexey Bataevb8329262015-02-27 06:33:30 +00001497
1498 // Okay, turn that back into the original value or whole atomic (for
1499 // non-simple lvalues) type.
John McCall7f416cc2015-09-08 08:05:57 +00001500 return convertAtomicTempToRValue(TempAddr, ResultSlot, Loc, AsValue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001501 }
1502
1503 // Okay, we're doing this natively.
1504 auto *Load = EmitAtomicLoadOp(AO, IsVolatile);
1505
1506 // If we're ignoring an aggregate return, don't do anything.
1507 if (getEvaluationKind() == TEK_Aggregate && ResultSlot.isIgnored())
John McCall7f416cc2015-09-08 08:05:57 +00001508 return RValue::getAggregate(Address::invalid(), false);
Alexey Bataevb8329262015-02-27 06:33:30 +00001509
1510 // Okay, turn that back into the original value or atomic (for non-simple
1511 // lvalues) type.
1512 return ConvertIntToValueOrAtomic(Load, ResultSlot, Loc, AsValue);
1513}
1514
John McCalla8ec7eb2013-03-07 21:37:17 +00001515/// Emit a load from an l-value of atomic type. Note that the r-value
1516/// we produce is an r-value of the atomic *value* type.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001517RValue CodeGenFunction::EmitAtomicLoad(LValue src, SourceLocation loc,
David Majnemera5b195a2015-02-14 01:35:12 +00001518 llvm::AtomicOrdering AO, bool IsVolatile,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001519 AggValueSlot resultSlot) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001520 AtomicInfo Atomics(*this, src);
1521 return Atomics.EmitAtomicLoad(resultSlot, loc, /*AsValue=*/true, AO,
1522 IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001523}
1524
John McCalla8ec7eb2013-03-07 21:37:17 +00001525/// Copy an r-value into memory as part of storing to an atomic type.
1526/// This needs to create a bit-pattern suitable for atomic operations.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001527void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
1528 assert(LVal.isSimple());
John McCalla8ec7eb2013-03-07 21:37:17 +00001529 // If we have an r-value, the rvalue should be of the atomic type,
1530 // which means that the caller is responsible for having zeroed
1531 // any padding. Just do an aggregate copy of that type.
1532 if (rvalue.isAggregate()) {
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001533 LValue Dest = CGF.MakeAddrLValue(getAtomicAddress(), getAtomicType());
1534 LValue Src = CGF.MakeAddrLValue(rvalue.getAggregateAddress(),
1535 getAtomicType());
1536 bool IsVolatile = rvalue.isVolatileQualified() ||
1537 LVal.isVolatileQualified();
Richard Smithe78fac52018-04-05 20:52:58 +00001538 CGF.EmitAggregateCopy(Dest, Src, getAtomicType(),
1539 AggValueSlot::DoesNotOverlap, IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001540 return;
1541 }
1542
1543 // Okay, otherwise we're copying stuff.
1544
1545 // Zero out the buffer if necessary.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001546 emitMemSetZeroIfNecessary();
John McCalla8ec7eb2013-03-07 21:37:17 +00001547
1548 // Drill past the padding if present.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001549 LValue TempLVal = projectValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001550
1551 // Okay, store the rvalue in.
1552 if (rvalue.isScalar()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001553 CGF.EmitStoreOfScalar(rvalue.getScalarVal(), TempLVal, /*init*/ true);
John McCalla8ec7eb2013-03-07 21:37:17 +00001554 } else {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001555 CGF.EmitStoreOfComplex(rvalue.getComplexVal(), TempLVal, /*init*/ true);
John McCalla8ec7eb2013-03-07 21:37:17 +00001556 }
1557}
1558
1559
1560/// Materialize an r-value into memory for the purposes of storing it
1561/// to an atomic type.
John McCall7f416cc2015-09-08 08:05:57 +00001562Address AtomicInfo::materializeRValue(RValue rvalue) const {
John McCalla8ec7eb2013-03-07 21:37:17 +00001563 // Aggregate r-values are already in memory, and EmitAtomicStore
1564 // requires them to be values of the atomic type.
1565 if (rvalue.isAggregate())
John McCall7f416cc2015-09-08 08:05:57 +00001566 return rvalue.getAggregateAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +00001567
1568 // Otherwise, make a temporary and materialize into it.
John McCall7f416cc2015-09-08 08:05:57 +00001569 LValue TempLV = CGF.MakeAddrLValue(CreateTempAlloca(), getAtomicType());
Alexey Bataevb8329262015-02-27 06:33:30 +00001570 AtomicInfo Atomics(CGF, TempLV);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001571 Atomics.emitCopyIntoMemory(rvalue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001572 return TempLV.getAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +00001573}
1574
Alexey Bataev452d8e12014-12-15 05:25:25 +00001575llvm::Value *AtomicInfo::convertRValueToInt(RValue RVal) const {
1576 // If we've got a scalar value of the right size, try to avoid going
1577 // through memory.
Alexey Bataevb8329262015-02-27 06:33:30 +00001578 if (RVal.isScalar() && (!hasPadding() || !LVal.isSimple())) {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001579 llvm::Value *Value = RVal.getScalarVal();
1580 if (isa<llvm::IntegerType>(Value->getType()))
Alexey Bataevb4505a72015-03-30 05:20:59 +00001581 return CGF.EmitToMemory(Value, ValueTy);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001582 else {
Alexey Bataevb8329262015-02-27 06:33:30 +00001583 llvm::IntegerType *InputIntTy = llvm::IntegerType::get(
1584 CGF.getLLVMContext(),
1585 LVal.isSimple() ? getValueSizeInBits() : getAtomicSizeInBits());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001586 if (isa<llvm::PointerType>(Value->getType()))
1587 return CGF.Builder.CreatePtrToInt(Value, InputIntTy);
1588 else if (llvm::BitCastInst::isBitCastable(Value->getType(), InputIntTy))
1589 return CGF.Builder.CreateBitCast(Value, InputIntTy);
1590 }
1591 }
1592 // Otherwise, we need to go through memory.
1593 // Put the r-value in memory.
John McCall7f416cc2015-09-08 08:05:57 +00001594 Address Addr = materializeRValue(RVal);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001595
1596 // Cast the temporary to the atomic int type and pull a value out.
1597 Addr = emitCastToAtomicIntPointer(Addr);
John McCall7f416cc2015-09-08 08:05:57 +00001598 return CGF.Builder.CreateLoad(Addr);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001599}
1600
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001601std::pair<llvm::Value *, llvm::Value *> AtomicInfo::EmitAtomicCompareExchangeOp(
1602 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
1603 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001604 // Do the atomic store.
John McCall7f416cc2015-09-08 08:05:57 +00001605 Address Addr = getAtomicAddressAsAtomicIntPointer();
1606 auto *Inst = CGF.Builder.CreateAtomicCmpXchg(Addr.getPointer(),
1607 ExpectedVal, DesiredVal,
Alexey Bataevb4505a72015-03-30 05:20:59 +00001608 Success, Failure);
Alexey Bataevb8329262015-02-27 06:33:30 +00001609 // Other decoration.
1610 Inst->setVolatile(LVal.isVolatileQualified());
1611 Inst->setWeak(IsWeak);
1612
1613 // Okay, turn that back into the original value type.
1614 auto *PreviousVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/0);
1615 auto *SuccessFailureVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/1);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001616 return std::make_pair(PreviousVal, SuccessFailureVal);
Alexey Bataevb8329262015-02-27 06:33:30 +00001617}
1618
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001619llvm::Value *
1620AtomicInfo::EmitAtomicCompareExchangeLibcall(llvm::Value *ExpectedAddr,
1621 llvm::Value *DesiredAddr,
Alexey Bataevb8329262015-02-27 06:33:30 +00001622 llvm::AtomicOrdering Success,
1623 llvm::AtomicOrdering Failure) {
1624 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
1625 // void *desired, int success, int failure);
1626 CallArgList Args;
1627 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001628 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001629 CGF.getContext().VoidPtrTy);
1630 Args.add(RValue::get(CGF.EmitCastToVoidPtr(ExpectedAddr)),
1631 CGF.getContext().VoidPtrTy);
1632 Args.add(RValue::get(CGF.EmitCastToVoidPtr(DesiredAddr)),
1633 CGF.getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001634 Args.add(RValue::get(
1635 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Success))),
Alexey Bataevb8329262015-02-27 06:33:30 +00001636 CGF.getContext().IntTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001637 Args.add(RValue::get(
1638 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Failure))),
Alexey Bataevb8329262015-02-27 06:33:30 +00001639 CGF.getContext().IntTy);
1640 auto SuccessFailureRVal = emitAtomicLibcall(CGF, "__atomic_compare_exchange",
1641 CGF.getContext().BoolTy, Args);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001642
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001643 return SuccessFailureRVal.getScalarVal();
Alexey Bataevb8329262015-02-27 06:33:30 +00001644}
1645
Alexey Bataevb4505a72015-03-30 05:20:59 +00001646std::pair<RValue, llvm::Value *> AtomicInfo::EmitAtomicCompareExchange(
Alexey Bataevb8329262015-02-27 06:33:30 +00001647 RValue Expected, RValue Desired, llvm::AtomicOrdering Success,
1648 llvm::AtomicOrdering Failure, bool IsWeak) {
JF Bastiendd11ee72016-04-06 23:37:36 +00001649 if (isStrongerThan(Failure, Success))
1650 // Don't assert on undefined behavior "failure argument shall be no stronger
1651 // than the success argument".
Alexey Bataevb8329262015-02-27 06:33:30 +00001652 Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(Success);
1653
1654 // Check whether we should use a library call.
1655 if (shouldUseLibcall()) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001656 // Produce a source address.
John McCall7f416cc2015-09-08 08:05:57 +00001657 Address ExpectedAddr = materializeRValue(Expected);
1658 Address DesiredAddr = materializeRValue(Desired);
1659 auto *Res = EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1660 DesiredAddr.getPointer(),
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001661 Success, Failure);
1662 return std::make_pair(
John McCall7f416cc2015-09-08 08:05:57 +00001663 convertAtomicTempToRValue(ExpectedAddr, AggValueSlot::ignored(),
1664 SourceLocation(), /*AsValue=*/false),
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001665 Res);
Alexey Bataevb8329262015-02-27 06:33:30 +00001666 }
1667
1668 // If we've got a scalar value of the right size, try to avoid going
1669 // through memory.
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001670 auto *ExpectedVal = convertRValueToInt(Expected);
1671 auto *DesiredVal = convertRValueToInt(Desired);
1672 auto Res = EmitAtomicCompareExchangeOp(ExpectedVal, DesiredVal, Success,
1673 Failure, IsWeak);
1674 return std::make_pair(
1675 ConvertIntToValueOrAtomic(Res.first, AggValueSlot::ignored(),
1676 SourceLocation(), /*AsValue=*/false),
1677 Res.second);
1678}
1679
1680static void
1681EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal,
1682 const llvm::function_ref<RValue(RValue)> &UpdateOp,
John McCall7f416cc2015-09-08 08:05:57 +00001683 Address DesiredAddr) {
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001684 RValue UpRVal;
1685 LValue AtomicLVal = Atomics.getAtomicLValue();
1686 LValue DesiredLVal;
1687 if (AtomicLVal.isSimple()) {
1688 UpRVal = OldRVal;
John McCall7f416cc2015-09-08 08:05:57 +00001689 DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001690 } else {
1691 // Build new lvalue for temp address
John McCall7f416cc2015-09-08 08:05:57 +00001692 Address Ptr = Atomics.materializeRValue(OldRVal);
1693 LValue UpdateLVal;
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001694 if (AtomicLVal.isBitField()) {
1695 UpdateLVal =
1696 LValue::MakeBitfield(Ptr, AtomicLVal.getBitFieldInfo(),
John McCall7f416cc2015-09-08 08:05:57 +00001697 AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001698 AtomicLVal.getBaseInfo(),
1699 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001700 DesiredLVal =
1701 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001702 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1703 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001704 } else if (AtomicLVal.isVectorElt()) {
1705 UpdateLVal = LValue::MakeVectorElt(Ptr, AtomicLVal.getVectorIdx(),
1706 AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001707 AtomicLVal.getBaseInfo(),
1708 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001709 DesiredLVal = LValue::MakeVectorElt(
1710 DesiredAddr, AtomicLVal.getVectorIdx(), AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001711 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001712 } else {
1713 assert(AtomicLVal.isExtVectorElt());
1714 UpdateLVal = LValue::MakeExtVectorElt(Ptr, AtomicLVal.getExtVectorElts(),
1715 AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001716 AtomicLVal.getBaseInfo(),
1717 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001718 DesiredLVal = LValue::MakeExtVectorElt(
1719 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001720 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001721 }
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001722 UpRVal = CGF.EmitLoadOfLValue(UpdateLVal, SourceLocation());
1723 }
1724 // Store new value in the corresponding memory area
1725 RValue NewRVal = UpdateOp(UpRVal);
1726 if (NewRVal.isScalar()) {
1727 CGF.EmitStoreThroughLValue(NewRVal, DesiredLVal);
1728 } else {
1729 assert(NewRVal.isComplex());
1730 CGF.EmitStoreOfComplex(NewRVal.getComplexVal(), DesiredLVal,
1731 /*isInit=*/false);
1732 }
1733}
1734
1735void AtomicInfo::EmitAtomicUpdateLibcall(
1736 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1737 bool IsVolatile) {
1738 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1739
John McCall7f416cc2015-09-08 08:05:57 +00001740 Address ExpectedAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001741
John McCall7f416cc2015-09-08 08:05:57 +00001742 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001743 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1744 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1745 CGF.EmitBlock(ContBB);
John McCall7f416cc2015-09-08 08:05:57 +00001746 Address DesiredAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001747 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001748 requiresMemSetZero(getAtomicAddress().getElementType())) {
1749 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1750 CGF.Builder.CreateStore(OldVal, DesiredAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001751 }
John McCall7f416cc2015-09-08 08:05:57 +00001752 auto OldRVal = convertAtomicTempToRValue(ExpectedAddr,
1753 AggValueSlot::ignored(),
1754 SourceLocation(), /*AsValue=*/false);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001755 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, DesiredAddr);
1756 auto *Res =
John McCall7f416cc2015-09-08 08:05:57 +00001757 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1758 DesiredAddr.getPointer(),
1759 AO, Failure);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001760 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1761 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1762}
1763
1764void AtomicInfo::EmitAtomicUpdateOp(
1765 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1766 bool IsVolatile) {
1767 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1768
1769 // Do the atomic load.
1770 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1771 // For non-simple lvalues perform compare-and-swap procedure.
1772 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1773 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1774 auto *CurBB = CGF.Builder.GetInsertBlock();
1775 CGF.EmitBlock(ContBB);
1776 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1777 /*NumReservedValues=*/2);
1778 PHI->addIncoming(OldVal, CurBB);
John McCall7f416cc2015-09-08 08:05:57 +00001779 Address NewAtomicAddr = CreateTempAlloca();
1780 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001781 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001782 requiresMemSetZero(getAtomicAddress().getElementType())) {
1783 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001784 }
1785 auto OldRVal = ConvertIntToValueOrAtomic(PHI, AggValueSlot::ignored(),
1786 SourceLocation(), /*AsValue=*/false);
1787 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, NewAtomicAddr);
John McCall7f416cc2015-09-08 08:05:57 +00001788 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001789 // Try to write new value using cmpxchg operation
1790 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1791 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1792 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1793 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1794}
1795
1796static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics,
John McCall7f416cc2015-09-08 08:05:57 +00001797 RValue UpdateRVal, Address DesiredAddr) {
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001798 LValue AtomicLVal = Atomics.getAtomicLValue();
1799 LValue DesiredLVal;
1800 // Build new lvalue for temp address
1801 if (AtomicLVal.isBitField()) {
1802 DesiredLVal =
1803 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001804 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1805 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001806 } else if (AtomicLVal.isVectorElt()) {
1807 DesiredLVal =
1808 LValue::MakeVectorElt(DesiredAddr, AtomicLVal.getVectorIdx(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001809 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1810 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001811 } else {
1812 assert(AtomicLVal.isExtVectorElt());
1813 DesiredLVal = LValue::MakeExtVectorElt(
1814 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001815 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001816 }
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001817 // Store new value in the corresponding memory area
1818 assert(UpdateRVal.isScalar());
1819 CGF.EmitStoreThroughLValue(UpdateRVal, DesiredLVal);
1820}
1821
1822void AtomicInfo::EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
1823 RValue UpdateRVal, bool IsVolatile) {
1824 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1825
John McCall7f416cc2015-09-08 08:05:57 +00001826 Address ExpectedAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001827
John McCall7f416cc2015-09-08 08:05:57 +00001828 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001829 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1830 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1831 CGF.EmitBlock(ContBB);
John McCall7f416cc2015-09-08 08:05:57 +00001832 Address DesiredAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001833 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001834 requiresMemSetZero(getAtomicAddress().getElementType())) {
1835 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1836 CGF.Builder.CreateStore(OldVal, DesiredAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001837 }
1838 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, DesiredAddr);
1839 auto *Res =
John McCall7f416cc2015-09-08 08:05:57 +00001840 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1841 DesiredAddr.getPointer(),
1842 AO, Failure);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001843 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1844 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1845}
1846
1847void AtomicInfo::EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRVal,
1848 bool IsVolatile) {
1849 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1850
1851 // Do the atomic load.
1852 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1853 // For non-simple lvalues perform compare-and-swap procedure.
1854 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1855 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1856 auto *CurBB = CGF.Builder.GetInsertBlock();
1857 CGF.EmitBlock(ContBB);
1858 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1859 /*NumReservedValues=*/2);
1860 PHI->addIncoming(OldVal, CurBB);
John McCall7f416cc2015-09-08 08:05:57 +00001861 Address NewAtomicAddr = CreateTempAlloca();
1862 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001863 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001864 requiresMemSetZero(getAtomicAddress().getElementType())) {
1865 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001866 }
1867 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, NewAtomicAddr);
John McCall7f416cc2015-09-08 08:05:57 +00001868 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001869 // Try to write new value using cmpxchg operation
1870 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1871 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1872 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1873 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1874}
1875
1876void AtomicInfo::EmitAtomicUpdate(
1877 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1878 bool IsVolatile) {
1879 if (shouldUseLibcall()) {
1880 EmitAtomicUpdateLibcall(AO, UpdateOp, IsVolatile);
1881 } else {
1882 EmitAtomicUpdateOp(AO, UpdateOp, IsVolatile);
1883 }
1884}
1885
1886void AtomicInfo::EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
1887 bool IsVolatile) {
1888 if (shouldUseLibcall()) {
1889 EmitAtomicUpdateLibcall(AO, UpdateRVal, IsVolatile);
1890 } else {
1891 EmitAtomicUpdateOp(AO, UpdateRVal, IsVolatile);
1892 }
Alexey Bataevb8329262015-02-27 06:33:30 +00001893}
1894
David Majnemera5b195a2015-02-14 01:35:12 +00001895void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue lvalue,
1896 bool isInit) {
1897 bool IsVolatile = lvalue.isVolatileQualified();
1898 llvm::AtomicOrdering AO;
1899 if (lvalue.getType()->isAtomicType()) {
JF Bastien92f4ef12016-04-06 17:26:42 +00001900 AO = llvm::AtomicOrdering::SequentiallyConsistent;
David Majnemera5b195a2015-02-14 01:35:12 +00001901 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00001902 AO = llvm::AtomicOrdering::Release;
David Majnemera5b195a2015-02-14 01:35:12 +00001903 IsVolatile = true;
1904 }
1905 return EmitAtomicStore(rvalue, lvalue, AO, IsVolatile, isInit);
1906}
1907
John McCalla8ec7eb2013-03-07 21:37:17 +00001908/// Emit a store to an l-value of atomic type.
1909///
1910/// Note that the r-value is expected to be an r-value *of the atomic
1911/// type*; this means that for aggregate r-values, it should include
1912/// storage for any padding that was necessary.
David Majnemera5b195a2015-02-14 01:35:12 +00001913void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue dest,
1914 llvm::AtomicOrdering AO, bool IsVolatile,
1915 bool isInit) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001916 // If this is an aggregate r-value, it should agree in type except
1917 // maybe for address-space qualification.
1918 assert(!rvalue.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001919 rvalue.getAggregateAddress().getElementType()
1920 == dest.getAddress().getElementType());
John McCalla8ec7eb2013-03-07 21:37:17 +00001921
1922 AtomicInfo atomics(*this, dest);
Alexey Bataevb8329262015-02-27 06:33:30 +00001923 LValue LVal = atomics.getAtomicLValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001924
1925 // If this is an initialization, just put the value there normally.
Alexey Bataevb8329262015-02-27 06:33:30 +00001926 if (LVal.isSimple()) {
1927 if (isInit) {
1928 atomics.emitCopyIntoMemory(rvalue);
1929 return;
1930 }
1931
1932 // Check whether we should use a library call.
1933 if (atomics.shouldUseLibcall()) {
1934 // Produce a source address.
John McCall7f416cc2015-09-08 08:05:57 +00001935 Address srcAddr = atomics.materializeRValue(rvalue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001936
1937 // void __atomic_store(size_t size, void *mem, void *val, int order)
1938 CallArgList args;
1939 args.add(RValue::get(atomics.getAtomicSizeValue()),
1940 getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001941 args.add(RValue::get(EmitCastToVoidPtr(atomics.getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001942 getContext().VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001943 args.add(RValue::get(EmitCastToVoidPtr(srcAddr.getPointer())),
1944 getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001945 args.add(
1946 RValue::get(llvm::ConstantInt::get(IntTy, (int)llvm::toCABI(AO))),
1947 getContext().IntTy);
Alexey Bataevb8329262015-02-27 06:33:30 +00001948 emitAtomicLibcall(*this, "__atomic_store", getContext().VoidTy, args);
1949 return;
1950 }
1951
1952 // Okay, we're doing this natively.
1953 llvm::Value *intValue = atomics.convertRValueToInt(rvalue);
1954
1955 // Do the atomic store.
John McCall7f416cc2015-09-08 08:05:57 +00001956 Address addr =
Alexey Bataevb8329262015-02-27 06:33:30 +00001957 atomics.emitCastToAtomicIntPointer(atomics.getAtomicAddress());
1958 intValue = Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00001959 intValue, addr.getElementType(), /*isSigned=*/false);
Alexey Bataevb8329262015-02-27 06:33:30 +00001960 llvm::StoreInst *store = Builder.CreateStore(intValue, addr);
1961
1962 // Initializations don't need to be atomic.
1963 if (!isInit)
1964 store->setAtomic(AO);
1965
1966 // Other decoration.
Alexey Bataevb8329262015-02-27 06:33:30 +00001967 if (IsVolatile)
1968 store->setVolatile(true);
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001969 CGM.DecorateInstructionWithTBAA(store, dest.getTBAAInfo());
John McCalla8ec7eb2013-03-07 21:37:17 +00001970 return;
1971 }
1972
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001973 // Emit simple atomic update operation.
1974 atomics.EmitAtomicUpdate(AO, rvalue, IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001975}
1976
Alexey Bataev452d8e12014-12-15 05:25:25 +00001977/// Emit a compare-and-exchange op for atomic type.
1978///
Alexey Bataevb4505a72015-03-30 05:20:59 +00001979std::pair<RValue, llvm::Value *> CodeGenFunction::EmitAtomicCompareExchange(
Alexey Bataev452d8e12014-12-15 05:25:25 +00001980 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
1981 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak,
1982 AggValueSlot Slot) {
1983 // If this is an aggregate r-value, it should agree in type except
1984 // maybe for address-space qualification.
1985 assert(!Expected.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001986 Expected.getAggregateAddress().getElementType() ==
1987 Obj.getAddress().getElementType());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001988 assert(!Desired.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001989 Desired.getAggregateAddress().getElementType() ==
1990 Obj.getAddress().getElementType());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001991 AtomicInfo Atomics(*this, Obj);
1992
Alexey Bataevb4505a72015-03-30 05:20:59 +00001993 return Atomics.EmitAtomicCompareExchange(Expected, Desired, Success, Failure,
1994 IsWeak);
1995}
1996
1997void CodeGenFunction::EmitAtomicUpdate(
1998 LValue LVal, llvm::AtomicOrdering AO,
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001999 const llvm::function_ref<RValue(RValue)> &UpdateOp, bool IsVolatile) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00002000 AtomicInfo Atomics(*this, LVal);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00002001 Atomics.EmitAtomicUpdate(AO, UpdateOp, IsVolatile);
Alexey Bataev452d8e12014-12-15 05:25:25 +00002002}
2003
John McCalla8ec7eb2013-03-07 21:37:17 +00002004void CodeGenFunction::EmitAtomicInit(Expr *init, LValue dest) {
2005 AtomicInfo atomics(*this, dest);
2006
2007 switch (atomics.getEvaluationKind()) {
2008 case TEK_Scalar: {
2009 llvm::Value *value = EmitScalarExpr(init);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002010 atomics.emitCopyIntoMemory(RValue::get(value));
John McCalla8ec7eb2013-03-07 21:37:17 +00002011 return;
2012 }
2013
2014 case TEK_Complex: {
2015 ComplexPairTy value = EmitComplexExpr(init);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002016 atomics.emitCopyIntoMemory(RValue::getComplex(value));
John McCalla8ec7eb2013-03-07 21:37:17 +00002017 return;
2018 }
2019
2020 case TEK_Aggregate: {
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002021 // Fix up the destination if the initializer isn't an expression
2022 // of atomic type.
2023 bool Zeroed = false;
John McCalla8ec7eb2013-03-07 21:37:17 +00002024 if (!init->getType()->isAtomicType()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002025 Zeroed = atomics.emitMemSetZeroIfNecessary();
2026 dest = atomics.projectValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00002027 }
2028
2029 // Evaluate the expression directly into the destination.
2030 AggValueSlot slot = AggValueSlot::forLValue(dest,
2031 AggValueSlot::IsNotDestructed,
2032 AggValueSlot::DoesNotNeedGCBarriers,
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002033 AggValueSlot::IsNotAliased,
Richard Smithe78fac52018-04-05 20:52:58 +00002034 AggValueSlot::DoesNotOverlap,
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002035 Zeroed ? AggValueSlot::IsZeroed :
2036 AggValueSlot::IsNotZeroed);
2037
John McCalla8ec7eb2013-03-07 21:37:17 +00002038 EmitAggExpr(init, slot);
2039 return;
2040 }
2041 }
2042 llvm_unreachable("bad evaluation kind");
2043}