blob: 149982d827908402d64f9866a2bf1f40d0e39c14 [file] [log] [blame]
John McCallfc207f22013-03-07 21:37:12 +00001//===--- CGAtomic.cpp - Emit LLVM IR for atomic operations ----------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
John McCallfc207f22013-03-07 21:37:12 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the code for emitting atomic operations.
10//
11//===----------------------------------------------------------------------===//
12
John McCallfc207f22013-03-07 21:37:12 +000013#include "CGCall.h"
Alexey Bataevb57056f2015-01-22 06:17:56 +000014#include "CGRecordLayout.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000015#include "CodeGenFunction.h"
John McCallfc207f22013-03-07 21:37:12 +000016#include "CodeGenModule.h"
Yaxun Liu39195062017-08-04 18:16:31 +000017#include "TargetInfo.h"
John McCallfc207f22013-03-07 21:37:12 +000018#include "clang/AST/ASTContext.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Richard Trieu5337c742018-12-06 06:12:20 +000020#include "clang/Frontend/FrontendDiagnostic.h"
Yaxun Liu30d652a2017-08-15 16:02:49 +000021#include "llvm/ADT/DenseMap.h"
John McCallfc207f22013-03-07 21:37:12 +000022#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Intrinsics.h"
John McCalla8ec7eb2013-03-07 21:37:17 +000024#include "llvm/IR/Operator.h"
John McCallfc207f22013-03-07 21:37:12 +000025
26using namespace clang;
27using namespace CodeGen;
28
John McCalla8ec7eb2013-03-07 21:37:17 +000029namespace {
30 class AtomicInfo {
31 CodeGenFunction &CGF;
32 QualType AtomicTy;
33 QualType ValueTy;
34 uint64_t AtomicSizeInBits;
35 uint64_t ValueSizeInBits;
36 CharUnits AtomicAlign;
37 CharUnits ValueAlign;
John McCalla8ec7eb2013-03-07 21:37:17 +000038 TypeEvaluationKind EvaluationKind;
39 bool UseLibcall;
Alexey Bataevb57056f2015-01-22 06:17:56 +000040 LValue LVal;
41 CGBitFieldInfo BFI;
John McCalla8ec7eb2013-03-07 21:37:17 +000042 public:
Alexey Bataevb57056f2015-01-22 06:17:56 +000043 AtomicInfo(CodeGenFunction &CGF, LValue &lvalue)
44 : CGF(CGF), AtomicSizeInBits(0), ValueSizeInBits(0),
45 EvaluationKind(TEK_Scalar), UseLibcall(true) {
46 assert(!lvalue.isGlobalReg());
John McCalla8ec7eb2013-03-07 21:37:17 +000047 ASTContext &C = CGF.getContext();
Alexey Bataevb57056f2015-01-22 06:17:56 +000048 if (lvalue.isSimple()) {
49 AtomicTy = lvalue.getType();
50 if (auto *ATy = AtomicTy->getAs<AtomicType>())
51 ValueTy = ATy->getValueType();
52 else
53 ValueTy = AtomicTy;
54 EvaluationKind = CGF.getEvaluationKind(ValueTy);
John McCalla8ec7eb2013-03-07 21:37:17 +000055
Alexey Bataevb57056f2015-01-22 06:17:56 +000056 uint64_t ValueAlignInBits;
57 uint64_t AtomicAlignInBits;
58 TypeInfo ValueTI = C.getTypeInfo(ValueTy);
59 ValueSizeInBits = ValueTI.Width;
60 ValueAlignInBits = ValueTI.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +000061
Alexey Bataevb57056f2015-01-22 06:17:56 +000062 TypeInfo AtomicTI = C.getTypeInfo(AtomicTy);
63 AtomicSizeInBits = AtomicTI.Width;
64 AtomicAlignInBits = AtomicTI.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +000065
Alexey Bataevb57056f2015-01-22 06:17:56 +000066 assert(ValueSizeInBits <= AtomicSizeInBits);
67 assert(ValueAlignInBits <= AtomicAlignInBits);
John McCalla8ec7eb2013-03-07 21:37:17 +000068
Alexey Bataevb57056f2015-01-22 06:17:56 +000069 AtomicAlign = C.toCharUnitsFromBits(AtomicAlignInBits);
70 ValueAlign = C.toCharUnitsFromBits(ValueAlignInBits);
71 if (lvalue.getAlignment().isZero())
72 lvalue.setAlignment(AtomicAlign);
John McCalla8ec7eb2013-03-07 21:37:17 +000073
Alexey Bataevb57056f2015-01-22 06:17:56 +000074 LVal = lvalue;
75 } else if (lvalue.isBitField()) {
Alexey Bataevb8329262015-02-27 06:33:30 +000076 ValueTy = lvalue.getType();
77 ValueSizeInBits = C.getTypeSize(ValueTy);
Alexey Bataevb57056f2015-01-22 06:17:56 +000078 auto &OrigBFI = lvalue.getBitFieldInfo();
79 auto Offset = OrigBFI.Offset % C.toBits(lvalue.getAlignment());
80 AtomicSizeInBits = C.toBits(
81 C.toCharUnitsFromBits(Offset + OrigBFI.Size + C.getCharWidth() - 1)
Rui Ueyama83aa9792016-01-14 21:00:27 +000082 .alignTo(lvalue.getAlignment()));
John McCall7f416cc2015-09-08 08:05:57 +000083 auto VoidPtrAddr = CGF.EmitCastToVoidPtr(lvalue.getBitFieldPointer());
Alexey Bataevb57056f2015-01-22 06:17:56 +000084 auto OffsetInChars =
85 (C.toCharUnitsFromBits(OrigBFI.Offset) / lvalue.getAlignment()) *
86 lvalue.getAlignment();
87 VoidPtrAddr = CGF.Builder.CreateConstGEP1_64(
88 VoidPtrAddr, OffsetInChars.getQuantity());
89 auto Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
90 VoidPtrAddr,
91 CGF.Builder.getIntNTy(AtomicSizeInBits)->getPointerTo(),
92 "atomic_bitfield_base");
93 BFI = OrigBFI;
94 BFI.Offset = Offset;
95 BFI.StorageSize = AtomicSizeInBits;
Ulrich Weigand03ce2a12015-07-10 17:30:00 +000096 BFI.StorageOffset += OffsetInChars;
John McCall7f416cc2015-09-08 08:05:57 +000097 LVal = LValue::MakeBitfield(Address(Addr, lvalue.getAlignment()),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +000098 BFI, lvalue.getType(), lvalue.getBaseInfo(),
99 lvalue.getTBAAInfo());
Alexey Bataevb8329262015-02-27 06:33:30 +0000100 AtomicTy = C.getIntTypeForBitwidth(AtomicSizeInBits, OrigBFI.IsSigned);
101 if (AtomicTy.isNull()) {
102 llvm::APInt Size(
103 /*numBits=*/32,
104 C.toCharUnitsFromBits(AtomicSizeInBits).getQuantity());
Richard Smith772e2662019-10-04 01:25:59 +0000105 AtomicTy =
106 C.getConstantArrayType(C.CharTy, Size, nullptr, ArrayType::Normal,
107 /*IndexTypeQuals=*/0);
Alexey Bataevb8329262015-02-27 06:33:30 +0000108 }
109 AtomicAlign = ValueAlign = lvalue.getAlignment();
Alexey Bataevb57056f2015-01-22 06:17:56 +0000110 } else if (lvalue.isVectorElt()) {
Simon Pilgrime0712012019-10-02 15:31:25 +0000111 ValueTy = lvalue.getType()->castAs<VectorType>()->getElementType();
Alexey Bataevb8329262015-02-27 06:33:30 +0000112 ValueSizeInBits = C.getTypeSize(ValueTy);
113 AtomicTy = lvalue.getType();
114 AtomicSizeInBits = C.getTypeSize(AtomicTy);
115 AtomicAlign = ValueAlign = lvalue.getAlignment();
Alexey Bataevb57056f2015-01-22 06:17:56 +0000116 LVal = lvalue;
117 } else {
118 assert(lvalue.isExtVectorElt());
Alexey Bataevb8329262015-02-27 06:33:30 +0000119 ValueTy = lvalue.getType();
120 ValueSizeInBits = C.getTypeSize(ValueTy);
121 AtomicTy = ValueTy = CGF.getContext().getExtVectorType(
John McCall7f416cc2015-09-08 08:05:57 +0000122 lvalue.getType(), lvalue.getExtVectorAddress()
123 .getElementType()->getVectorNumElements());
Alexey Bataevb8329262015-02-27 06:33:30 +0000124 AtomicSizeInBits = C.getTypeSize(AtomicTy);
125 AtomicAlign = ValueAlign = lvalue.getAlignment();
Alexey Bataevb57056f2015-01-22 06:17:56 +0000126 LVal = lvalue;
127 }
Alexey Bataev452d8e12014-12-15 05:25:25 +0000128 UseLibcall = !C.getTargetInfo().hasBuiltinAtomic(
129 AtomicSizeInBits, C.toBits(lvalue.getAlignment()));
John McCalla8ec7eb2013-03-07 21:37:17 +0000130 }
131
132 QualType getAtomicType() const { return AtomicTy; }
133 QualType getValueType() const { return ValueTy; }
134 CharUnits getAtomicAlignment() const { return AtomicAlign; }
John McCalla8ec7eb2013-03-07 21:37:17 +0000135 uint64_t getAtomicSizeInBits() const { return AtomicSizeInBits; }
Alexey Bataev452d8e12014-12-15 05:25:25 +0000136 uint64_t getValueSizeInBits() const { return ValueSizeInBits; }
John McCalla8ec7eb2013-03-07 21:37:17 +0000137 TypeEvaluationKind getEvaluationKind() const { return EvaluationKind; }
138 bool shouldUseLibcall() const { return UseLibcall; }
Alexey Bataevb57056f2015-01-22 06:17:56 +0000139 const LValue &getAtomicLValue() const { return LVal; }
John McCall7f416cc2015-09-08 08:05:57 +0000140 llvm::Value *getAtomicPointer() const {
Alexey Bataevb8329262015-02-27 06:33:30 +0000141 if (LVal.isSimple())
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800142 return LVal.getPointer(CGF);
Alexey Bataevb8329262015-02-27 06:33:30 +0000143 else if (LVal.isBitField())
John McCall7f416cc2015-09-08 08:05:57 +0000144 return LVal.getBitFieldPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000145 else if (LVal.isVectorElt())
John McCall7f416cc2015-09-08 08:05:57 +0000146 return LVal.getVectorPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000147 assert(LVal.isExtVectorElt());
John McCall7f416cc2015-09-08 08:05:57 +0000148 return LVal.getExtVectorPointer();
149 }
150 Address getAtomicAddress() const {
151 return Address(getAtomicPointer(), getAtomicAlignment());
152 }
153
154 Address getAtomicAddressAsAtomicIntPointer() const {
155 return emitCastToAtomicIntPointer(getAtomicAddress());
Alexey Bataevb8329262015-02-27 06:33:30 +0000156 }
John McCalla8ec7eb2013-03-07 21:37:17 +0000157
158 /// Is the atomic size larger than the underlying value type?
159 ///
160 /// Note that the absence of padding does not mean that atomic
161 /// objects are completely interchangeable with non-atomic
162 /// objects: we might have promoted the alignment of a type
163 /// without making it bigger.
164 bool hasPadding() const {
165 return (ValueSizeInBits != AtomicSizeInBits);
166 }
167
Alexey Bataevb57056f2015-01-22 06:17:56 +0000168 bool emitMemSetZeroIfNecessary() const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000169
170 llvm::Value *getAtomicSizeValue() const {
171 CharUnits size = CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits);
172 return CGF.CGM.getSize(size);
173 }
174
Tim Northovercc2a6e02015-11-09 19:56:35 +0000175 /// Cast the given pointer to an integer pointer suitable for atomic
176 /// operations if the source.
177 Address emitCastToAtomicIntPointer(Address Addr) const;
178
179 /// If Addr is compatible with the iN that will be used for an atomic
180 /// operation, bitcast it. Otherwise, create a temporary that is suitable
181 /// and copy the value across.
182 Address convertToAtomicIntPointer(Address Addr) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000183
184 /// Turn an atomic-layout object into an r-value.
John McCall7f416cc2015-09-08 08:05:57 +0000185 RValue convertAtomicTempToRValue(Address addr, AggValueSlot resultSlot,
186 SourceLocation loc, bool AsValue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000187
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000188 /// Converts a rvalue to integer value.
Alexey Bataev452d8e12014-12-15 05:25:25 +0000189 llvm::Value *convertRValueToInt(RValue RVal) const;
190
Alexey Bataevb8329262015-02-27 06:33:30 +0000191 RValue ConvertIntToValueOrAtomic(llvm::Value *IntVal,
192 AggValueSlot ResultSlot,
193 SourceLocation Loc, bool AsValue) const;
Alexey Bataev452d8e12014-12-15 05:25:25 +0000194
John McCalla8ec7eb2013-03-07 21:37:17 +0000195 /// Copy an atomic r-value into atomic-layout memory.
Alexey Bataevb57056f2015-01-22 06:17:56 +0000196 void emitCopyIntoMemory(RValue rvalue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000197
198 /// Project an l-value down to the value field.
Alexey Bataevb57056f2015-01-22 06:17:56 +0000199 LValue projectValue() const {
200 assert(LVal.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000201 Address addr = getAtomicAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +0000202 if (hasPadding())
James Y Knight751fe282019-02-09 22:22:28 +0000203 addr = CGF.Builder.CreateStructGEP(addr, 0);
John McCalla8ec7eb2013-03-07 21:37:17 +0000204
John McCall7f416cc2015-09-08 08:05:57 +0000205 return LValue::MakeAddr(addr, getValueType(), CGF.getContext(),
Ivan A. Kosarev383890b2017-10-06 08:17:48 +0000206 LVal.getBaseInfo(), LVal.getTBAAInfo());
John McCalla8ec7eb2013-03-07 21:37:17 +0000207 }
208
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000209 /// Emits atomic load.
Alexey Bataevb8329262015-02-27 06:33:30 +0000210 /// \returns Loaded value.
211 RValue EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
212 bool AsValue, llvm::AtomicOrdering AO,
213 bool IsVolatile);
214
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000215 /// Emits atomic compare-and-exchange sequence.
Alexey Bataevb8329262015-02-27 06:33:30 +0000216 /// \param Expected Expected value.
217 /// \param Desired Desired value.
218 /// \param Success Atomic ordering for success operation.
219 /// \param Failure Atomic ordering for failed operation.
220 /// \param IsWeak true if atomic operation is weak, false otherwise.
221 /// \returns Pair of values: previous value from storage (value type) and
222 /// boolean flag (i1 type) with true if success and false otherwise.
JF Bastien92f4ef12016-04-06 17:26:42 +0000223 std::pair<RValue, llvm::Value *>
224 EmitAtomicCompareExchange(RValue Expected, RValue Desired,
225 llvm::AtomicOrdering Success =
226 llvm::AtomicOrdering::SequentiallyConsistent,
227 llvm::AtomicOrdering Failure =
228 llvm::AtomicOrdering::SequentiallyConsistent,
229 bool IsWeak = false);
Alexey Bataevb8329262015-02-27 06:33:30 +0000230
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000231 /// Emits atomic update.
NAKAMURA Takumid16af5d2015-05-15 13:47:52 +0000232 /// \param AO Atomic ordering.
233 /// \param UpdateOp Update operation for the current lvalue.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000234 void EmitAtomicUpdate(llvm::AtomicOrdering AO,
235 const llvm::function_ref<RValue(RValue)> &UpdateOp,
236 bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000237 /// Emits atomic update.
NAKAMURA Takumid16af5d2015-05-15 13:47:52 +0000238 /// \param AO Atomic ordering.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000239 void EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
240 bool IsVolatile);
241
John McCalla8ec7eb2013-03-07 21:37:17 +0000242 /// Materialize an atomic r-value in atomic-layout memory.
John McCall7f416cc2015-09-08 08:05:57 +0000243 Address materializeRValue(RValue rvalue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000244
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000245 /// Creates temp alloca for intermediate operations on atomic value.
Tim Northovercc2a6e02015-11-09 19:56:35 +0000246 Address CreateTempAlloca() const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000247 private:
248 bool requiresMemSetZero(llvm::Type *type) const;
Alexey Bataevb8329262015-02-27 06:33:30 +0000249
Alexey Bataevb8329262015-02-27 06:33:30 +0000250
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000251 /// Emits atomic load as a libcall.
Alexey Bataevb8329262015-02-27 06:33:30 +0000252 void EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
253 llvm::AtomicOrdering AO, bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000254 /// Emits atomic load as LLVM instruction.
Alexey Bataevb8329262015-02-27 06:33:30 +0000255 llvm::Value *EmitAtomicLoadOp(llvm::AtomicOrdering AO, bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000256 /// Emits atomic compare-and-exchange op as a libcall.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000257 llvm::Value *EmitAtomicCompareExchangeLibcall(
258 llvm::Value *ExpectedAddr, llvm::Value *DesiredAddr,
JF Bastien92f4ef12016-04-06 17:26:42 +0000259 llvm::AtomicOrdering Success =
260 llvm::AtomicOrdering::SequentiallyConsistent,
261 llvm::AtomicOrdering Failure =
262 llvm::AtomicOrdering::SequentiallyConsistent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000263 /// Emits atomic compare-and-exchange op as LLVM instruction.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000264 std::pair<llvm::Value *, llvm::Value *> EmitAtomicCompareExchangeOp(
265 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
JF Bastien92f4ef12016-04-06 17:26:42 +0000266 llvm::AtomicOrdering Success =
267 llvm::AtomicOrdering::SequentiallyConsistent,
268 llvm::AtomicOrdering Failure =
269 llvm::AtomicOrdering::SequentiallyConsistent,
Alexey Bataevb8329262015-02-27 06:33:30 +0000270 bool IsWeak = false);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000271 /// Emit atomic update as libcalls.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000272 void
273 EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
274 const llvm::function_ref<RValue(RValue)> &UpdateOp,
275 bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000276 /// Emit atomic update as LLVM instructions.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000277 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO,
278 const llvm::function_ref<RValue(RValue)> &UpdateOp,
279 bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000280 /// Emit atomic update as libcalls.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000281 void EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO, RValue UpdateRVal,
282 bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000283 /// Emit atomic update as LLVM instructions.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000284 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRal,
285 bool IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +0000286 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000287}
John McCalla8ec7eb2013-03-07 21:37:17 +0000288
John McCall7f416cc2015-09-08 08:05:57 +0000289Address AtomicInfo::CreateTempAlloca() const {
290 Address TempAlloca = CGF.CreateMemTemp(
Alexey Bataevb8329262015-02-27 06:33:30 +0000291 (LVal.isBitField() && ValueSizeInBits > AtomicSizeInBits) ? ValueTy
292 : AtomicTy,
John McCall7f416cc2015-09-08 08:05:57 +0000293 getAtomicAlignment(),
Alexey Bataevb8329262015-02-27 06:33:30 +0000294 "atomic-temp");
Alexey Bataevb8329262015-02-27 06:33:30 +0000295 // Cast to pointer to value type for bitfields.
296 if (LVal.isBitField())
297 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +0000298 TempAlloca, getAtomicAddress().getType());
Alexey Bataevb8329262015-02-27 06:33:30 +0000299 return TempAlloca;
300}
301
John McCalla8ec7eb2013-03-07 21:37:17 +0000302static RValue emitAtomicLibcall(CodeGenFunction &CGF,
303 StringRef fnName,
304 QualType resultType,
305 CallArgList &args) {
306 const CGFunctionInfo &fnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000307 CGF.CGM.getTypes().arrangeBuiltinFunctionCall(resultType, args);
John McCalla8ec7eb2013-03-07 21:37:17 +0000308 llvm::FunctionType *fnTy = CGF.CGM.getTypes().GetFunctionType(fnInfo);
James Y Knight9871db02019-02-05 16:42:33 +0000309 llvm::FunctionCallee fn = CGF.CGM.CreateRuntimeFunction(fnTy, fnName);
John McCallb92ab1a2016-10-26 23:46:34 +0000310 auto callee = CGCallee::forDirect(fn);
311 return CGF.EmitCall(fnInfo, callee, ReturnValueSlot(), args);
John McCalla8ec7eb2013-03-07 21:37:17 +0000312}
313
314/// Does a store of the given IR type modify the full expected width?
315static bool isFullSizeType(CodeGenModule &CGM, llvm::Type *type,
316 uint64_t expectedSize) {
317 return (CGM.getDataLayout().getTypeStoreSize(type) * 8 == expectedSize);
318}
319
320/// Does the atomic type require memsetting to zero before initialization?
321///
322/// The IR type is provided as a way of making certain queries faster.
323bool AtomicInfo::requiresMemSetZero(llvm::Type *type) const {
324 // If the atomic type has size padding, we definitely need a memset.
325 if (hasPadding()) return true;
326
327 // Otherwise, do some simple heuristics to try to avoid it:
328 switch (getEvaluationKind()) {
329 // For scalars and complexes, check whether the store size of the
330 // type uses the full size.
331 case TEK_Scalar:
332 return !isFullSizeType(CGF.CGM, type, AtomicSizeInBits);
333 case TEK_Complex:
334 return !isFullSizeType(CGF.CGM, type->getStructElementType(0),
335 AtomicSizeInBits / 2);
336
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000337 // Padding in structs has an undefined bit pattern. User beware.
John McCalla8ec7eb2013-03-07 21:37:17 +0000338 case TEK_Aggregate:
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000339 return false;
John McCalla8ec7eb2013-03-07 21:37:17 +0000340 }
341 llvm_unreachable("bad evaluation kind");
342}
343
Alexey Bataevb57056f2015-01-22 06:17:56 +0000344bool AtomicInfo::emitMemSetZeroIfNecessary() const {
345 assert(LVal.isSimple());
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800346 llvm::Value *addr = LVal.getPointer(CGF);
John McCalla8ec7eb2013-03-07 21:37:17 +0000347 if (!requiresMemSetZero(addr->getType()->getPointerElementType()))
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000348 return false;
John McCalla8ec7eb2013-03-07 21:37:17 +0000349
Alexey Bataevb8329262015-02-27 06:33:30 +0000350 CGF.Builder.CreateMemSet(
351 addr, llvm::ConstantInt::get(CGF.Int8Ty, 0),
352 CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits).getQuantity(),
Guillaume Chatelet1b2842b2019-12-09 17:36:50 +0100353 LVal.getAlignment().getAsAlign());
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000354 return true;
John McCalla8ec7eb2013-03-07 21:37:17 +0000355}
356
Tim Northovercadbbe12014-06-13 19:43:04 +0000357static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak,
John McCall7f416cc2015-09-08 08:05:57 +0000358 Address Dest, Address Ptr,
359 Address Val1, Address Val2,
360 uint64_t Size,
Tim Northover9c177222014-03-13 19:25:48 +0000361 llvm::AtomicOrdering SuccessOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000362 llvm::AtomicOrdering FailureOrder,
363 llvm::SyncScope::ID Scope) {
Tim Northover9c177222014-03-13 19:25:48 +0000364 // Note that cmpxchg doesn't support weak cmpxchg, at least at the moment.
John McCall7f416cc2015-09-08 08:05:57 +0000365 llvm::Value *Expected = CGF.Builder.CreateLoad(Val1);
366 llvm::Value *Desired = CGF.Builder.CreateLoad(Val2);
Tim Northover9c177222014-03-13 19:25:48 +0000367
Tim Northoverb49b04b2014-06-13 14:24:59 +0000368 llvm::AtomicCmpXchgInst *Pair = CGF.Builder.CreateAtomicCmpXchg(
Yaxun Liu39195062017-08-04 18:16:31 +0000369 Ptr.getPointer(), Expected, Desired, SuccessOrder, FailureOrder,
370 Scope);
Tim Northoverb49b04b2014-06-13 14:24:59 +0000371 Pair->setVolatile(E->isVolatile());
Tim Northovercadbbe12014-06-13 19:43:04 +0000372 Pair->setWeak(IsWeak);
Tim Northover9c177222014-03-13 19:25:48 +0000373
374 // Cmp holds the result of the compare-exchange operation: true on success,
375 // false on failure.
Tim Northoverb49b04b2014-06-13 14:24:59 +0000376 llvm::Value *Old = CGF.Builder.CreateExtractValue(Pair, 0);
377 llvm::Value *Cmp = CGF.Builder.CreateExtractValue(Pair, 1);
Tim Northover9c177222014-03-13 19:25:48 +0000378
379 // This basic block is used to hold the store instruction if the operation
380 // failed.
381 llvm::BasicBlock *StoreExpectedBB =
382 CGF.createBasicBlock("cmpxchg.store_expected", CGF.CurFn);
383
384 // This basic block is the exit point of the operation, we should end up
385 // here regardless of whether or not the operation succeeded.
386 llvm::BasicBlock *ContinueBB =
387 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
388
389 // Update Expected if Expected isn't equal to Old, otherwise branch to the
390 // exit point.
391 CGF.Builder.CreateCondBr(Cmp, ContinueBB, StoreExpectedBB);
392
393 CGF.Builder.SetInsertPoint(StoreExpectedBB);
394 // Update the memory at Expected with Old's value.
John McCall7f416cc2015-09-08 08:05:57 +0000395 CGF.Builder.CreateStore(Old, Val1);
Tim Northover9c177222014-03-13 19:25:48 +0000396 // Finally, branch to the exit point.
397 CGF.Builder.CreateBr(ContinueBB);
398
399 CGF.Builder.SetInsertPoint(ContinueBB);
400 // Update the memory at Dest with Cmp's value.
401 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
Tim Northover9c177222014-03-13 19:25:48 +0000402}
403
404/// Given an ordering required on success, emit all possible cmpxchg
405/// instructions to cope with the provided (but possibly only dynamically known)
406/// FailureOrder.
407static void emitAtomicCmpXchgFailureSet(CodeGenFunction &CGF, AtomicExpr *E,
JF Bastiendda2cb12016-04-18 18:01:49 +0000408 bool IsWeak, Address Dest, Address Ptr,
409 Address Val1, Address Val2,
Tim Northover9c177222014-03-13 19:25:48 +0000410 llvm::Value *FailureOrderVal,
John McCall7f416cc2015-09-08 08:05:57 +0000411 uint64_t Size,
Yaxun Liu39195062017-08-04 18:16:31 +0000412 llvm::AtomicOrdering SuccessOrder,
413 llvm::SyncScope::ID Scope) {
Tim Northover9c177222014-03-13 19:25:48 +0000414 llvm::AtomicOrdering FailureOrder;
415 if (llvm::ConstantInt *FO = dyn_cast<llvm::ConstantInt>(FailureOrderVal)) {
JF Bastiendda2cb12016-04-18 18:01:49 +0000416 auto FOS = FO->getSExtValue();
417 if (!llvm::isValidAtomicOrderingCABI(FOS))
JF Bastien92f4ef12016-04-06 17:26:42 +0000418 FailureOrder = llvm::AtomicOrdering::Monotonic;
JF Bastiendda2cb12016-04-18 18:01:49 +0000419 else
420 switch ((llvm::AtomicOrderingCABI)FOS) {
421 case llvm::AtomicOrderingCABI::relaxed:
422 case llvm::AtomicOrderingCABI::release:
423 case llvm::AtomicOrderingCABI::acq_rel:
424 FailureOrder = llvm::AtomicOrdering::Monotonic;
425 break;
426 case llvm::AtomicOrderingCABI::consume:
427 case llvm::AtomicOrderingCABI::acquire:
428 FailureOrder = llvm::AtomicOrdering::Acquire;
429 break;
430 case llvm::AtomicOrderingCABI::seq_cst:
431 FailureOrder = llvm::AtomicOrdering::SequentiallyConsistent;
432 break;
433 }
JF Bastiendd11ee72016-04-06 23:37:36 +0000434 if (isStrongerThan(FailureOrder, SuccessOrder)) {
435 // Don't assert on undefined behavior "failure argument shall be no
436 // stronger than the success argument".
Tim Northover9c177222014-03-13 19:25:48 +0000437 FailureOrder =
JF Bastiendda2cb12016-04-18 18:01:49 +0000438 llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrder);
Tim Northover9c177222014-03-13 19:25:48 +0000439 }
JF Bastiendda2cb12016-04-18 18:01:49 +0000440 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000441 FailureOrder, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000442 return;
443 }
444
445 // Create all the relevant BB's
Craig Topper8a13c412014-05-21 05:09:00 +0000446 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
447 *SeqCstBB = nullptr;
Tim Northover9c177222014-03-13 19:25:48 +0000448 MonotonicBB = CGF.createBasicBlock("monotonic_fail", CGF.CurFn);
JF Bastien92f4ef12016-04-06 17:26:42 +0000449 if (SuccessOrder != llvm::AtomicOrdering::Monotonic &&
450 SuccessOrder != llvm::AtomicOrdering::Release)
Tim Northover9c177222014-03-13 19:25:48 +0000451 AcquireBB = CGF.createBasicBlock("acquire_fail", CGF.CurFn);
JF Bastien92f4ef12016-04-06 17:26:42 +0000452 if (SuccessOrder == llvm::AtomicOrdering::SequentiallyConsistent)
Tim Northover9c177222014-03-13 19:25:48 +0000453 SeqCstBB = CGF.createBasicBlock("seqcst_fail", CGF.CurFn);
454
455 llvm::BasicBlock *ContBB = CGF.createBasicBlock("atomic.continue", CGF.CurFn);
456
457 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(FailureOrderVal, MonotonicBB);
458
459 // Emit all the different atomics
460
461 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
462 // doesn't matter unless someone is crazy enough to use something that
463 // doesn't fold to a constant for the ordering.
464 CGF.Builder.SetInsertPoint(MonotonicBB);
Tim Northovercadbbe12014-06-13 19:43:04 +0000465 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000466 Size, SuccessOrder, llvm::AtomicOrdering::Monotonic, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000467 CGF.Builder.CreateBr(ContBB);
468
469 if (AcquireBB) {
470 CGF.Builder.SetInsertPoint(AcquireBB);
Tim Northovercadbbe12014-06-13 19:43:04 +0000471 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000472 Size, SuccessOrder, llvm::AtomicOrdering::Acquire, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000473 CGF.Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +0000474 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
Tim Northover9c177222014-03-13 19:25:48 +0000475 AcquireBB);
JF Bastiendda2cb12016-04-18 18:01:49 +0000476 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
Tim Northover9c177222014-03-13 19:25:48 +0000477 AcquireBB);
478 }
479 if (SeqCstBB) {
480 CGF.Builder.SetInsertPoint(SeqCstBB);
JF Bastien92f4ef12016-04-06 17:26:42 +0000481 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000482 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000483 CGF.Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +0000484 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
Tim Northover9c177222014-03-13 19:25:48 +0000485 SeqCstBB);
486 }
487
488 CGF.Builder.SetInsertPoint(ContBB);
489}
490
Tim Northover5cf58762019-11-21 10:31:30 +0000491/// Duplicate the atomic min/max operation in conventional IR for the builtin
492/// variants that return the new rather than the original value.
493static llvm::Value *EmitPostAtomicMinMax(CGBuilderTy &Builder,
494 AtomicExpr::AtomicOp Op,
495 bool IsSigned,
496 llvm::Value *OldVal,
497 llvm::Value *RHS) {
498 llvm::CmpInst::Predicate Pred;
499 switch (Op) {
500 default:
501 llvm_unreachable("Unexpected min/max operation");
502 case AtomicExpr::AO__atomic_max_fetch:
503 Pred = IsSigned ? llvm::CmpInst::ICMP_SGT : llvm::CmpInst::ICMP_UGT;
504 break;
505 case AtomicExpr::AO__atomic_min_fetch:
506 Pred = IsSigned ? llvm::CmpInst::ICMP_SLT : llvm::CmpInst::ICMP_ULT;
507 break;
508 }
509 llvm::Value *Cmp = Builder.CreateICmp(Pred, OldVal, RHS, "tst");
510 return Builder.CreateSelect(Cmp, OldVal, RHS, "newval");
511}
512
John McCall7f416cc2015-09-08 08:05:57 +0000513static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest,
514 Address Ptr, Address Val1, Address Val2,
Tim Northovercadbbe12014-06-13 19:43:04 +0000515 llvm::Value *IsWeak, llvm::Value *FailureOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000516 uint64_t Size, llvm::AtomicOrdering Order,
517 llvm::SyncScope::ID Scope) {
John McCallfc207f22013-03-07 21:37:12 +0000518 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
Tim Northover5cf58762019-11-21 10:31:30 +0000519 bool PostOpMinMax = false;
520 unsigned PostOp = 0;
John McCallfc207f22013-03-07 21:37:12 +0000521
522 switch (E->getOp()) {
523 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000524 case AtomicExpr::AO__opencl_atomic_init:
John McCallfc207f22013-03-07 21:37:12 +0000525 llvm_unreachable("Already handled!");
526
527 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +0000528 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
Tim Northovercadbbe12014-06-13 19:43:04 +0000529 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000530 FailureOrder, Size, Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000531 return;
Tim Northovercadbbe12014-06-13 19:43:04 +0000532 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +0000533 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Tim Northovercadbbe12014-06-13 19:43:04 +0000534 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000535 FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000536 return;
537 case AtomicExpr::AO__atomic_compare_exchange:
538 case AtomicExpr::AO__atomic_compare_exchange_n: {
539 if (llvm::ConstantInt *IsWeakC = dyn_cast<llvm::ConstantInt>(IsWeak)) {
540 emitAtomicCmpXchgFailureSet(CGF, E, IsWeakC->getZExtValue(), Dest, Ptr,
Yaxun Liu39195062017-08-04 18:16:31 +0000541 Val1, Val2, FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000542 } else {
543 // Create all the relevant BB's
544 llvm::BasicBlock *StrongBB =
545 CGF.createBasicBlock("cmpxchg.strong", CGF.CurFn);
546 llvm::BasicBlock *WeakBB = CGF.createBasicBlock("cmxchg.weak", CGF.CurFn);
547 llvm::BasicBlock *ContBB =
548 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
549
550 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(IsWeak, WeakBB);
551 SI->addCase(CGF.Builder.getInt1(false), StrongBB);
552
553 CGF.Builder.SetInsertPoint(StrongBB);
554 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000555 FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000556 CGF.Builder.CreateBr(ContBB);
557
558 CGF.Builder.SetInsertPoint(WeakBB);
559 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000560 FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000561 CGF.Builder.CreateBr(ContBB);
562
563 CGF.Builder.SetInsertPoint(ContBB);
564 }
565 return;
566 }
John McCallfc207f22013-03-07 21:37:12 +0000567 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +0000568 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +0000569 case AtomicExpr::AO__atomic_load_n:
570 case AtomicExpr::AO__atomic_load: {
571 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
Yaxun Liu39195062017-08-04 18:16:31 +0000572 Load->setAtomic(Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000573 Load->setVolatile(E->isVolatile());
John McCall7f416cc2015-09-08 08:05:57 +0000574 CGF.Builder.CreateStore(Load, Dest);
John McCallfc207f22013-03-07 21:37:12 +0000575 return;
576 }
577
578 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +0000579 case AtomicExpr::AO__opencl_atomic_store:
John McCallfc207f22013-03-07 21:37:12 +0000580 case AtomicExpr::AO__atomic_store:
581 case AtomicExpr::AO__atomic_store_n: {
John McCall7f416cc2015-09-08 08:05:57 +0000582 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
John McCallfc207f22013-03-07 21:37:12 +0000583 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
Yaxun Liu39195062017-08-04 18:16:31 +0000584 Store->setAtomic(Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000585 Store->setVolatile(E->isVolatile());
586 return;
587 }
588
589 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +0000590 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +0000591 case AtomicExpr::AO__atomic_exchange_n:
592 case AtomicExpr::AO__atomic_exchange:
593 Op = llvm::AtomicRMWInst::Xchg;
594 break;
595
596 case AtomicExpr::AO__atomic_add_fetch:
597 PostOp = llvm::Instruction::Add;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000598 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000599 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +0000600 case AtomicExpr::AO__opencl_atomic_fetch_add:
John McCallfc207f22013-03-07 21:37:12 +0000601 case AtomicExpr::AO__atomic_fetch_add:
602 Op = llvm::AtomicRMWInst::Add;
603 break;
604
605 case AtomicExpr::AO__atomic_sub_fetch:
606 PostOp = llvm::Instruction::Sub;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000607 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000608 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000609 case AtomicExpr::AO__opencl_atomic_fetch_sub:
John McCallfc207f22013-03-07 21:37:12 +0000610 case AtomicExpr::AO__atomic_fetch_sub:
611 Op = llvm::AtomicRMWInst::Sub;
612 break;
613
Tim Northover5cf58762019-11-21 10:31:30 +0000614 case AtomicExpr::AO__atomic_min_fetch:
615 PostOpMinMax = true;
616 LLVM_FALLTHROUGH;
617 case AtomicExpr::AO__c11_atomic_fetch_min:
Yaxun Liu39195062017-08-04 18:16:31 +0000618 case AtomicExpr::AO__opencl_atomic_fetch_min:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +0000619 case AtomicExpr::AO__atomic_fetch_min:
Yaxun Liu39195062017-08-04 18:16:31 +0000620 Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Min
621 : llvm::AtomicRMWInst::UMin;
622 break;
623
Tim Northover5cf58762019-11-21 10:31:30 +0000624 case AtomicExpr::AO__atomic_max_fetch:
625 PostOpMinMax = true;
626 LLVM_FALLTHROUGH;
627 case AtomicExpr::AO__c11_atomic_fetch_max:
Yaxun Liu39195062017-08-04 18:16:31 +0000628 case AtomicExpr::AO__opencl_atomic_fetch_max:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +0000629 case AtomicExpr::AO__atomic_fetch_max:
Yaxun Liu39195062017-08-04 18:16:31 +0000630 Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Max
631 : llvm::AtomicRMWInst::UMax;
632 break;
633
John McCallfc207f22013-03-07 21:37:12 +0000634 case AtomicExpr::AO__atomic_and_fetch:
635 PostOp = llvm::Instruction::And;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000636 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000637 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +0000638 case AtomicExpr::AO__opencl_atomic_fetch_and:
John McCallfc207f22013-03-07 21:37:12 +0000639 case AtomicExpr::AO__atomic_fetch_and:
640 Op = llvm::AtomicRMWInst::And;
641 break;
642
643 case AtomicExpr::AO__atomic_or_fetch:
644 PostOp = llvm::Instruction::Or;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000645 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000646 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +0000647 case AtomicExpr::AO__opencl_atomic_fetch_or:
John McCallfc207f22013-03-07 21:37:12 +0000648 case AtomicExpr::AO__atomic_fetch_or:
649 Op = llvm::AtomicRMWInst::Or;
650 break;
651
652 case AtomicExpr::AO__atomic_xor_fetch:
653 PostOp = llvm::Instruction::Xor;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000654 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000655 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +0000656 case AtomicExpr::AO__opencl_atomic_fetch_xor:
John McCallfc207f22013-03-07 21:37:12 +0000657 case AtomicExpr::AO__atomic_fetch_xor:
658 Op = llvm::AtomicRMWInst::Xor;
659 break;
660
661 case AtomicExpr::AO__atomic_nand_fetch:
James Y Knight7aefb5b2015-11-12 18:37:29 +0000662 PostOp = llvm::Instruction::And; // the NOT is special cased below
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000663 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000664 case AtomicExpr::AO__atomic_fetch_nand:
665 Op = llvm::AtomicRMWInst::Nand;
666 break;
667 }
668
John McCall7f416cc2015-09-08 08:05:57 +0000669 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
John McCallfc207f22013-03-07 21:37:12 +0000670 llvm::AtomicRMWInst *RMWI =
Yaxun Liu39195062017-08-04 18:16:31 +0000671 CGF.Builder.CreateAtomicRMW(Op, Ptr.getPointer(), LoadVal1, Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000672 RMWI->setVolatile(E->isVolatile());
673
674 // For __atomic_*_fetch operations, perform the operation again to
675 // determine the value which was written.
676 llvm::Value *Result = RMWI;
Tim Northover5cf58762019-11-21 10:31:30 +0000677 if (PostOpMinMax)
678 Result = EmitPostAtomicMinMax(CGF.Builder, E->getOp(),
679 E->getValueType()->isSignedIntegerType(),
680 RMWI, LoadVal1);
681 else if (PostOp)
682 Result = CGF.Builder.CreateBinOp((llvm::Instruction::BinaryOps)PostOp, RMWI,
683 LoadVal1);
John McCallfc207f22013-03-07 21:37:12 +0000684 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
685 Result = CGF.Builder.CreateNot(Result);
John McCall7f416cc2015-09-08 08:05:57 +0000686 CGF.Builder.CreateStore(Result, Dest);
John McCallfc207f22013-03-07 21:37:12 +0000687}
688
689// This function emits any expression (scalar, complex, or aggregate)
690// into a temporary alloca.
John McCall7f416cc2015-09-08 08:05:57 +0000691static Address
John McCallfc207f22013-03-07 21:37:12 +0000692EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
John McCall7f416cc2015-09-08 08:05:57 +0000693 Address DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
John McCallfc207f22013-03-07 21:37:12 +0000694 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
695 /*Init*/ true);
696 return DeclPtr;
697}
698
Yaxun Liu30d652a2017-08-15 16:02:49 +0000699static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *Expr, Address Dest,
700 Address Ptr, Address Val1, Address Val2,
701 llvm::Value *IsWeak, llvm::Value *FailureOrder,
702 uint64_t Size, llvm::AtomicOrdering Order,
703 llvm::Value *Scope) {
704 auto ScopeModel = Expr->getScopeModel();
705
706 // LLVM atomic instructions always have synch scope. If clang atomic
707 // expression has no scope operand, use default LLVM synch scope.
708 if (!ScopeModel) {
709 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
710 Order, CGF.CGM.getLLVMContext().getOrInsertSyncScopeID(""));
711 return;
712 }
713
714 // Handle constant scope.
715 if (auto SC = dyn_cast<llvm::ConstantInt>(Scope)) {
716 auto SCID = CGF.getTargetHooks().getLLVMSyncScopeID(
Konstantin Zhuravlyovec28a1d2019-03-25 20:54:00 +0000717 CGF.CGM.getLangOpts(), ScopeModel->map(SC->getZExtValue()),
718 Order, CGF.CGM.getLLVMContext());
Yaxun Liu30d652a2017-08-15 16:02:49 +0000719 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
720 Order, SCID);
721 return;
722 }
723
724 // Handle non-constant scope.
725 auto &Builder = CGF.Builder;
726 auto Scopes = ScopeModel->getRuntimeValues();
727 llvm::DenseMap<unsigned, llvm::BasicBlock *> BB;
728 for (auto S : Scopes)
729 BB[S] = CGF.createBasicBlock(getAsString(ScopeModel->map(S)), CGF.CurFn);
730
731 llvm::BasicBlock *ContBB =
732 CGF.createBasicBlock("atomic.scope.continue", CGF.CurFn);
733
734 auto *SC = Builder.CreateIntCast(Scope, Builder.getInt32Ty(), false);
735 // If unsupported synch scope is encountered at run time, assume a fallback
736 // synch scope value.
737 auto FallBack = ScopeModel->getFallBackValue();
738 llvm::SwitchInst *SI = Builder.CreateSwitch(SC, BB[FallBack]);
739 for (auto S : Scopes) {
740 auto *B = BB[S];
741 if (S != FallBack)
742 SI->addCase(Builder.getInt32(S), B);
743
744 Builder.SetInsertPoint(B);
745 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
746 Order,
Konstantin Zhuravlyovec28a1d2019-03-25 20:54:00 +0000747 CGF.getTargetHooks().getLLVMSyncScopeID(CGF.CGM.getLangOpts(),
748 ScopeModel->map(S),
749 Order,
Yaxun Liu30d652a2017-08-15 16:02:49 +0000750 CGF.getLLVMContext()));
751 Builder.CreateBr(ContBB);
752 }
753
754 Builder.SetInsertPoint(ContBB);
755}
756
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000757static void
758AddDirectArgument(CodeGenFunction &CGF, CallArgList &Args,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000759 bool UseOptimizedLibcall, llvm::Value *Val, QualType ValTy,
David Majnemer0392cf82014-08-29 07:27:49 +0000760 SourceLocation Loc, CharUnits SizeInChars) {
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000761 if (UseOptimizedLibcall) {
762 // Load value and pass it to the function directly.
John McCall7f416cc2015-09-08 08:05:57 +0000763 CharUnits Align = CGF.getContext().getTypeAlignInChars(ValTy);
David Majnemer0392cf82014-08-29 07:27:49 +0000764 int64_t SizeInBits = CGF.getContext().toBits(SizeInChars);
765 ValTy =
766 CGF.getContext().getIntTypeForBitwidth(SizeInBits, /*Signed=*/false);
767 llvm::Type *IPtrTy = llvm::IntegerType::get(CGF.getLLVMContext(),
768 SizeInBits)->getPointerTo();
John McCall7f416cc2015-09-08 08:05:57 +0000769 Address Ptr = Address(CGF.Builder.CreateBitCast(Val, IPtrTy), Align);
770 Val = CGF.EmitLoadOfScalar(Ptr, false,
771 CGF.getContext().getPointerType(ValTy),
David Majnemer0392cf82014-08-29 07:27:49 +0000772 Loc);
773 // Coerce the value into an appropriately sized integer type.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000774 Args.add(RValue::get(Val), ValTy);
775 } else {
776 // Non-optimized functions always take a reference.
777 Args.add(RValue::get(CGF.EmitCastToVoidPtr(Val)),
778 CGF.getContext().VoidPtrTy);
779 }
780}
781
Tim Northovercc2a6e02015-11-09 19:56:35 +0000782RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
John McCallfc207f22013-03-07 21:37:12 +0000783 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
784 QualType MemTy = AtomicTy;
785 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
786 MemTy = AT->getValueType();
John McCall7f416cc2015-09-08 08:05:57 +0000787 llvm::Value *IsWeak = nullptr, *OrderFail = nullptr;
788
789 Address Val1 = Address::invalid();
790 Address Val2 = Address::invalid();
Tim Northovercc2a6e02015-11-09 19:56:35 +0000791 Address Dest = Address::invalid();
Wei Mi01414bd2017-09-25 19:57:59 +0000792 Address Ptr = EmitPointerWithAlignment(E->getPtr());
793
Tim Northover9dc1d0c2018-04-23 08:16:24 +0000794 if (E->getOp() == AtomicExpr::AO__c11_atomic_init ||
795 E->getOp() == AtomicExpr::AO__opencl_atomic_init) {
796 LValue lvalue = MakeAddrLValue(Ptr, AtomicTy);
797 EmitAtomicInit(E->getVal1(), lvalue);
798 return RValue::get(nullptr);
799 }
800
Wei Mi01414bd2017-09-25 19:57:59 +0000801 CharUnits sizeChars, alignChars;
802 std::tie(sizeChars, alignChars) = getContext().getTypeInfoInChars(AtomicTy);
803 uint64_t Size = sizeChars.getQuantity();
804 unsigned MaxInlineWidthInBits = getTarget().getMaxAtomicInlineWidth();
John McCallfc207f22013-03-07 21:37:12 +0000805
Richard Smithedb9fbb2018-09-07 21:24:27 +0000806 bool Oversized = getContext().toBits(sizeChars) > MaxInlineWidthInBits;
807 bool Misaligned = (Ptr.getAlignment() % sizeChars) != 0;
808 bool UseLibcall = Misaligned | Oversized;
809
810 if (UseLibcall) {
811 CGM.getDiags().Report(E->getBeginLoc(), diag::warn_atomic_op_misaligned)
812 << !Oversized;
813 }
John McCallfc207f22013-03-07 21:37:12 +0000814
Craig Topper8a13c412014-05-21 05:09:00 +0000815 llvm::Value *Order = EmitScalarExpr(E->getOrder());
Yaxun Liu30d652a2017-08-15 16:02:49 +0000816 llvm::Value *Scope =
817 E->getScopeModel() ? EmitScalarExpr(E->getScope()) : nullptr;
John McCallfc207f22013-03-07 21:37:12 +0000818
819 switch (E->getOp()) {
820 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000821 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000822 llvm_unreachable("Already handled above with EmitAtomicInit!");
John McCallfc207f22013-03-07 21:37:12 +0000823
824 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +0000825 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +0000826 case AtomicExpr::AO__atomic_load_n:
827 break;
828
829 case AtomicExpr::AO__atomic_load:
John McCall7f416cc2015-09-08 08:05:57 +0000830 Dest = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000831 break;
832
833 case AtomicExpr::AO__atomic_store:
John McCall7f416cc2015-09-08 08:05:57 +0000834 Val1 = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000835 break;
836
837 case AtomicExpr::AO__atomic_exchange:
John McCall7f416cc2015-09-08 08:05:57 +0000838 Val1 = EmitPointerWithAlignment(E->getVal1());
839 Dest = EmitPointerWithAlignment(E->getVal2());
John McCallfc207f22013-03-07 21:37:12 +0000840 break;
841
842 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
843 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +0000844 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
845 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
John McCallfc207f22013-03-07 21:37:12 +0000846 case AtomicExpr::AO__atomic_compare_exchange_n:
847 case AtomicExpr::AO__atomic_compare_exchange:
John McCall7f416cc2015-09-08 08:05:57 +0000848 Val1 = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000849 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
John McCall7f416cc2015-09-08 08:05:57 +0000850 Val2 = EmitPointerWithAlignment(E->getVal2());
John McCallfc207f22013-03-07 21:37:12 +0000851 else
852 Val2 = EmitValToTemp(*this, E->getVal2());
853 OrderFail = EmitScalarExpr(E->getOrderFail());
Yaxun Liu39195062017-08-04 18:16:31 +0000854 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
855 E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
Tim Northovercadbbe12014-06-13 19:43:04 +0000856 IsWeak = EmitScalarExpr(E->getWeak());
John McCallfc207f22013-03-07 21:37:12 +0000857 break;
858
859 case AtomicExpr::AO__c11_atomic_fetch_add:
860 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000861 case AtomicExpr::AO__opencl_atomic_fetch_add:
862 case AtomicExpr::AO__opencl_atomic_fetch_sub:
John McCallfc207f22013-03-07 21:37:12 +0000863 if (MemTy->isPointerType()) {
864 // For pointer arithmetic, we're required to do a bit of math:
865 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
866 // ... but only for the C11 builtins. The GNU builtins expect the
867 // user to multiply by sizeof(T).
868 QualType Val1Ty = E->getVal1()->getType();
869 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
870 CharUnits PointeeIncAmt =
871 getContext().getTypeSizeInChars(MemTy->getPointeeType());
872 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
John McCall7f416cc2015-09-08 08:05:57 +0000873 auto Temp = CreateMemTemp(Val1Ty, ".atomictmp");
874 Val1 = Temp;
875 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Temp, Val1Ty));
John McCallfc207f22013-03-07 21:37:12 +0000876 break;
877 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000878 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000879 case AtomicExpr::AO__atomic_fetch_add:
880 case AtomicExpr::AO__atomic_fetch_sub:
881 case AtomicExpr::AO__atomic_add_fetch:
882 case AtomicExpr::AO__atomic_sub_fetch:
883 case AtomicExpr::AO__c11_atomic_store:
884 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +0000885 case AtomicExpr::AO__opencl_atomic_store:
886 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +0000887 case AtomicExpr::AO__atomic_store_n:
888 case AtomicExpr::AO__atomic_exchange_n:
889 case AtomicExpr::AO__c11_atomic_fetch_and:
890 case AtomicExpr::AO__c11_atomic_fetch_or:
891 case AtomicExpr::AO__c11_atomic_fetch_xor:
Tim Northover5cf58762019-11-21 10:31:30 +0000892 case AtomicExpr::AO__c11_atomic_fetch_max:
893 case AtomicExpr::AO__c11_atomic_fetch_min:
Yaxun Liu39195062017-08-04 18:16:31 +0000894 case AtomicExpr::AO__opencl_atomic_fetch_and:
895 case AtomicExpr::AO__opencl_atomic_fetch_or:
896 case AtomicExpr::AO__opencl_atomic_fetch_xor:
897 case AtomicExpr::AO__opencl_atomic_fetch_min:
898 case AtomicExpr::AO__opencl_atomic_fetch_max:
John McCallfc207f22013-03-07 21:37:12 +0000899 case AtomicExpr::AO__atomic_fetch_and:
900 case AtomicExpr::AO__atomic_fetch_or:
901 case AtomicExpr::AO__atomic_fetch_xor:
902 case AtomicExpr::AO__atomic_fetch_nand:
903 case AtomicExpr::AO__atomic_and_fetch:
904 case AtomicExpr::AO__atomic_or_fetch:
905 case AtomicExpr::AO__atomic_xor_fetch:
906 case AtomicExpr::AO__atomic_nand_fetch:
Tim Northover5cf58762019-11-21 10:31:30 +0000907 case AtomicExpr::AO__atomic_max_fetch:
908 case AtomicExpr::AO__atomic_min_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +0000909 case AtomicExpr::AO__atomic_fetch_max:
Tim Northover5cf58762019-11-21 10:31:30 +0000910 case AtomicExpr::AO__atomic_fetch_min:
John McCallfc207f22013-03-07 21:37:12 +0000911 Val1 = EmitValToTemp(*this, E->getVal1());
912 break;
913 }
914
David Majnemeree8d04d2014-12-12 08:16:09 +0000915 QualType RValTy = E->getType().getUnqualifiedType();
916
Tim Northovercc2a6e02015-11-09 19:56:35 +0000917 // The inlined atomics only function on iN types, where N is a power of 2. We
918 // need to make sure (via temporaries if necessary) that all incoming values
919 // are compatible.
920 LValue AtomicVal = MakeAddrLValue(Ptr, AtomicTy);
921 AtomicInfo Atomics(*this, AtomicVal);
922
923 Ptr = Atomics.emitCastToAtomicIntPointer(Ptr);
924 if (Val1.isValid()) Val1 = Atomics.convertToAtomicIntPointer(Val1);
925 if (Val2.isValid()) Val2 = Atomics.convertToAtomicIntPointer(Val2);
926 if (Dest.isValid())
927 Dest = Atomics.emitCastToAtomicIntPointer(Dest);
928 else if (E->isCmpXChg())
929 Dest = CreateMemTemp(RValTy, "cmpxchg.bool");
930 else if (!RValTy->isVoidType())
931 Dest = Atomics.emitCastToAtomicIntPointer(Atomics.CreateTempAlloca());
John McCallfc207f22013-03-07 21:37:12 +0000932
933 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
934 if (UseLibcall) {
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000935 bool UseOptimizedLibcall = false;
936 switch (E->getOp()) {
James Y Knight81167fb2015-08-05 16:57:36 +0000937 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000938 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000939 llvm_unreachable("Already handled above with EmitAtomicInit!");
940
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000941 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +0000942 case AtomicExpr::AO__opencl_atomic_fetch_add:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000943 case AtomicExpr::AO__atomic_fetch_add:
944 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +0000945 case AtomicExpr::AO__opencl_atomic_fetch_and:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000946 case AtomicExpr::AO__atomic_fetch_and:
947 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +0000948 case AtomicExpr::AO__opencl_atomic_fetch_or:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000949 case AtomicExpr::AO__atomic_fetch_or:
James Y Knight81167fb2015-08-05 16:57:36 +0000950 case AtomicExpr::AO__atomic_fetch_nand:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000951 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000952 case AtomicExpr::AO__opencl_atomic_fetch_sub:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000953 case AtomicExpr::AO__atomic_fetch_sub:
954 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +0000955 case AtomicExpr::AO__opencl_atomic_fetch_xor:
956 case AtomicExpr::AO__opencl_atomic_fetch_min:
957 case AtomicExpr::AO__opencl_atomic_fetch_max:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000958 case AtomicExpr::AO__atomic_fetch_xor:
Tim Northover5cf58762019-11-21 10:31:30 +0000959 case AtomicExpr::AO__c11_atomic_fetch_max:
960 case AtomicExpr::AO__c11_atomic_fetch_min:
James Y Knight81167fb2015-08-05 16:57:36 +0000961 case AtomicExpr::AO__atomic_add_fetch:
962 case AtomicExpr::AO__atomic_and_fetch:
963 case AtomicExpr::AO__atomic_nand_fetch:
964 case AtomicExpr::AO__atomic_or_fetch:
965 case AtomicExpr::AO__atomic_sub_fetch:
966 case AtomicExpr::AO__atomic_xor_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +0000967 case AtomicExpr::AO__atomic_fetch_max:
Tim Northover5cf58762019-11-21 10:31:30 +0000968 case AtomicExpr::AO__atomic_fetch_min:
969 case AtomicExpr::AO__atomic_max_fetch:
970 case AtomicExpr::AO__atomic_min_fetch:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000971 // For these, only library calls for certain sizes exist.
972 UseOptimizedLibcall = true;
973 break;
James Y Knight81167fb2015-08-05 16:57:36 +0000974
Richard Smithda3729d2018-09-07 23:57:54 +0000975 case AtomicExpr::AO__atomic_load:
976 case AtomicExpr::AO__atomic_store:
977 case AtomicExpr::AO__atomic_exchange:
978 case AtomicExpr::AO__atomic_compare_exchange:
979 // Use the generic version if we don't know that the operand will be
980 // suitably aligned for the optimized version.
981 if (Misaligned)
982 break;
983 LLVM_FALLTHROUGH;
James Y Knight81167fb2015-08-05 16:57:36 +0000984 case AtomicExpr::AO__c11_atomic_load:
985 case AtomicExpr::AO__c11_atomic_store:
986 case AtomicExpr::AO__c11_atomic_exchange:
987 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
988 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +0000989 case AtomicExpr::AO__opencl_atomic_load:
990 case AtomicExpr::AO__opencl_atomic_store:
991 case AtomicExpr::AO__opencl_atomic_exchange:
992 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
993 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
James Y Knight81167fb2015-08-05 16:57:36 +0000994 case AtomicExpr::AO__atomic_load_n:
James Y Knight81167fb2015-08-05 16:57:36 +0000995 case AtomicExpr::AO__atomic_store_n:
James Y Knight81167fb2015-08-05 16:57:36 +0000996 case AtomicExpr::AO__atomic_exchange_n:
James Y Knight81167fb2015-08-05 16:57:36 +0000997 case AtomicExpr::AO__atomic_compare_exchange_n:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000998 // Only use optimized library calls for sizes for which they exist.
Richard Smithda3729d2018-09-07 23:57:54 +0000999 // FIXME: Size == 16 optimized library functions exist too.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001000 if (Size == 1 || Size == 2 || Size == 4 || Size == 8)
1001 UseOptimizedLibcall = true;
1002 break;
1003 }
John McCallfc207f22013-03-07 21:37:12 +00001004
John McCallfc207f22013-03-07 21:37:12 +00001005 CallArgList Args;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001006 if (!UseOptimizedLibcall) {
1007 // For non-optimized library calls, the size is the first parameter
1008 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
1009 getContext().getSizeType());
1010 }
1011 // Atomic address is the first or second parameter
Yaxun Liu39195062017-08-04 18:16:31 +00001012 // The OpenCL atomic library functions only accept pointer arguments to
1013 // generic address space.
1014 auto CastToGenericAddrSpace = [&](llvm::Value *V, QualType PT) {
1015 if (!E->isOpenCL())
1016 return V;
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00001017 auto AS = PT->castAs<PointerType>()->getPointeeType().getAddressSpace();
Yaxun Liu39195062017-08-04 18:16:31 +00001018 if (AS == LangAS::opencl_generic)
1019 return V;
1020 auto DestAS = getContext().getTargetAddressSpace(LangAS::opencl_generic);
1021 auto T = V->getType();
1022 auto *DestType = T->getPointerElementType()->getPointerTo(DestAS);
1023
1024 return getTargetHooks().performAddrSpaceCast(
1025 *this, V, AS, LangAS::opencl_generic, DestType, false);
1026 };
1027
1028 Args.add(RValue::get(CastToGenericAddrSpace(
1029 EmitCastToVoidPtr(Ptr.getPointer()), E->getPtr()->getType())),
John McCall7f416cc2015-09-08 08:05:57 +00001030 getContext().VoidPtrTy);
John McCallfc207f22013-03-07 21:37:12 +00001031
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001032 std::string LibCallName;
Logan Chien74798a32014-03-26 17:35:01 +00001033 QualType LoweredMemTy =
1034 MemTy->isPointerType() ? getContext().getIntPtrType() : MemTy;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001035 QualType RetTy;
1036 bool HaveRetTy = false;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001037 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
Tim Northover5cf58762019-11-21 10:31:30 +00001038 bool PostOpMinMax = false;
John McCallfc207f22013-03-07 21:37:12 +00001039 switch (E->getOp()) {
James Y Knight81167fb2015-08-05 16:57:36 +00001040 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00001041 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +00001042 llvm_unreachable("Already handled!");
1043
John McCallfc207f22013-03-07 21:37:12 +00001044 // There is only one libcall for compare an exchange, because there is no
1045 // optimisation benefit possible from a libcall version of a weak compare
1046 // and exchange.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001047 // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
John McCallfc207f22013-03-07 21:37:12 +00001048 // void *desired, int success, int failure)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001049 // bool __atomic_compare_exchange_N(T *mem, T *expected, T desired,
1050 // int success, int failure)
John McCallfc207f22013-03-07 21:37:12 +00001051 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1052 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +00001053 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1054 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
John McCallfc207f22013-03-07 21:37:12 +00001055 case AtomicExpr::AO__atomic_compare_exchange:
1056 case AtomicExpr::AO__atomic_compare_exchange_n:
1057 LibCallName = "__atomic_compare_exchange";
1058 RetTy = getContext().BoolTy;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001059 HaveRetTy = true;
Yaxun Liu39195062017-08-04 18:16:31 +00001060 Args.add(
1061 RValue::get(CastToGenericAddrSpace(
1062 EmitCastToVoidPtr(Val1.getPointer()), E->getVal1()->getType())),
1063 getContext().VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001064 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val2.getPointer(),
1065 MemTy, E->getExprLoc(), sizeChars);
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001066 Args.add(RValue::get(Order), getContext().IntTy);
John McCallfc207f22013-03-07 21:37:12 +00001067 Order = OrderFail;
1068 break;
1069 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
1070 // int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001071 // T __atomic_exchange_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +00001072 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00001073 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +00001074 case AtomicExpr::AO__atomic_exchange_n:
1075 case AtomicExpr::AO__atomic_exchange:
1076 LibCallName = "__atomic_exchange";
John McCall7f416cc2015-09-08 08:05:57 +00001077 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1078 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001079 break;
1080 // void __atomic_store(size_t size, void *mem, void *val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001081 // void __atomic_store_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +00001082 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00001083 case AtomicExpr::AO__opencl_atomic_store:
John McCallfc207f22013-03-07 21:37:12 +00001084 case AtomicExpr::AO__atomic_store:
1085 case AtomicExpr::AO__atomic_store_n:
1086 LibCallName = "__atomic_store";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001087 RetTy = getContext().VoidTy;
1088 HaveRetTy = true;
John McCall7f416cc2015-09-08 08:05:57 +00001089 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1090 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001091 break;
1092 // void __atomic_load(size_t size, void *mem, void *return, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001093 // T __atomic_load_N(T *mem, int order)
John McCallfc207f22013-03-07 21:37:12 +00001094 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00001095 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +00001096 case AtomicExpr::AO__atomic_load:
1097 case AtomicExpr::AO__atomic_load_n:
1098 LibCallName = "__atomic_load";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001099 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001100 // T __atomic_add_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001101 // T __atomic_fetch_add_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001102 case AtomicExpr::AO__atomic_add_fetch:
1103 PostOp = llvm::Instruction::Add;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001104 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001105 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +00001106 case AtomicExpr::AO__opencl_atomic_fetch_add:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001107 case AtomicExpr::AO__atomic_fetch_add:
1108 LibCallName = "__atomic_fetch_add";
John McCall7f416cc2015-09-08 08:05:57 +00001109 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1110 LoweredMemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001111 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001112 // T __atomic_and_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001113 // T __atomic_fetch_and_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001114 case AtomicExpr::AO__atomic_and_fetch:
1115 PostOp = llvm::Instruction::And;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001116 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001117 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +00001118 case AtomicExpr::AO__opencl_atomic_fetch_and:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001119 case AtomicExpr::AO__atomic_fetch_and:
1120 LibCallName = "__atomic_fetch_and";
John McCall7f416cc2015-09-08 08:05:57 +00001121 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1122 MemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001123 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001124 // T __atomic_or_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001125 // T __atomic_fetch_or_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001126 case AtomicExpr::AO__atomic_or_fetch:
1127 PostOp = llvm::Instruction::Or;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001128 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001129 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +00001130 case AtomicExpr::AO__opencl_atomic_fetch_or:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001131 case AtomicExpr::AO__atomic_fetch_or:
1132 LibCallName = "__atomic_fetch_or";
John McCall7f416cc2015-09-08 08:05:57 +00001133 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1134 MemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001135 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001136 // T __atomic_sub_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001137 // T __atomic_fetch_sub_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001138 case AtomicExpr::AO__atomic_sub_fetch:
1139 PostOp = llvm::Instruction::Sub;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001140 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001141 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00001142 case AtomicExpr::AO__opencl_atomic_fetch_sub:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001143 case AtomicExpr::AO__atomic_fetch_sub:
1144 LibCallName = "__atomic_fetch_sub";
John McCall7f416cc2015-09-08 08:05:57 +00001145 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1146 LoweredMemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001147 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001148 // T __atomic_xor_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001149 // T __atomic_fetch_xor_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001150 case AtomicExpr::AO__atomic_xor_fetch:
1151 PostOp = llvm::Instruction::Xor;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001152 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001153 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00001154 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001155 case AtomicExpr::AO__atomic_fetch_xor:
1156 LibCallName = "__atomic_fetch_xor";
John McCall7f416cc2015-09-08 08:05:57 +00001157 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1158 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001159 break;
Tim Northover5cf58762019-11-21 10:31:30 +00001160 case AtomicExpr::AO__atomic_min_fetch:
1161 PostOpMinMax = true;
1162 LLVM_FALLTHROUGH;
1163 case AtomicExpr::AO__c11_atomic_fetch_min:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00001164 case AtomicExpr::AO__atomic_fetch_min:
Yaxun Liu39195062017-08-04 18:16:31 +00001165 case AtomicExpr::AO__opencl_atomic_fetch_min:
1166 LibCallName = E->getValueType()->isSignedIntegerType()
1167 ? "__atomic_fetch_min"
1168 : "__atomic_fetch_umin";
1169 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1170 LoweredMemTy, E->getExprLoc(), sizeChars);
1171 break;
Tim Northover5cf58762019-11-21 10:31:30 +00001172 case AtomicExpr::AO__atomic_max_fetch:
1173 PostOpMinMax = true;
1174 LLVM_FALLTHROUGH;
1175 case AtomicExpr::AO__c11_atomic_fetch_max:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00001176 case AtomicExpr::AO__atomic_fetch_max:
Yaxun Liu39195062017-08-04 18:16:31 +00001177 case AtomicExpr::AO__opencl_atomic_fetch_max:
1178 LibCallName = E->getValueType()->isSignedIntegerType()
1179 ? "__atomic_fetch_max"
1180 : "__atomic_fetch_umax";
1181 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1182 LoweredMemTy, E->getExprLoc(), sizeChars);
1183 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001184 // T __atomic_nand_fetch_N(T *mem, T val, int order)
James Y Knight81167fb2015-08-05 16:57:36 +00001185 // T __atomic_fetch_nand_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001186 case AtomicExpr::AO__atomic_nand_fetch:
1187 PostOp = llvm::Instruction::And; // the NOT is special cased below
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001188 LLVM_FALLTHROUGH;
James Y Knight81167fb2015-08-05 16:57:36 +00001189 case AtomicExpr::AO__atomic_fetch_nand:
1190 LibCallName = "__atomic_fetch_nand";
John McCall7f416cc2015-09-08 08:05:57 +00001191 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1192 MemTy, E->getExprLoc(), sizeChars);
James Y Knight81167fb2015-08-05 16:57:36 +00001193 break;
John McCallfc207f22013-03-07 21:37:12 +00001194 }
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001195
Yaxun Liu39195062017-08-04 18:16:31 +00001196 if (E->isOpenCL()) {
1197 LibCallName = std::string("__opencl") +
1198 StringRef(LibCallName).drop_front(1).str();
1199
1200 }
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001201 // Optimized functions have the size in their name.
1202 if (UseOptimizedLibcall)
1203 LibCallName += "_" + llvm::utostr(Size);
1204 // By default, assume we return a value of the atomic type.
1205 if (!HaveRetTy) {
1206 if (UseOptimizedLibcall) {
1207 // Value is returned directly.
David Majnemer0392cf82014-08-29 07:27:49 +00001208 // The function returns an appropriately sized integer type.
1209 RetTy = getContext().getIntTypeForBitwidth(
1210 getContext().toBits(sizeChars), /*Signed=*/false);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001211 } else {
1212 // Value is returned through parameter before the order.
1213 RetTy = getContext().VoidTy;
John McCall7f416cc2015-09-08 08:05:57 +00001214 Args.add(RValue::get(EmitCastToVoidPtr(Dest.getPointer())),
1215 getContext().VoidPtrTy);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001216 }
1217 }
John McCallfc207f22013-03-07 21:37:12 +00001218 // order is always the last parameter
1219 Args.add(RValue::get(Order),
1220 getContext().IntTy);
Yaxun Liu39195062017-08-04 18:16:31 +00001221 if (E->isOpenCL())
1222 Args.add(RValue::get(Scope), getContext().IntTy);
John McCallfc207f22013-03-07 21:37:12 +00001223
James Y Knight7aefb5b2015-11-12 18:37:29 +00001224 // PostOp is only needed for the atomic_*_fetch operations, and
1225 // thus is only needed for and implemented in the
1226 // UseOptimizedLibcall codepath.
Tim Northover5cf58762019-11-21 10:31:30 +00001227 assert(UseOptimizedLibcall || (!PostOp && !PostOpMinMax));
James Y Knight7aefb5b2015-11-12 18:37:29 +00001228
David Majnemer659be552014-11-25 23:44:32 +00001229 RValue Res = emitAtomicLibcall(*this, LibCallName, RetTy, Args);
1230 // The value is returned directly from the libcall.
Tim Northovercc2a6e02015-11-09 19:56:35 +00001231 if (E->isCmpXChg())
David Majnemer659be552014-11-25 23:44:32 +00001232 return Res;
Tim Northovercc2a6e02015-11-09 19:56:35 +00001233
1234 // The value is returned directly for optimized libcalls but the expr
1235 // provided an out-param.
1236 if (UseOptimizedLibcall && Res.getScalarVal()) {
David Majnemer659be552014-11-25 23:44:32 +00001237 llvm::Value *ResVal = Res.getScalarVal();
Tim Northover5cf58762019-11-21 10:31:30 +00001238 if (PostOpMinMax) {
1239 llvm::Value *LoadVal1 = Args[1].getRValue(*this).getScalarVal();
1240 ResVal = EmitPostAtomicMinMax(Builder, E->getOp(),
1241 E->getValueType()->isSignedIntegerType(),
1242 ResVal, LoadVal1);
1243 } else if (PostOp) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00001244 llvm::Value *LoadVal1 = Args[1].getRValue(*this).getScalarVal();
James Y Knight7aefb5b2015-11-12 18:37:29 +00001245 ResVal = Builder.CreateBinOp(PostOp, ResVal, LoadVal1);
1246 }
1247 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
1248 ResVal = Builder.CreateNot(ResVal);
1249
Tim Northovercc2a6e02015-11-09 19:56:35 +00001250 Builder.CreateStore(
1251 ResVal,
1252 Builder.CreateBitCast(Dest, ResVal->getType()->getPointerTo()));
David Majnemer659be552014-11-25 23:44:32 +00001253 }
Tim Northovercc2a6e02015-11-09 19:56:35 +00001254
1255 if (RValTy->isVoidType())
1256 return RValue::get(nullptr);
1257
1258 return convertTempToRValue(
1259 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo()),
1260 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001261 }
1262
1263 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
Yaxun Liu39195062017-08-04 18:16:31 +00001264 E->getOp() == AtomicExpr::AO__opencl_atomic_store ||
John McCallfc207f22013-03-07 21:37:12 +00001265 E->getOp() == AtomicExpr::AO__atomic_store ||
1266 E->getOp() == AtomicExpr::AO__atomic_store_n;
1267 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00001268 E->getOp() == AtomicExpr::AO__opencl_atomic_load ||
John McCallfc207f22013-03-07 21:37:12 +00001269 E->getOp() == AtomicExpr::AO__atomic_load ||
1270 E->getOp() == AtomicExpr::AO__atomic_load_n;
1271
John McCallfc207f22013-03-07 21:37:12 +00001272 if (isa<llvm::ConstantInt>(Order)) {
JF Bastiendda2cb12016-04-18 18:01:49 +00001273 auto ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
1274 // We should not ever get to a case where the ordering isn't a valid C ABI
1275 // value, but it's hard to enforce that in general.
1276 if (llvm::isValidAtomicOrderingCABI(ord))
1277 switch ((llvm::AtomicOrderingCABI)ord) {
1278 case llvm::AtomicOrderingCABI::relaxed:
1279 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001280 llvm::AtomicOrdering::Monotonic, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001281 break;
1282 case llvm::AtomicOrderingCABI::consume:
1283 case llvm::AtomicOrderingCABI::acquire:
1284 if (IsStore)
1285 break; // Avoid crashing on code with undefined behavior
1286 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001287 llvm::AtomicOrdering::Acquire, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001288 break;
1289 case llvm::AtomicOrderingCABI::release:
1290 if (IsLoad)
1291 break; // Avoid crashing on code with undefined behavior
1292 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001293 llvm::AtomicOrdering::Release, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001294 break;
1295 case llvm::AtomicOrderingCABI::acq_rel:
1296 if (IsLoad || IsStore)
1297 break; // Avoid crashing on code with undefined behavior
1298 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001299 llvm::AtomicOrdering::AcquireRelease, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001300 break;
1301 case llvm::AtomicOrderingCABI::seq_cst:
1302 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001303 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001304 break;
1305 }
David Majnemeree8d04d2014-12-12 08:16:09 +00001306 if (RValTy->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001307 return RValue::get(nullptr);
Tim Northovercc2a6e02015-11-09 19:56:35 +00001308
1309 return convertTempToRValue(
Yaxun Liu8ab5ab02017-10-17 14:19:29 +00001310 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1311 Dest.getAddressSpace())),
Tim Northovercc2a6e02015-11-09 19:56:35 +00001312 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001313 }
1314
1315 // Long case, when Order isn't obviously constant.
1316
1317 // Create all the relevant BB's
Craig Topper8a13c412014-05-21 05:09:00 +00001318 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
1319 *ReleaseBB = nullptr, *AcqRelBB = nullptr,
1320 *SeqCstBB = nullptr;
John McCallfc207f22013-03-07 21:37:12 +00001321 MonotonicBB = createBasicBlock("monotonic", CurFn);
1322 if (!IsStore)
1323 AcquireBB = createBasicBlock("acquire", CurFn);
1324 if (!IsLoad)
1325 ReleaseBB = createBasicBlock("release", CurFn);
1326 if (!IsLoad && !IsStore)
1327 AcqRelBB = createBasicBlock("acqrel", CurFn);
1328 SeqCstBB = createBasicBlock("seqcst", CurFn);
1329 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
1330
1331 // Create the switch for the split
1332 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
1333 // doesn't matter unless someone is crazy enough to use something that
1334 // doesn't fold to a constant for the ordering.
1335 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
1336 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
1337
1338 // Emit all the different atomics
1339 Builder.SetInsertPoint(MonotonicBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001340 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001341 llvm::AtomicOrdering::Monotonic, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001342 Builder.CreateBr(ContBB);
1343 if (!IsStore) {
1344 Builder.SetInsertPoint(AcquireBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001345 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001346 llvm::AtomicOrdering::Acquire, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001347 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001348 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
Tim Northover514fc612014-03-13 19:25:52 +00001349 AcquireBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001350 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
Tim Northover514fc612014-03-13 19:25:52 +00001351 AcquireBB);
John McCallfc207f22013-03-07 21:37:12 +00001352 }
1353 if (!IsLoad) {
1354 Builder.SetInsertPoint(ReleaseBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001355 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001356 llvm::AtomicOrdering::Release, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001357 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001358 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::release),
Tim Northover514fc612014-03-13 19:25:52 +00001359 ReleaseBB);
John McCallfc207f22013-03-07 21:37:12 +00001360 }
1361 if (!IsLoad && !IsStore) {
1362 Builder.SetInsertPoint(AcqRelBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001363 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001364 llvm::AtomicOrdering::AcquireRelease, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001365 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001366 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acq_rel),
Tim Northover514fc612014-03-13 19:25:52 +00001367 AcqRelBB);
John McCallfc207f22013-03-07 21:37:12 +00001368 }
1369 Builder.SetInsertPoint(SeqCstBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001370 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001371 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001372 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001373 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
Tim Northover514fc612014-03-13 19:25:52 +00001374 SeqCstBB);
John McCallfc207f22013-03-07 21:37:12 +00001375
1376 // Cleanup and return
1377 Builder.SetInsertPoint(ContBB);
David Majnemeree8d04d2014-12-12 08:16:09 +00001378 if (RValTy->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001379 return RValue::get(nullptr);
Tim Northovercc2a6e02015-11-09 19:56:35 +00001380
1381 assert(Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits());
1382 return convertTempToRValue(
Yaxun Liu8ab5ab02017-10-17 14:19:29 +00001383 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1384 Dest.getAddressSpace())),
Tim Northovercc2a6e02015-11-09 19:56:35 +00001385 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001386}
John McCalla8ec7eb2013-03-07 21:37:17 +00001387
John McCall7f416cc2015-09-08 08:05:57 +00001388Address AtomicInfo::emitCastToAtomicIntPointer(Address addr) const {
John McCalla8ec7eb2013-03-07 21:37:17 +00001389 unsigned addrspace =
John McCall7f416cc2015-09-08 08:05:57 +00001390 cast<llvm::PointerType>(addr.getPointer()->getType())->getAddressSpace();
John McCalla8ec7eb2013-03-07 21:37:17 +00001391 llvm::IntegerType *ty =
1392 llvm::IntegerType::get(CGF.getLLVMContext(), AtomicSizeInBits);
1393 return CGF.Builder.CreateBitCast(addr, ty->getPointerTo(addrspace));
1394}
1395
Tim Northovercc2a6e02015-11-09 19:56:35 +00001396Address AtomicInfo::convertToAtomicIntPointer(Address Addr) const {
1397 llvm::Type *Ty = Addr.getElementType();
1398 uint64_t SourceSizeInBits = CGF.CGM.getDataLayout().getTypeSizeInBits(Ty);
1399 if (SourceSizeInBits != AtomicSizeInBits) {
1400 Address Tmp = CreateTempAlloca();
1401 CGF.Builder.CreateMemCpy(Tmp, Addr,
1402 std::min(AtomicSizeInBits, SourceSizeInBits) / 8);
1403 Addr = Tmp;
1404 }
1405
1406 return emitCastToAtomicIntPointer(Addr);
1407}
1408
John McCall7f416cc2015-09-08 08:05:57 +00001409RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
1410 AggValueSlot resultSlot,
1411 SourceLocation loc,
1412 bool asValue) const {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001413 if (LVal.isSimple()) {
1414 if (EvaluationKind == TEK_Aggregate)
1415 return resultSlot.asRValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001416
Alexey Bataevb57056f2015-01-22 06:17:56 +00001417 // Drill into the padding structure if we have one.
1418 if (hasPadding())
James Y Knight751fe282019-02-09 22:22:28 +00001419 addr = CGF.Builder.CreateStructGEP(addr, 0);
John McCalla8ec7eb2013-03-07 21:37:17 +00001420
Alexey Bataevb57056f2015-01-22 06:17:56 +00001421 // Otherwise, just convert the temporary to an r-value using the
1422 // normal conversion routine.
1423 return CGF.convertTempToRValue(addr, getValueType(), loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001424 }
John McCall7f416cc2015-09-08 08:05:57 +00001425 if (!asValue)
Alexey Bataevb8329262015-02-27 06:33:30 +00001426 // Get RValue from temp memory as atomic for non-simple lvalues
John McCall7f416cc2015-09-08 08:05:57 +00001427 return RValue::get(CGF.Builder.CreateLoad(addr));
David Blaikie1ed728c2015-04-05 22:45:47 +00001428 if (LVal.isBitField())
John McCall7f416cc2015-09-08 08:05:57 +00001429 return CGF.EmitLoadOfBitfieldLValue(
1430 LValue::MakeBitfield(addr, LVal.getBitFieldInfo(), LVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001431 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001432 if (LVal.isVectorElt())
John McCall7f416cc2015-09-08 08:05:57 +00001433 return CGF.EmitLoadOfLValue(
1434 LValue::MakeVectorElt(addr, LVal.getVectorIdx(), LVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001435 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001436 assert(LVal.isExtVectorElt());
1437 return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
John McCall7f416cc2015-09-08 08:05:57 +00001438 addr, LVal.getExtVectorElts(), LVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001439 LVal.getBaseInfo(), TBAAAccessInfo()));
John McCalla8ec7eb2013-03-07 21:37:17 +00001440}
1441
Alexey Bataevb8329262015-02-27 06:33:30 +00001442RValue AtomicInfo::ConvertIntToValueOrAtomic(llvm::Value *IntVal,
1443 AggValueSlot ResultSlot,
1444 SourceLocation Loc,
1445 bool AsValue) const {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001446 // Try not to in some easy cases.
1447 assert(IntVal->getType()->isIntegerTy() && "Expected integer value");
Alexey Bataevb8329262015-02-27 06:33:30 +00001448 if (getEvaluationKind() == TEK_Scalar &&
1449 (((!LVal.isBitField() ||
1450 LVal.getBitFieldInfo().Size == ValueSizeInBits) &&
1451 !hasPadding()) ||
1452 !AsValue)) {
1453 auto *ValTy = AsValue
1454 ? CGF.ConvertTypeForMem(ValueTy)
John McCall7f416cc2015-09-08 08:05:57 +00001455 : getAtomicAddress().getType()->getPointerElementType();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001456 if (ValTy->isIntegerTy()) {
1457 assert(IntVal->getType() == ValTy && "Different integer types.");
David Majnemereeaec262015-02-14 02:18:14 +00001458 return RValue::get(CGF.EmitFromMemory(IntVal, ValueTy));
Alexey Bataev452d8e12014-12-15 05:25:25 +00001459 } else if (ValTy->isPointerTy())
1460 return RValue::get(CGF.Builder.CreateIntToPtr(IntVal, ValTy));
1461 else if (llvm::CastInst::isBitCastable(IntVal->getType(), ValTy))
1462 return RValue::get(CGF.Builder.CreateBitCast(IntVal, ValTy));
1463 }
1464
1465 // Create a temporary. This needs to be big enough to hold the
1466 // atomic integer.
John McCall7f416cc2015-09-08 08:05:57 +00001467 Address Temp = Address::invalid();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001468 bool TempIsVolatile = false;
Alexey Bataevb8329262015-02-27 06:33:30 +00001469 if (AsValue && getEvaluationKind() == TEK_Aggregate) {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001470 assert(!ResultSlot.isIgnored());
John McCall7f416cc2015-09-08 08:05:57 +00001471 Temp = ResultSlot.getAddress();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001472 TempIsVolatile = ResultSlot.isVolatile();
1473 } else {
Alexey Bataevb8329262015-02-27 06:33:30 +00001474 Temp = CreateTempAlloca();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001475 }
1476
1477 // Slam the integer into the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00001478 Address CastTemp = emitCastToAtomicIntPointer(Temp);
1479 CGF.Builder.CreateStore(IntVal, CastTemp)
Alexey Bataev452d8e12014-12-15 05:25:25 +00001480 ->setVolatile(TempIsVolatile);
1481
John McCall7f416cc2015-09-08 08:05:57 +00001482 return convertAtomicTempToRValue(Temp, ResultSlot, Loc, AsValue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001483}
1484
1485void AtomicInfo::EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
1486 llvm::AtomicOrdering AO, bool) {
1487 // void __atomic_load(size_t size, void *mem, void *return, int order);
1488 CallArgList Args;
1489 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001490 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001491 CGF.getContext().VoidPtrTy);
1492 Args.add(RValue::get(CGF.EmitCastToVoidPtr(AddForLoaded)),
1493 CGF.getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001494 Args.add(
1495 RValue::get(llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(AO))),
1496 CGF.getContext().IntTy);
Alexey Bataevb8329262015-02-27 06:33:30 +00001497 emitAtomicLibcall(CGF, "__atomic_load", CGF.getContext().VoidTy, Args);
1498}
1499
1500llvm::Value *AtomicInfo::EmitAtomicLoadOp(llvm::AtomicOrdering AO,
1501 bool IsVolatile) {
1502 // Okay, we're doing this natively.
John McCall7f416cc2015-09-08 08:05:57 +00001503 Address Addr = getAtomicAddressAsAtomicIntPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +00001504 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Addr, "atomic-load");
1505 Load->setAtomic(AO);
1506
1507 // Other decoration.
Alexey Bataevb8329262015-02-27 06:33:30 +00001508 if (IsVolatile)
1509 Load->setVolatile(true);
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001510 CGF.CGM.DecorateInstructionWithTBAA(Load, LVal.getTBAAInfo());
Alexey Bataevb8329262015-02-27 06:33:30 +00001511 return Load;
Alexey Bataev452d8e12014-12-15 05:25:25 +00001512}
1513
David Majnemera5b195a2015-02-14 01:35:12 +00001514/// An LValue is a candidate for having its loads and stores be made atomic if
1515/// we are operating under /volatile:ms *and* the LValue itself is volatile and
1516/// performing such an operation can be performed without a libcall.
1517bool CodeGenFunction::LValueIsSuitableForInlineAtomic(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001518 if (!CGM.getCodeGenOpts().MSVolatile) return false;
David Majnemera5b195a2015-02-14 01:35:12 +00001519 AtomicInfo AI(*this, LV);
1520 bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
1521 // An atomic is inline if we don't need to use a libcall.
1522 bool AtomicIsInline = !AI.shouldUseLibcall();
David Majnemerfc80b6e2016-01-22 16:36:44 +00001523 // MSVC doesn't seem to do this for types wider than a pointer.
David Majnemera38c9f12016-05-24 16:09:25 +00001524 if (getContext().getTypeSize(LV.getType()) >
David Majnemerfc80b6e2016-01-22 16:36:44 +00001525 getContext().getTypeSize(getContext().getIntPtrType()))
1526 return false;
David Majnemera38c9f12016-05-24 16:09:25 +00001527 return IsVolatile && AtomicIsInline;
David Majnemera5b195a2015-02-14 01:35:12 +00001528}
1529
1530RValue CodeGenFunction::EmitAtomicLoad(LValue LV, SourceLocation SL,
1531 AggValueSlot Slot) {
1532 llvm::AtomicOrdering AO;
1533 bool IsVolatile = LV.isVolatileQualified();
1534 if (LV.getType()->isAtomicType()) {
JF Bastien92f4ef12016-04-06 17:26:42 +00001535 AO = llvm::AtomicOrdering::SequentiallyConsistent;
David Majnemera5b195a2015-02-14 01:35:12 +00001536 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00001537 AO = llvm::AtomicOrdering::Acquire;
David Majnemera5b195a2015-02-14 01:35:12 +00001538 IsVolatile = true;
1539 }
1540 return EmitAtomicLoad(LV, SL, AO, IsVolatile, Slot);
1541}
1542
Alexey Bataevb8329262015-02-27 06:33:30 +00001543RValue AtomicInfo::EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
1544 bool AsValue, llvm::AtomicOrdering AO,
1545 bool IsVolatile) {
1546 // Check whether we should use a library call.
1547 if (shouldUseLibcall()) {
John McCall7f416cc2015-09-08 08:05:57 +00001548 Address TempAddr = Address::invalid();
Alexey Bataevb8329262015-02-27 06:33:30 +00001549 if (LVal.isSimple() && !ResultSlot.isIgnored()) {
1550 assert(getEvaluationKind() == TEK_Aggregate);
John McCall7f416cc2015-09-08 08:05:57 +00001551 TempAddr = ResultSlot.getAddress();
Alexey Bataevb8329262015-02-27 06:33:30 +00001552 } else
1553 TempAddr = CreateTempAlloca();
1554
John McCall7f416cc2015-09-08 08:05:57 +00001555 EmitAtomicLoadLibcall(TempAddr.getPointer(), AO, IsVolatile);
Alexey Bataevb8329262015-02-27 06:33:30 +00001556
1557 // Okay, turn that back into the original value or whole atomic (for
1558 // non-simple lvalues) type.
John McCall7f416cc2015-09-08 08:05:57 +00001559 return convertAtomicTempToRValue(TempAddr, ResultSlot, Loc, AsValue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001560 }
1561
1562 // Okay, we're doing this natively.
1563 auto *Load = EmitAtomicLoadOp(AO, IsVolatile);
1564
1565 // If we're ignoring an aggregate return, don't do anything.
1566 if (getEvaluationKind() == TEK_Aggregate && ResultSlot.isIgnored())
John McCall7f416cc2015-09-08 08:05:57 +00001567 return RValue::getAggregate(Address::invalid(), false);
Alexey Bataevb8329262015-02-27 06:33:30 +00001568
1569 // Okay, turn that back into the original value or atomic (for non-simple
1570 // lvalues) type.
1571 return ConvertIntToValueOrAtomic(Load, ResultSlot, Loc, AsValue);
1572}
1573
John McCalla8ec7eb2013-03-07 21:37:17 +00001574/// Emit a load from an l-value of atomic type. Note that the r-value
1575/// we produce is an r-value of the atomic *value* type.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001576RValue CodeGenFunction::EmitAtomicLoad(LValue src, SourceLocation loc,
David Majnemera5b195a2015-02-14 01:35:12 +00001577 llvm::AtomicOrdering AO, bool IsVolatile,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001578 AggValueSlot resultSlot) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001579 AtomicInfo Atomics(*this, src);
1580 return Atomics.EmitAtomicLoad(resultSlot, loc, /*AsValue=*/true, AO,
1581 IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001582}
1583
John McCalla8ec7eb2013-03-07 21:37:17 +00001584/// Copy an r-value into memory as part of storing to an atomic type.
1585/// This needs to create a bit-pattern suitable for atomic operations.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001586void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
1587 assert(LVal.isSimple());
John McCalla8ec7eb2013-03-07 21:37:17 +00001588 // If we have an r-value, the rvalue should be of the atomic type,
1589 // which means that the caller is responsible for having zeroed
1590 // any padding. Just do an aggregate copy of that type.
1591 if (rvalue.isAggregate()) {
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001592 LValue Dest = CGF.MakeAddrLValue(getAtomicAddress(), getAtomicType());
1593 LValue Src = CGF.MakeAddrLValue(rvalue.getAggregateAddress(),
1594 getAtomicType());
1595 bool IsVolatile = rvalue.isVolatileQualified() ||
1596 LVal.isVolatileQualified();
Richard Smithe78fac52018-04-05 20:52:58 +00001597 CGF.EmitAggregateCopy(Dest, Src, getAtomicType(),
1598 AggValueSlot::DoesNotOverlap, IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001599 return;
1600 }
1601
1602 // Okay, otherwise we're copying stuff.
1603
1604 // Zero out the buffer if necessary.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001605 emitMemSetZeroIfNecessary();
John McCalla8ec7eb2013-03-07 21:37:17 +00001606
1607 // Drill past the padding if present.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001608 LValue TempLVal = projectValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001609
1610 // Okay, store the rvalue in.
1611 if (rvalue.isScalar()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001612 CGF.EmitStoreOfScalar(rvalue.getScalarVal(), TempLVal, /*init*/ true);
John McCalla8ec7eb2013-03-07 21:37:17 +00001613 } else {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001614 CGF.EmitStoreOfComplex(rvalue.getComplexVal(), TempLVal, /*init*/ true);
John McCalla8ec7eb2013-03-07 21:37:17 +00001615 }
1616}
1617
1618
1619/// Materialize an r-value into memory for the purposes of storing it
1620/// to an atomic type.
John McCall7f416cc2015-09-08 08:05:57 +00001621Address AtomicInfo::materializeRValue(RValue rvalue) const {
John McCalla8ec7eb2013-03-07 21:37:17 +00001622 // Aggregate r-values are already in memory, and EmitAtomicStore
1623 // requires them to be values of the atomic type.
1624 if (rvalue.isAggregate())
John McCall7f416cc2015-09-08 08:05:57 +00001625 return rvalue.getAggregateAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +00001626
1627 // Otherwise, make a temporary and materialize into it.
John McCall7f416cc2015-09-08 08:05:57 +00001628 LValue TempLV = CGF.MakeAddrLValue(CreateTempAlloca(), getAtomicType());
Alexey Bataevb8329262015-02-27 06:33:30 +00001629 AtomicInfo Atomics(CGF, TempLV);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001630 Atomics.emitCopyIntoMemory(rvalue);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001631 return TempLV.getAddress(CGF);
John McCalla8ec7eb2013-03-07 21:37:17 +00001632}
1633
Alexey Bataev452d8e12014-12-15 05:25:25 +00001634llvm::Value *AtomicInfo::convertRValueToInt(RValue RVal) const {
1635 // If we've got a scalar value of the right size, try to avoid going
1636 // through memory.
Alexey Bataevb8329262015-02-27 06:33:30 +00001637 if (RVal.isScalar() && (!hasPadding() || !LVal.isSimple())) {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001638 llvm::Value *Value = RVal.getScalarVal();
1639 if (isa<llvm::IntegerType>(Value->getType()))
Alexey Bataevb4505a72015-03-30 05:20:59 +00001640 return CGF.EmitToMemory(Value, ValueTy);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001641 else {
Alexey Bataevb8329262015-02-27 06:33:30 +00001642 llvm::IntegerType *InputIntTy = llvm::IntegerType::get(
1643 CGF.getLLVMContext(),
1644 LVal.isSimple() ? getValueSizeInBits() : getAtomicSizeInBits());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001645 if (isa<llvm::PointerType>(Value->getType()))
1646 return CGF.Builder.CreatePtrToInt(Value, InputIntTy);
1647 else if (llvm::BitCastInst::isBitCastable(Value->getType(), InputIntTy))
1648 return CGF.Builder.CreateBitCast(Value, InputIntTy);
1649 }
1650 }
1651 // Otherwise, we need to go through memory.
1652 // Put the r-value in memory.
John McCall7f416cc2015-09-08 08:05:57 +00001653 Address Addr = materializeRValue(RVal);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001654
1655 // Cast the temporary to the atomic int type and pull a value out.
1656 Addr = emitCastToAtomicIntPointer(Addr);
John McCall7f416cc2015-09-08 08:05:57 +00001657 return CGF.Builder.CreateLoad(Addr);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001658}
1659
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001660std::pair<llvm::Value *, llvm::Value *> AtomicInfo::EmitAtomicCompareExchangeOp(
1661 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
1662 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001663 // Do the atomic store.
John McCall7f416cc2015-09-08 08:05:57 +00001664 Address Addr = getAtomicAddressAsAtomicIntPointer();
1665 auto *Inst = CGF.Builder.CreateAtomicCmpXchg(Addr.getPointer(),
1666 ExpectedVal, DesiredVal,
Alexey Bataevb4505a72015-03-30 05:20:59 +00001667 Success, Failure);
Alexey Bataevb8329262015-02-27 06:33:30 +00001668 // Other decoration.
1669 Inst->setVolatile(LVal.isVolatileQualified());
1670 Inst->setWeak(IsWeak);
1671
1672 // Okay, turn that back into the original value type.
1673 auto *PreviousVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/0);
1674 auto *SuccessFailureVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/1);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001675 return std::make_pair(PreviousVal, SuccessFailureVal);
Alexey Bataevb8329262015-02-27 06:33:30 +00001676}
1677
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001678llvm::Value *
1679AtomicInfo::EmitAtomicCompareExchangeLibcall(llvm::Value *ExpectedAddr,
1680 llvm::Value *DesiredAddr,
Alexey Bataevb8329262015-02-27 06:33:30 +00001681 llvm::AtomicOrdering Success,
1682 llvm::AtomicOrdering Failure) {
1683 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
1684 // void *desired, int success, int failure);
1685 CallArgList Args;
1686 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001687 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001688 CGF.getContext().VoidPtrTy);
1689 Args.add(RValue::get(CGF.EmitCastToVoidPtr(ExpectedAddr)),
1690 CGF.getContext().VoidPtrTy);
1691 Args.add(RValue::get(CGF.EmitCastToVoidPtr(DesiredAddr)),
1692 CGF.getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001693 Args.add(RValue::get(
1694 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Success))),
Alexey Bataevb8329262015-02-27 06:33:30 +00001695 CGF.getContext().IntTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001696 Args.add(RValue::get(
1697 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Failure))),
Alexey Bataevb8329262015-02-27 06:33:30 +00001698 CGF.getContext().IntTy);
1699 auto SuccessFailureRVal = emitAtomicLibcall(CGF, "__atomic_compare_exchange",
1700 CGF.getContext().BoolTy, Args);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001701
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001702 return SuccessFailureRVal.getScalarVal();
Alexey Bataevb8329262015-02-27 06:33:30 +00001703}
1704
Alexey Bataevb4505a72015-03-30 05:20:59 +00001705std::pair<RValue, llvm::Value *> AtomicInfo::EmitAtomicCompareExchange(
Alexey Bataevb8329262015-02-27 06:33:30 +00001706 RValue Expected, RValue Desired, llvm::AtomicOrdering Success,
1707 llvm::AtomicOrdering Failure, bool IsWeak) {
JF Bastiendd11ee72016-04-06 23:37:36 +00001708 if (isStrongerThan(Failure, Success))
1709 // Don't assert on undefined behavior "failure argument shall be no stronger
1710 // than the success argument".
Alexey Bataevb8329262015-02-27 06:33:30 +00001711 Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(Success);
1712
1713 // Check whether we should use a library call.
1714 if (shouldUseLibcall()) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001715 // Produce a source address.
John McCall7f416cc2015-09-08 08:05:57 +00001716 Address ExpectedAddr = materializeRValue(Expected);
1717 Address DesiredAddr = materializeRValue(Desired);
1718 auto *Res = EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1719 DesiredAddr.getPointer(),
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001720 Success, Failure);
1721 return std::make_pair(
John McCall7f416cc2015-09-08 08:05:57 +00001722 convertAtomicTempToRValue(ExpectedAddr, AggValueSlot::ignored(),
1723 SourceLocation(), /*AsValue=*/false),
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001724 Res);
Alexey Bataevb8329262015-02-27 06:33:30 +00001725 }
1726
1727 // If we've got a scalar value of the right size, try to avoid going
1728 // through memory.
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001729 auto *ExpectedVal = convertRValueToInt(Expected);
1730 auto *DesiredVal = convertRValueToInt(Desired);
1731 auto Res = EmitAtomicCompareExchangeOp(ExpectedVal, DesiredVal, Success,
1732 Failure, IsWeak);
1733 return std::make_pair(
1734 ConvertIntToValueOrAtomic(Res.first, AggValueSlot::ignored(),
1735 SourceLocation(), /*AsValue=*/false),
1736 Res.second);
1737}
1738
1739static void
1740EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal,
1741 const llvm::function_ref<RValue(RValue)> &UpdateOp,
John McCall7f416cc2015-09-08 08:05:57 +00001742 Address DesiredAddr) {
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001743 RValue UpRVal;
1744 LValue AtomicLVal = Atomics.getAtomicLValue();
1745 LValue DesiredLVal;
1746 if (AtomicLVal.isSimple()) {
1747 UpRVal = OldRVal;
John McCall7f416cc2015-09-08 08:05:57 +00001748 DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001749 } else {
Amy Huang144a43a22019-04-03 22:19:07 +00001750 // Build new lvalue for temp address.
John McCall7f416cc2015-09-08 08:05:57 +00001751 Address Ptr = Atomics.materializeRValue(OldRVal);
1752 LValue UpdateLVal;
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001753 if (AtomicLVal.isBitField()) {
1754 UpdateLVal =
1755 LValue::MakeBitfield(Ptr, AtomicLVal.getBitFieldInfo(),
John McCall7f416cc2015-09-08 08:05:57 +00001756 AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001757 AtomicLVal.getBaseInfo(),
1758 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001759 DesiredLVal =
1760 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001761 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1762 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001763 } else if (AtomicLVal.isVectorElt()) {
1764 UpdateLVal = LValue::MakeVectorElt(Ptr, AtomicLVal.getVectorIdx(),
1765 AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001766 AtomicLVal.getBaseInfo(),
1767 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001768 DesiredLVal = LValue::MakeVectorElt(
1769 DesiredAddr, AtomicLVal.getVectorIdx(), AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001770 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001771 } else {
1772 assert(AtomicLVal.isExtVectorElt());
1773 UpdateLVal = LValue::MakeExtVectorElt(Ptr, AtomicLVal.getExtVectorElts(),
1774 AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001775 AtomicLVal.getBaseInfo(),
1776 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001777 DesiredLVal = LValue::MakeExtVectorElt(
1778 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001779 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001780 }
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001781 UpRVal = CGF.EmitLoadOfLValue(UpdateLVal, SourceLocation());
1782 }
Amy Huang144a43a22019-04-03 22:19:07 +00001783 // Store new value in the corresponding memory area.
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001784 RValue NewRVal = UpdateOp(UpRVal);
1785 if (NewRVal.isScalar()) {
1786 CGF.EmitStoreThroughLValue(NewRVal, DesiredLVal);
1787 } else {
1788 assert(NewRVal.isComplex());
1789 CGF.EmitStoreOfComplex(NewRVal.getComplexVal(), DesiredLVal,
1790 /*isInit=*/false);
1791 }
1792}
1793
1794void AtomicInfo::EmitAtomicUpdateLibcall(
1795 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1796 bool IsVolatile) {
1797 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1798
John McCall7f416cc2015-09-08 08:05:57 +00001799 Address ExpectedAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001800
John McCall7f416cc2015-09-08 08:05:57 +00001801 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001802 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1803 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1804 CGF.EmitBlock(ContBB);
John McCall7f416cc2015-09-08 08:05:57 +00001805 Address DesiredAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001806 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001807 requiresMemSetZero(getAtomicAddress().getElementType())) {
1808 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1809 CGF.Builder.CreateStore(OldVal, DesiredAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001810 }
John McCall7f416cc2015-09-08 08:05:57 +00001811 auto OldRVal = convertAtomicTempToRValue(ExpectedAddr,
1812 AggValueSlot::ignored(),
1813 SourceLocation(), /*AsValue=*/false);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001814 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, DesiredAddr);
1815 auto *Res =
John McCall7f416cc2015-09-08 08:05:57 +00001816 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1817 DesiredAddr.getPointer(),
1818 AO, Failure);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001819 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1820 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1821}
1822
1823void AtomicInfo::EmitAtomicUpdateOp(
1824 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1825 bool IsVolatile) {
1826 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1827
1828 // Do the atomic load.
1829 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1830 // For non-simple lvalues perform compare-and-swap procedure.
1831 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1832 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1833 auto *CurBB = CGF.Builder.GetInsertBlock();
1834 CGF.EmitBlock(ContBB);
1835 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1836 /*NumReservedValues=*/2);
1837 PHI->addIncoming(OldVal, CurBB);
John McCall7f416cc2015-09-08 08:05:57 +00001838 Address NewAtomicAddr = CreateTempAlloca();
1839 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001840 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001841 requiresMemSetZero(getAtomicAddress().getElementType())) {
1842 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001843 }
1844 auto OldRVal = ConvertIntToValueOrAtomic(PHI, AggValueSlot::ignored(),
1845 SourceLocation(), /*AsValue=*/false);
1846 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, NewAtomicAddr);
John McCall7f416cc2015-09-08 08:05:57 +00001847 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
Amy Huang144a43a22019-04-03 22:19:07 +00001848 // Try to write new value using cmpxchg operation.
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001849 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1850 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1851 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1852 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1853}
1854
1855static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics,
John McCall7f416cc2015-09-08 08:05:57 +00001856 RValue UpdateRVal, Address DesiredAddr) {
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001857 LValue AtomicLVal = Atomics.getAtomicLValue();
1858 LValue DesiredLVal;
Amy Huang144a43a22019-04-03 22:19:07 +00001859 // Build new lvalue for temp address.
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001860 if (AtomicLVal.isBitField()) {
1861 DesiredLVal =
1862 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001863 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1864 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001865 } else if (AtomicLVal.isVectorElt()) {
1866 DesiredLVal =
1867 LValue::MakeVectorElt(DesiredAddr, AtomicLVal.getVectorIdx(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001868 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1869 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001870 } else {
1871 assert(AtomicLVal.isExtVectorElt());
1872 DesiredLVal = LValue::MakeExtVectorElt(
1873 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001874 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001875 }
Amy Huang144a43a22019-04-03 22:19:07 +00001876 // Store new value in the corresponding memory area.
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001877 assert(UpdateRVal.isScalar());
1878 CGF.EmitStoreThroughLValue(UpdateRVal, DesiredLVal);
1879}
1880
1881void AtomicInfo::EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
1882 RValue UpdateRVal, bool IsVolatile) {
1883 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1884
John McCall7f416cc2015-09-08 08:05:57 +00001885 Address ExpectedAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001886
John McCall7f416cc2015-09-08 08:05:57 +00001887 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001888 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1889 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1890 CGF.EmitBlock(ContBB);
John McCall7f416cc2015-09-08 08:05:57 +00001891 Address DesiredAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001892 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001893 requiresMemSetZero(getAtomicAddress().getElementType())) {
1894 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1895 CGF.Builder.CreateStore(OldVal, DesiredAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001896 }
1897 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, DesiredAddr);
1898 auto *Res =
John McCall7f416cc2015-09-08 08:05:57 +00001899 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1900 DesiredAddr.getPointer(),
1901 AO, Failure);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001902 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1903 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1904}
1905
1906void AtomicInfo::EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRVal,
1907 bool IsVolatile) {
1908 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1909
1910 // Do the atomic load.
1911 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1912 // For non-simple lvalues perform compare-and-swap procedure.
1913 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1914 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1915 auto *CurBB = CGF.Builder.GetInsertBlock();
1916 CGF.EmitBlock(ContBB);
1917 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1918 /*NumReservedValues=*/2);
1919 PHI->addIncoming(OldVal, CurBB);
John McCall7f416cc2015-09-08 08:05:57 +00001920 Address NewAtomicAddr = CreateTempAlloca();
1921 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001922 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001923 requiresMemSetZero(getAtomicAddress().getElementType())) {
1924 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001925 }
1926 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, NewAtomicAddr);
John McCall7f416cc2015-09-08 08:05:57 +00001927 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
Amy Huang144a43a22019-04-03 22:19:07 +00001928 // Try to write new value using cmpxchg operation.
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001929 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1930 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1931 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1932 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1933}
1934
1935void AtomicInfo::EmitAtomicUpdate(
1936 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1937 bool IsVolatile) {
1938 if (shouldUseLibcall()) {
1939 EmitAtomicUpdateLibcall(AO, UpdateOp, IsVolatile);
1940 } else {
1941 EmitAtomicUpdateOp(AO, UpdateOp, IsVolatile);
1942 }
1943}
1944
1945void AtomicInfo::EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
1946 bool IsVolatile) {
1947 if (shouldUseLibcall()) {
1948 EmitAtomicUpdateLibcall(AO, UpdateRVal, IsVolatile);
1949 } else {
1950 EmitAtomicUpdateOp(AO, UpdateRVal, IsVolatile);
1951 }
Alexey Bataevb8329262015-02-27 06:33:30 +00001952}
1953
David Majnemera5b195a2015-02-14 01:35:12 +00001954void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue lvalue,
1955 bool isInit) {
1956 bool IsVolatile = lvalue.isVolatileQualified();
1957 llvm::AtomicOrdering AO;
1958 if (lvalue.getType()->isAtomicType()) {
JF Bastien92f4ef12016-04-06 17:26:42 +00001959 AO = llvm::AtomicOrdering::SequentiallyConsistent;
David Majnemera5b195a2015-02-14 01:35:12 +00001960 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00001961 AO = llvm::AtomicOrdering::Release;
David Majnemera5b195a2015-02-14 01:35:12 +00001962 IsVolatile = true;
1963 }
1964 return EmitAtomicStore(rvalue, lvalue, AO, IsVolatile, isInit);
1965}
1966
John McCalla8ec7eb2013-03-07 21:37:17 +00001967/// Emit a store to an l-value of atomic type.
1968///
1969/// Note that the r-value is expected to be an r-value *of the atomic
1970/// type*; this means that for aggregate r-values, it should include
1971/// storage for any padding that was necessary.
David Majnemera5b195a2015-02-14 01:35:12 +00001972void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue dest,
1973 llvm::AtomicOrdering AO, bool IsVolatile,
1974 bool isInit) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001975 // If this is an aggregate r-value, it should agree in type except
1976 // maybe for address-space qualification.
1977 assert(!rvalue.isAggregate() ||
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001978 rvalue.getAggregateAddress().getElementType() ==
1979 dest.getAddress(*this).getElementType());
John McCalla8ec7eb2013-03-07 21:37:17 +00001980
1981 AtomicInfo atomics(*this, dest);
Alexey Bataevb8329262015-02-27 06:33:30 +00001982 LValue LVal = atomics.getAtomicLValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001983
1984 // If this is an initialization, just put the value there normally.
Alexey Bataevb8329262015-02-27 06:33:30 +00001985 if (LVal.isSimple()) {
1986 if (isInit) {
1987 atomics.emitCopyIntoMemory(rvalue);
1988 return;
1989 }
1990
1991 // Check whether we should use a library call.
1992 if (atomics.shouldUseLibcall()) {
1993 // Produce a source address.
John McCall7f416cc2015-09-08 08:05:57 +00001994 Address srcAddr = atomics.materializeRValue(rvalue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001995
1996 // void __atomic_store(size_t size, void *mem, void *val, int order)
1997 CallArgList args;
1998 args.add(RValue::get(atomics.getAtomicSizeValue()),
1999 getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00002000 args.add(RValue::get(EmitCastToVoidPtr(atomics.getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00002001 getContext().VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002002 args.add(RValue::get(EmitCastToVoidPtr(srcAddr.getPointer())),
2003 getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00002004 args.add(
2005 RValue::get(llvm::ConstantInt::get(IntTy, (int)llvm::toCABI(AO))),
2006 getContext().IntTy);
Alexey Bataevb8329262015-02-27 06:33:30 +00002007 emitAtomicLibcall(*this, "__atomic_store", getContext().VoidTy, args);
2008 return;
2009 }
2010
2011 // Okay, we're doing this natively.
2012 llvm::Value *intValue = atomics.convertRValueToInt(rvalue);
2013
2014 // Do the atomic store.
John McCall7f416cc2015-09-08 08:05:57 +00002015 Address addr =
Alexey Bataevb8329262015-02-27 06:33:30 +00002016 atomics.emitCastToAtomicIntPointer(atomics.getAtomicAddress());
2017 intValue = Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00002018 intValue, addr.getElementType(), /*isSigned=*/false);
Alexey Bataevb8329262015-02-27 06:33:30 +00002019 llvm::StoreInst *store = Builder.CreateStore(intValue, addr);
2020
2021 // Initializations don't need to be atomic.
2022 if (!isInit)
2023 store->setAtomic(AO);
2024
2025 // Other decoration.
Alexey Bataevb8329262015-02-27 06:33:30 +00002026 if (IsVolatile)
2027 store->setVolatile(true);
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00002028 CGM.DecorateInstructionWithTBAA(store, dest.getTBAAInfo());
John McCalla8ec7eb2013-03-07 21:37:17 +00002029 return;
2030 }
2031
Alexey Bataevf0ab5532015-05-15 08:36:34 +00002032 // Emit simple atomic update operation.
2033 atomics.EmitAtomicUpdate(AO, rvalue, IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00002034}
2035
Alexey Bataev452d8e12014-12-15 05:25:25 +00002036/// Emit a compare-and-exchange op for atomic type.
2037///
Alexey Bataevb4505a72015-03-30 05:20:59 +00002038std::pair<RValue, llvm::Value *> CodeGenFunction::EmitAtomicCompareExchange(
Alexey Bataev452d8e12014-12-15 05:25:25 +00002039 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2040 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak,
2041 AggValueSlot Slot) {
2042 // If this is an aggregate r-value, it should agree in type except
2043 // maybe for address-space qualification.
2044 assert(!Expected.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00002045 Expected.getAggregateAddress().getElementType() ==
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002046 Obj.getAddress(*this).getElementType());
Alexey Bataev452d8e12014-12-15 05:25:25 +00002047 assert(!Desired.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00002048 Desired.getAggregateAddress().getElementType() ==
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002049 Obj.getAddress(*this).getElementType());
Alexey Bataev452d8e12014-12-15 05:25:25 +00002050 AtomicInfo Atomics(*this, Obj);
2051
Alexey Bataevb4505a72015-03-30 05:20:59 +00002052 return Atomics.EmitAtomicCompareExchange(Expected, Desired, Success, Failure,
2053 IsWeak);
2054}
2055
2056void CodeGenFunction::EmitAtomicUpdate(
2057 LValue LVal, llvm::AtomicOrdering AO,
Alexey Bataevf0ab5532015-05-15 08:36:34 +00002058 const llvm::function_ref<RValue(RValue)> &UpdateOp, bool IsVolatile) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00002059 AtomicInfo Atomics(*this, LVal);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00002060 Atomics.EmitAtomicUpdate(AO, UpdateOp, IsVolatile);
Alexey Bataev452d8e12014-12-15 05:25:25 +00002061}
2062
John McCalla8ec7eb2013-03-07 21:37:17 +00002063void CodeGenFunction::EmitAtomicInit(Expr *init, LValue dest) {
2064 AtomicInfo atomics(*this, dest);
2065
2066 switch (atomics.getEvaluationKind()) {
2067 case TEK_Scalar: {
2068 llvm::Value *value = EmitScalarExpr(init);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002069 atomics.emitCopyIntoMemory(RValue::get(value));
John McCalla8ec7eb2013-03-07 21:37:17 +00002070 return;
2071 }
2072
2073 case TEK_Complex: {
2074 ComplexPairTy value = EmitComplexExpr(init);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002075 atomics.emitCopyIntoMemory(RValue::getComplex(value));
John McCalla8ec7eb2013-03-07 21:37:17 +00002076 return;
2077 }
2078
2079 case TEK_Aggregate: {
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002080 // Fix up the destination if the initializer isn't an expression
2081 // of atomic type.
2082 bool Zeroed = false;
John McCalla8ec7eb2013-03-07 21:37:17 +00002083 if (!init->getType()->isAtomicType()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002084 Zeroed = atomics.emitMemSetZeroIfNecessary();
2085 dest = atomics.projectValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00002086 }
2087
2088 // Evaluate the expression directly into the destination.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002089 AggValueSlot slot = AggValueSlot::forLValue(
2090 dest, *this, AggValueSlot::IsNotDestructed,
2091 AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
2092 AggValueSlot::DoesNotOverlap,
2093 Zeroed ? AggValueSlot::IsZeroed : AggValueSlot::IsNotZeroed);
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002094
John McCalla8ec7eb2013-03-07 21:37:17 +00002095 EmitAggExpr(init, slot);
2096 return;
2097 }
2098 }
2099 llvm_unreachable("bad evaluation kind");
2100}