blob: 20e59155942a6cab0821e8a135e6768f1a094906 [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;
38 CharUnits LValueAlign;
39 TypeEvaluationKind EvaluationKind;
40 bool UseLibcall;
Alexey Bataevb57056f2015-01-22 06:17:56 +000041 LValue LVal;
42 CGBitFieldInfo BFI;
John McCalla8ec7eb2013-03-07 21:37:17 +000043 public:
Alexey Bataevb57056f2015-01-22 06:17:56 +000044 AtomicInfo(CodeGenFunction &CGF, LValue &lvalue)
45 : CGF(CGF), AtomicSizeInBits(0), ValueSizeInBits(0),
46 EvaluationKind(TEK_Scalar), UseLibcall(true) {
47 assert(!lvalue.isGlobalReg());
John McCalla8ec7eb2013-03-07 21:37:17 +000048 ASTContext &C = CGF.getContext();
Alexey Bataevb57056f2015-01-22 06:17:56 +000049 if (lvalue.isSimple()) {
50 AtomicTy = lvalue.getType();
51 if (auto *ATy = AtomicTy->getAs<AtomicType>())
52 ValueTy = ATy->getValueType();
53 else
54 ValueTy = AtomicTy;
55 EvaluationKind = CGF.getEvaluationKind(ValueTy);
John McCalla8ec7eb2013-03-07 21:37:17 +000056
Alexey Bataevb57056f2015-01-22 06:17:56 +000057 uint64_t ValueAlignInBits;
58 uint64_t AtomicAlignInBits;
59 TypeInfo ValueTI = C.getTypeInfo(ValueTy);
60 ValueSizeInBits = ValueTI.Width;
61 ValueAlignInBits = ValueTI.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +000062
Alexey Bataevb57056f2015-01-22 06:17:56 +000063 TypeInfo AtomicTI = C.getTypeInfo(AtomicTy);
64 AtomicSizeInBits = AtomicTI.Width;
65 AtomicAlignInBits = AtomicTI.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +000066
Alexey Bataevb57056f2015-01-22 06:17:56 +000067 assert(ValueSizeInBits <= AtomicSizeInBits);
68 assert(ValueAlignInBits <= AtomicAlignInBits);
John McCalla8ec7eb2013-03-07 21:37:17 +000069
Alexey Bataevb57056f2015-01-22 06:17:56 +000070 AtomicAlign = C.toCharUnitsFromBits(AtomicAlignInBits);
71 ValueAlign = C.toCharUnitsFromBits(ValueAlignInBits);
72 if (lvalue.getAlignment().isZero())
73 lvalue.setAlignment(AtomicAlign);
John McCalla8ec7eb2013-03-07 21:37:17 +000074
Alexey Bataevb57056f2015-01-22 06:17:56 +000075 LVal = lvalue;
76 } else if (lvalue.isBitField()) {
Alexey Bataevb8329262015-02-27 06:33:30 +000077 ValueTy = lvalue.getType();
78 ValueSizeInBits = C.getTypeSize(ValueTy);
Alexey Bataevb57056f2015-01-22 06:17:56 +000079 auto &OrigBFI = lvalue.getBitFieldInfo();
80 auto Offset = OrigBFI.Offset % C.toBits(lvalue.getAlignment());
81 AtomicSizeInBits = C.toBits(
82 C.toCharUnitsFromBits(Offset + OrigBFI.Size + C.getCharWidth() - 1)
Rui Ueyama83aa9792016-01-14 21:00:27 +000083 .alignTo(lvalue.getAlignment()));
John McCall7f416cc2015-09-08 08:05:57 +000084 auto VoidPtrAddr = CGF.EmitCastToVoidPtr(lvalue.getBitFieldPointer());
Alexey Bataevb57056f2015-01-22 06:17:56 +000085 auto OffsetInChars =
86 (C.toCharUnitsFromBits(OrigBFI.Offset) / lvalue.getAlignment()) *
87 lvalue.getAlignment();
88 VoidPtrAddr = CGF.Builder.CreateConstGEP1_64(
89 VoidPtrAddr, OffsetInChars.getQuantity());
90 auto Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
91 VoidPtrAddr,
92 CGF.Builder.getIntNTy(AtomicSizeInBits)->getPointerTo(),
93 "atomic_bitfield_base");
94 BFI = OrigBFI;
95 BFI.Offset = Offset;
96 BFI.StorageSize = AtomicSizeInBits;
Ulrich Weigand03ce2a12015-07-10 17:30:00 +000097 BFI.StorageOffset += OffsetInChars;
John McCall7f416cc2015-09-08 08:05:57 +000098 LVal = LValue::MakeBitfield(Address(Addr, lvalue.getAlignment()),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +000099 BFI, lvalue.getType(), lvalue.getBaseInfo(),
100 lvalue.getTBAAInfo());
Alexey Bataevb8329262015-02-27 06:33:30 +0000101 AtomicTy = C.getIntTypeForBitwidth(AtomicSizeInBits, OrigBFI.IsSigned);
102 if (AtomicTy.isNull()) {
103 llvm::APInt Size(
104 /*numBits=*/32,
105 C.toCharUnitsFromBits(AtomicSizeInBits).getQuantity());
106 AtomicTy = C.getConstantArrayType(C.CharTy, Size, ArrayType::Normal,
107 /*IndexTypeQuals=*/0);
108 }
109 AtomicAlign = ValueAlign = lvalue.getAlignment();
Alexey Bataevb57056f2015-01-22 06:17:56 +0000110 } else if (lvalue.isVectorElt()) {
Alexey Bataevb8329262015-02-27 06:33:30 +0000111 ValueTy = lvalue.getType()->getAs<VectorType>()->getElementType();
112 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; }
135 CharUnits getValueAlignment() const { return ValueAlign; }
136 uint64_t getAtomicSizeInBits() const { return AtomicSizeInBits; }
Alexey Bataev452d8e12014-12-15 05:25:25 +0000137 uint64_t getValueSizeInBits() const { return ValueSizeInBits; }
John McCalla8ec7eb2013-03-07 21:37:17 +0000138 TypeEvaluationKind getEvaluationKind() const { return EvaluationKind; }
139 bool shouldUseLibcall() const { return UseLibcall; }
Alexey Bataevb57056f2015-01-22 06:17:56 +0000140 const LValue &getAtomicLValue() const { return LVal; }
John McCall7f416cc2015-09-08 08:05:57 +0000141 llvm::Value *getAtomicPointer() const {
Alexey Bataevb8329262015-02-27 06:33:30 +0000142 if (LVal.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000143 return LVal.getPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000144 else if (LVal.isBitField())
John McCall7f416cc2015-09-08 08:05:57 +0000145 return LVal.getBitFieldPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000146 else if (LVal.isVectorElt())
John McCall7f416cc2015-09-08 08:05:57 +0000147 return LVal.getVectorPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000148 assert(LVal.isExtVectorElt());
John McCall7f416cc2015-09-08 08:05:57 +0000149 return LVal.getExtVectorPointer();
150 }
151 Address getAtomicAddress() const {
152 return Address(getAtomicPointer(), getAtomicAlignment());
153 }
154
155 Address getAtomicAddressAsAtomicIntPointer() const {
156 return emitCastToAtomicIntPointer(getAtomicAddress());
Alexey Bataevb8329262015-02-27 06:33:30 +0000157 }
John McCalla8ec7eb2013-03-07 21:37:17 +0000158
159 /// Is the atomic size larger than the underlying value type?
160 ///
161 /// Note that the absence of padding does not mean that atomic
162 /// objects are completely interchangeable with non-atomic
163 /// objects: we might have promoted the alignment of a type
164 /// without making it bigger.
165 bool hasPadding() const {
166 return (ValueSizeInBits != AtomicSizeInBits);
167 }
168
Alexey Bataevb57056f2015-01-22 06:17:56 +0000169 bool emitMemSetZeroIfNecessary() const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000170
171 llvm::Value *getAtomicSizeValue() const {
172 CharUnits size = CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits);
173 return CGF.CGM.getSize(size);
174 }
175
Tim Northovercc2a6e02015-11-09 19:56:35 +0000176 /// Cast the given pointer to an integer pointer suitable for atomic
177 /// operations if the source.
178 Address emitCastToAtomicIntPointer(Address Addr) const;
179
180 /// If Addr is compatible with the iN that will be used for an atomic
181 /// operation, bitcast it. Otherwise, create a temporary that is suitable
182 /// and copy the value across.
183 Address convertToAtomicIntPointer(Address Addr) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000184
185 /// Turn an atomic-layout object into an r-value.
John McCall7f416cc2015-09-08 08:05:57 +0000186 RValue convertAtomicTempToRValue(Address addr, AggValueSlot resultSlot,
187 SourceLocation loc, bool AsValue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000188
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000189 /// Converts a rvalue to integer value.
Alexey Bataev452d8e12014-12-15 05:25:25 +0000190 llvm::Value *convertRValueToInt(RValue RVal) const;
191
Alexey Bataevb8329262015-02-27 06:33:30 +0000192 RValue ConvertIntToValueOrAtomic(llvm::Value *IntVal,
193 AggValueSlot ResultSlot,
194 SourceLocation Loc, bool AsValue) const;
Alexey Bataev452d8e12014-12-15 05:25:25 +0000195
John McCalla8ec7eb2013-03-07 21:37:17 +0000196 /// Copy an atomic r-value into atomic-layout memory.
Alexey Bataevb57056f2015-01-22 06:17:56 +0000197 void emitCopyIntoMemory(RValue rvalue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000198
199 /// Project an l-value down to the value field.
Alexey Bataevb57056f2015-01-22 06:17:56 +0000200 LValue projectValue() const {
201 assert(LVal.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000202 Address addr = getAtomicAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +0000203 if (hasPadding())
John McCall7f416cc2015-09-08 08:05:57 +0000204 addr = CGF.Builder.CreateStructGEP(addr, 0, CharUnits());
John McCalla8ec7eb2013-03-07 21:37:17 +0000205
John McCall7f416cc2015-09-08 08:05:57 +0000206 return LValue::MakeAddr(addr, getValueType(), CGF.getContext(),
Ivan A. Kosarev383890b2017-10-06 08:17:48 +0000207 LVal.getBaseInfo(), LVal.getTBAAInfo());
John McCalla8ec7eb2013-03-07 21:37:17 +0000208 }
209
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000210 /// Emits atomic load.
Alexey Bataevb8329262015-02-27 06:33:30 +0000211 /// \returns Loaded value.
212 RValue EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
213 bool AsValue, llvm::AtomicOrdering AO,
214 bool IsVolatile);
215
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000216 /// Emits atomic compare-and-exchange sequence.
Alexey Bataevb8329262015-02-27 06:33:30 +0000217 /// \param Expected Expected value.
218 /// \param Desired Desired value.
219 /// \param Success Atomic ordering for success operation.
220 /// \param Failure Atomic ordering for failed operation.
221 /// \param IsWeak true if atomic operation is weak, false otherwise.
222 /// \returns Pair of values: previous value from storage (value type) and
223 /// boolean flag (i1 type) with true if success and false otherwise.
JF Bastien92f4ef12016-04-06 17:26:42 +0000224 std::pair<RValue, llvm::Value *>
225 EmitAtomicCompareExchange(RValue Expected, RValue Desired,
226 llvm::AtomicOrdering Success =
227 llvm::AtomicOrdering::SequentiallyConsistent,
228 llvm::AtomicOrdering Failure =
229 llvm::AtomicOrdering::SequentiallyConsistent,
230 bool IsWeak = false);
Alexey Bataevb8329262015-02-27 06:33:30 +0000231
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000232 /// Emits atomic update.
NAKAMURA Takumid16af5d2015-05-15 13:47:52 +0000233 /// \param AO Atomic ordering.
234 /// \param UpdateOp Update operation for the current lvalue.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000235 void EmitAtomicUpdate(llvm::AtomicOrdering AO,
236 const llvm::function_ref<RValue(RValue)> &UpdateOp,
237 bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000238 /// Emits atomic update.
NAKAMURA Takumid16af5d2015-05-15 13:47:52 +0000239 /// \param AO Atomic ordering.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000240 void EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
241 bool IsVolatile);
242
John McCalla8ec7eb2013-03-07 21:37:17 +0000243 /// Materialize an atomic r-value in atomic-layout memory.
John McCall7f416cc2015-09-08 08:05:57 +0000244 Address materializeRValue(RValue rvalue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000245
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000246 /// Creates temp alloca for intermediate operations on atomic value.
Tim Northovercc2a6e02015-11-09 19:56:35 +0000247 Address CreateTempAlloca() const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000248 private:
249 bool requiresMemSetZero(llvm::Type *type) const;
Alexey Bataevb8329262015-02-27 06:33:30 +0000250
Alexey Bataevb8329262015-02-27 06:33:30 +0000251
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000252 /// Emits atomic load as a libcall.
Alexey Bataevb8329262015-02-27 06:33:30 +0000253 void EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
254 llvm::AtomicOrdering AO, bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000255 /// Emits atomic load as LLVM instruction.
Alexey Bataevb8329262015-02-27 06:33:30 +0000256 llvm::Value *EmitAtomicLoadOp(llvm::AtomicOrdering AO, bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000257 /// Emits atomic compare-and-exchange op as a libcall.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000258 llvm::Value *EmitAtomicCompareExchangeLibcall(
259 llvm::Value *ExpectedAddr, llvm::Value *DesiredAddr,
JF Bastien92f4ef12016-04-06 17:26:42 +0000260 llvm::AtomicOrdering Success =
261 llvm::AtomicOrdering::SequentiallyConsistent,
262 llvm::AtomicOrdering Failure =
263 llvm::AtomicOrdering::SequentiallyConsistent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000264 /// Emits atomic compare-and-exchange op as LLVM instruction.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000265 std::pair<llvm::Value *, llvm::Value *> EmitAtomicCompareExchangeOp(
266 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
JF Bastien92f4ef12016-04-06 17:26:42 +0000267 llvm::AtomicOrdering Success =
268 llvm::AtomicOrdering::SequentiallyConsistent,
269 llvm::AtomicOrdering Failure =
270 llvm::AtomicOrdering::SequentiallyConsistent,
Alexey Bataevb8329262015-02-27 06:33:30 +0000271 bool IsWeak = false);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000272 /// Emit atomic update as libcalls.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000273 void
274 EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
275 const llvm::function_ref<RValue(RValue)> &UpdateOp,
276 bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000277 /// Emit atomic update as LLVM instructions.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000278 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO,
279 const llvm::function_ref<RValue(RValue)> &UpdateOp,
280 bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000281 /// Emit atomic update as libcalls.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000282 void EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO, RValue UpdateRVal,
283 bool IsVolatile);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000284 /// Emit atomic update as LLVM instructions.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000285 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRal,
286 bool IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +0000287 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000288}
John McCalla8ec7eb2013-03-07 21:37:17 +0000289
John McCall7f416cc2015-09-08 08:05:57 +0000290Address AtomicInfo::CreateTempAlloca() const {
291 Address TempAlloca = CGF.CreateMemTemp(
Alexey Bataevb8329262015-02-27 06:33:30 +0000292 (LVal.isBitField() && ValueSizeInBits > AtomicSizeInBits) ? ValueTy
293 : AtomicTy,
John McCall7f416cc2015-09-08 08:05:57 +0000294 getAtomicAlignment(),
Alexey Bataevb8329262015-02-27 06:33:30 +0000295 "atomic-temp");
Alexey Bataevb8329262015-02-27 06:33:30 +0000296 // Cast to pointer to value type for bitfields.
297 if (LVal.isBitField())
298 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +0000299 TempAlloca, getAtomicAddress().getType());
Alexey Bataevb8329262015-02-27 06:33:30 +0000300 return TempAlloca;
301}
302
John McCalla8ec7eb2013-03-07 21:37:17 +0000303static RValue emitAtomicLibcall(CodeGenFunction &CGF,
304 StringRef fnName,
305 QualType resultType,
306 CallArgList &args) {
307 const CGFunctionInfo &fnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000308 CGF.CGM.getTypes().arrangeBuiltinFunctionCall(resultType, args);
John McCalla8ec7eb2013-03-07 21:37:17 +0000309 llvm::FunctionType *fnTy = CGF.CGM.getTypes().GetFunctionType(fnInfo);
James Y Knight9871db02019-02-05 16:42:33 +0000310 llvm::FunctionCallee fn = CGF.CGM.CreateRuntimeFunction(fnTy, fnName);
John McCallb92ab1a2016-10-26 23:46:34 +0000311 auto callee = CGCallee::forDirect(fn);
312 return CGF.EmitCall(fnInfo, callee, ReturnValueSlot(), args);
John McCalla8ec7eb2013-03-07 21:37:17 +0000313}
314
315/// Does a store of the given IR type modify the full expected width?
316static bool isFullSizeType(CodeGenModule &CGM, llvm::Type *type,
317 uint64_t expectedSize) {
318 return (CGM.getDataLayout().getTypeStoreSize(type) * 8 == expectedSize);
319}
320
321/// Does the atomic type require memsetting to zero before initialization?
322///
323/// The IR type is provided as a way of making certain queries faster.
324bool AtomicInfo::requiresMemSetZero(llvm::Type *type) const {
325 // If the atomic type has size padding, we definitely need a memset.
326 if (hasPadding()) return true;
327
328 // Otherwise, do some simple heuristics to try to avoid it:
329 switch (getEvaluationKind()) {
330 // For scalars and complexes, check whether the store size of the
331 // type uses the full size.
332 case TEK_Scalar:
333 return !isFullSizeType(CGF.CGM, type, AtomicSizeInBits);
334 case TEK_Complex:
335 return !isFullSizeType(CGF.CGM, type->getStructElementType(0),
336 AtomicSizeInBits / 2);
337
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000338 // Padding in structs has an undefined bit pattern. User beware.
John McCalla8ec7eb2013-03-07 21:37:17 +0000339 case TEK_Aggregate:
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000340 return false;
John McCalla8ec7eb2013-03-07 21:37:17 +0000341 }
342 llvm_unreachable("bad evaluation kind");
343}
344
Alexey Bataevb57056f2015-01-22 06:17:56 +0000345bool AtomicInfo::emitMemSetZeroIfNecessary() const {
346 assert(LVal.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000347 llvm::Value *addr = LVal.getPointer();
John McCalla8ec7eb2013-03-07 21:37:17 +0000348 if (!requiresMemSetZero(addr->getType()->getPointerElementType()))
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000349 return false;
John McCalla8ec7eb2013-03-07 21:37:17 +0000350
Alexey Bataevb8329262015-02-27 06:33:30 +0000351 CGF.Builder.CreateMemSet(
352 addr, llvm::ConstantInt::get(CGF.Int8Ty, 0),
353 CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits).getQuantity(),
354 LVal.getAlignment().getQuantity());
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000355 return true;
John McCalla8ec7eb2013-03-07 21:37:17 +0000356}
357
Tim Northovercadbbe12014-06-13 19:43:04 +0000358static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak,
John McCall7f416cc2015-09-08 08:05:57 +0000359 Address Dest, Address Ptr,
360 Address Val1, Address Val2,
361 uint64_t Size,
Tim Northover9c177222014-03-13 19:25:48 +0000362 llvm::AtomicOrdering SuccessOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000363 llvm::AtomicOrdering FailureOrder,
364 llvm::SyncScope::ID Scope) {
Tim Northover9c177222014-03-13 19:25:48 +0000365 // Note that cmpxchg doesn't support weak cmpxchg, at least at the moment.
John McCall7f416cc2015-09-08 08:05:57 +0000366 llvm::Value *Expected = CGF.Builder.CreateLoad(Val1);
367 llvm::Value *Desired = CGF.Builder.CreateLoad(Val2);
Tim Northover9c177222014-03-13 19:25:48 +0000368
Tim Northoverb49b04b2014-06-13 14:24:59 +0000369 llvm::AtomicCmpXchgInst *Pair = CGF.Builder.CreateAtomicCmpXchg(
Yaxun Liu39195062017-08-04 18:16:31 +0000370 Ptr.getPointer(), Expected, Desired, SuccessOrder, FailureOrder,
371 Scope);
Tim Northoverb49b04b2014-06-13 14:24:59 +0000372 Pair->setVolatile(E->isVolatile());
Tim Northovercadbbe12014-06-13 19:43:04 +0000373 Pair->setWeak(IsWeak);
Tim Northover9c177222014-03-13 19:25:48 +0000374
375 // Cmp holds the result of the compare-exchange operation: true on success,
376 // false on failure.
Tim Northoverb49b04b2014-06-13 14:24:59 +0000377 llvm::Value *Old = CGF.Builder.CreateExtractValue(Pair, 0);
378 llvm::Value *Cmp = CGF.Builder.CreateExtractValue(Pair, 1);
Tim Northover9c177222014-03-13 19:25:48 +0000379
380 // This basic block is used to hold the store instruction if the operation
381 // failed.
382 llvm::BasicBlock *StoreExpectedBB =
383 CGF.createBasicBlock("cmpxchg.store_expected", CGF.CurFn);
384
385 // This basic block is the exit point of the operation, we should end up
386 // here regardless of whether or not the operation succeeded.
387 llvm::BasicBlock *ContinueBB =
388 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
389
390 // Update Expected if Expected isn't equal to Old, otherwise branch to the
391 // exit point.
392 CGF.Builder.CreateCondBr(Cmp, ContinueBB, StoreExpectedBB);
393
394 CGF.Builder.SetInsertPoint(StoreExpectedBB);
395 // Update the memory at Expected with Old's value.
John McCall7f416cc2015-09-08 08:05:57 +0000396 CGF.Builder.CreateStore(Old, Val1);
Tim Northover9c177222014-03-13 19:25:48 +0000397 // Finally, branch to the exit point.
398 CGF.Builder.CreateBr(ContinueBB);
399
400 CGF.Builder.SetInsertPoint(ContinueBB);
401 // Update the memory at Dest with Cmp's value.
402 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
Tim Northover9c177222014-03-13 19:25:48 +0000403}
404
405/// Given an ordering required on success, emit all possible cmpxchg
406/// instructions to cope with the provided (but possibly only dynamically known)
407/// FailureOrder.
408static void emitAtomicCmpXchgFailureSet(CodeGenFunction &CGF, AtomicExpr *E,
JF Bastiendda2cb12016-04-18 18:01:49 +0000409 bool IsWeak, Address Dest, Address Ptr,
410 Address Val1, Address Val2,
Tim Northover9c177222014-03-13 19:25:48 +0000411 llvm::Value *FailureOrderVal,
John McCall7f416cc2015-09-08 08:05:57 +0000412 uint64_t Size,
Yaxun Liu39195062017-08-04 18:16:31 +0000413 llvm::AtomicOrdering SuccessOrder,
414 llvm::SyncScope::ID Scope) {
Tim Northover9c177222014-03-13 19:25:48 +0000415 llvm::AtomicOrdering FailureOrder;
416 if (llvm::ConstantInt *FO = dyn_cast<llvm::ConstantInt>(FailureOrderVal)) {
JF Bastiendda2cb12016-04-18 18:01:49 +0000417 auto FOS = FO->getSExtValue();
418 if (!llvm::isValidAtomicOrderingCABI(FOS))
JF Bastien92f4ef12016-04-06 17:26:42 +0000419 FailureOrder = llvm::AtomicOrdering::Monotonic;
JF Bastiendda2cb12016-04-18 18:01:49 +0000420 else
421 switch ((llvm::AtomicOrderingCABI)FOS) {
422 case llvm::AtomicOrderingCABI::relaxed:
423 case llvm::AtomicOrderingCABI::release:
424 case llvm::AtomicOrderingCABI::acq_rel:
425 FailureOrder = llvm::AtomicOrdering::Monotonic;
426 break;
427 case llvm::AtomicOrderingCABI::consume:
428 case llvm::AtomicOrderingCABI::acquire:
429 FailureOrder = llvm::AtomicOrdering::Acquire;
430 break;
431 case llvm::AtomicOrderingCABI::seq_cst:
432 FailureOrder = llvm::AtomicOrdering::SequentiallyConsistent;
433 break;
434 }
JF Bastiendd11ee72016-04-06 23:37:36 +0000435 if (isStrongerThan(FailureOrder, SuccessOrder)) {
436 // Don't assert on undefined behavior "failure argument shall be no
437 // stronger than the success argument".
Tim Northover9c177222014-03-13 19:25:48 +0000438 FailureOrder =
JF Bastiendda2cb12016-04-18 18:01:49 +0000439 llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrder);
Tim Northover9c177222014-03-13 19:25:48 +0000440 }
JF Bastiendda2cb12016-04-18 18:01:49 +0000441 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000442 FailureOrder, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000443 return;
444 }
445
446 // Create all the relevant BB's
Craig Topper8a13c412014-05-21 05:09:00 +0000447 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
448 *SeqCstBB = nullptr;
Tim Northover9c177222014-03-13 19:25:48 +0000449 MonotonicBB = CGF.createBasicBlock("monotonic_fail", CGF.CurFn);
JF Bastien92f4ef12016-04-06 17:26:42 +0000450 if (SuccessOrder != llvm::AtomicOrdering::Monotonic &&
451 SuccessOrder != llvm::AtomicOrdering::Release)
Tim Northover9c177222014-03-13 19:25:48 +0000452 AcquireBB = CGF.createBasicBlock("acquire_fail", CGF.CurFn);
JF Bastien92f4ef12016-04-06 17:26:42 +0000453 if (SuccessOrder == llvm::AtomicOrdering::SequentiallyConsistent)
Tim Northover9c177222014-03-13 19:25:48 +0000454 SeqCstBB = CGF.createBasicBlock("seqcst_fail", CGF.CurFn);
455
456 llvm::BasicBlock *ContBB = CGF.createBasicBlock("atomic.continue", CGF.CurFn);
457
458 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(FailureOrderVal, MonotonicBB);
459
460 // Emit all the different atomics
461
462 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
463 // doesn't matter unless someone is crazy enough to use something that
464 // doesn't fold to a constant for the ordering.
465 CGF.Builder.SetInsertPoint(MonotonicBB);
Tim Northovercadbbe12014-06-13 19:43:04 +0000466 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000467 Size, SuccessOrder, llvm::AtomicOrdering::Monotonic, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000468 CGF.Builder.CreateBr(ContBB);
469
470 if (AcquireBB) {
471 CGF.Builder.SetInsertPoint(AcquireBB);
Tim Northovercadbbe12014-06-13 19:43:04 +0000472 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000473 Size, SuccessOrder, llvm::AtomicOrdering::Acquire, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000474 CGF.Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +0000475 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
Tim Northover9c177222014-03-13 19:25:48 +0000476 AcquireBB);
JF Bastiendda2cb12016-04-18 18:01:49 +0000477 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
Tim Northover9c177222014-03-13 19:25:48 +0000478 AcquireBB);
479 }
480 if (SeqCstBB) {
481 CGF.Builder.SetInsertPoint(SeqCstBB);
JF Bastien92f4ef12016-04-06 17:26:42 +0000482 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000483 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000484 CGF.Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +0000485 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
Tim Northover9c177222014-03-13 19:25:48 +0000486 SeqCstBB);
487 }
488
489 CGF.Builder.SetInsertPoint(ContBB);
490}
491
John McCall7f416cc2015-09-08 08:05:57 +0000492static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest,
493 Address Ptr, Address Val1, Address Val2,
Tim Northovercadbbe12014-06-13 19:43:04 +0000494 llvm::Value *IsWeak, llvm::Value *FailureOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000495 uint64_t Size, llvm::AtomicOrdering Order,
496 llvm::SyncScope::ID Scope) {
John McCallfc207f22013-03-07 21:37:12 +0000497 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
498 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
499
500 switch (E->getOp()) {
501 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000502 case AtomicExpr::AO__opencl_atomic_init:
John McCallfc207f22013-03-07 21:37:12 +0000503 llvm_unreachable("Already handled!");
504
505 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +0000506 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
Tim Northovercadbbe12014-06-13 19:43:04 +0000507 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000508 FailureOrder, Size, Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000509 return;
Tim Northovercadbbe12014-06-13 19:43:04 +0000510 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +0000511 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Tim Northovercadbbe12014-06-13 19:43:04 +0000512 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000513 FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000514 return;
515 case AtomicExpr::AO__atomic_compare_exchange:
516 case AtomicExpr::AO__atomic_compare_exchange_n: {
517 if (llvm::ConstantInt *IsWeakC = dyn_cast<llvm::ConstantInt>(IsWeak)) {
518 emitAtomicCmpXchgFailureSet(CGF, E, IsWeakC->getZExtValue(), Dest, Ptr,
Yaxun Liu39195062017-08-04 18:16:31 +0000519 Val1, Val2, FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000520 } else {
521 // Create all the relevant BB's
522 llvm::BasicBlock *StrongBB =
523 CGF.createBasicBlock("cmpxchg.strong", CGF.CurFn);
524 llvm::BasicBlock *WeakBB = CGF.createBasicBlock("cmxchg.weak", CGF.CurFn);
525 llvm::BasicBlock *ContBB =
526 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
527
528 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(IsWeak, WeakBB);
529 SI->addCase(CGF.Builder.getInt1(false), StrongBB);
530
531 CGF.Builder.SetInsertPoint(StrongBB);
532 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000533 FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000534 CGF.Builder.CreateBr(ContBB);
535
536 CGF.Builder.SetInsertPoint(WeakBB);
537 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000538 FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000539 CGF.Builder.CreateBr(ContBB);
540
541 CGF.Builder.SetInsertPoint(ContBB);
542 }
543 return;
544 }
John McCallfc207f22013-03-07 21:37:12 +0000545 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +0000546 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +0000547 case AtomicExpr::AO__atomic_load_n:
548 case AtomicExpr::AO__atomic_load: {
549 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
Yaxun Liu39195062017-08-04 18:16:31 +0000550 Load->setAtomic(Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000551 Load->setVolatile(E->isVolatile());
John McCall7f416cc2015-09-08 08:05:57 +0000552 CGF.Builder.CreateStore(Load, Dest);
John McCallfc207f22013-03-07 21:37:12 +0000553 return;
554 }
555
556 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +0000557 case AtomicExpr::AO__opencl_atomic_store:
John McCallfc207f22013-03-07 21:37:12 +0000558 case AtomicExpr::AO__atomic_store:
559 case AtomicExpr::AO__atomic_store_n: {
John McCall7f416cc2015-09-08 08:05:57 +0000560 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
John McCallfc207f22013-03-07 21:37:12 +0000561 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
Yaxun Liu39195062017-08-04 18:16:31 +0000562 Store->setAtomic(Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000563 Store->setVolatile(E->isVolatile());
564 return;
565 }
566
567 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +0000568 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +0000569 case AtomicExpr::AO__atomic_exchange_n:
570 case AtomicExpr::AO__atomic_exchange:
571 Op = llvm::AtomicRMWInst::Xchg;
572 break;
573
574 case AtomicExpr::AO__atomic_add_fetch:
575 PostOp = llvm::Instruction::Add;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000576 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000577 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +0000578 case AtomicExpr::AO__opencl_atomic_fetch_add:
John McCallfc207f22013-03-07 21:37:12 +0000579 case AtomicExpr::AO__atomic_fetch_add:
580 Op = llvm::AtomicRMWInst::Add;
581 break;
582
583 case AtomicExpr::AO__atomic_sub_fetch:
584 PostOp = llvm::Instruction::Sub;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000585 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000586 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000587 case AtomicExpr::AO__opencl_atomic_fetch_sub:
John McCallfc207f22013-03-07 21:37:12 +0000588 case AtomicExpr::AO__atomic_fetch_sub:
589 Op = llvm::AtomicRMWInst::Sub;
590 break;
591
Yaxun Liu39195062017-08-04 18:16:31 +0000592 case AtomicExpr::AO__opencl_atomic_fetch_min:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +0000593 case AtomicExpr::AO__atomic_fetch_min:
Yaxun Liu39195062017-08-04 18:16:31 +0000594 Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Min
595 : llvm::AtomicRMWInst::UMin;
596 break;
597
598 case AtomicExpr::AO__opencl_atomic_fetch_max:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +0000599 case AtomicExpr::AO__atomic_fetch_max:
Yaxun Liu39195062017-08-04 18:16:31 +0000600 Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Max
601 : llvm::AtomicRMWInst::UMax;
602 break;
603
John McCallfc207f22013-03-07 21:37:12 +0000604 case AtomicExpr::AO__atomic_and_fetch:
605 PostOp = llvm::Instruction::And;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000606 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000607 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +0000608 case AtomicExpr::AO__opencl_atomic_fetch_and:
John McCallfc207f22013-03-07 21:37:12 +0000609 case AtomicExpr::AO__atomic_fetch_and:
610 Op = llvm::AtomicRMWInst::And;
611 break;
612
613 case AtomicExpr::AO__atomic_or_fetch:
614 PostOp = llvm::Instruction::Or;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000615 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000616 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +0000617 case AtomicExpr::AO__opencl_atomic_fetch_or:
John McCallfc207f22013-03-07 21:37:12 +0000618 case AtomicExpr::AO__atomic_fetch_or:
619 Op = llvm::AtomicRMWInst::Or;
620 break;
621
622 case AtomicExpr::AO__atomic_xor_fetch:
623 PostOp = llvm::Instruction::Xor;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000624 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000625 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +0000626 case AtomicExpr::AO__opencl_atomic_fetch_xor:
John McCallfc207f22013-03-07 21:37:12 +0000627 case AtomicExpr::AO__atomic_fetch_xor:
628 Op = llvm::AtomicRMWInst::Xor;
629 break;
630
631 case AtomicExpr::AO__atomic_nand_fetch:
James Y Knight7aefb5b2015-11-12 18:37:29 +0000632 PostOp = llvm::Instruction::And; // the NOT is special cased below
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000633 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000634 case AtomicExpr::AO__atomic_fetch_nand:
635 Op = llvm::AtomicRMWInst::Nand;
636 break;
637 }
638
John McCall7f416cc2015-09-08 08:05:57 +0000639 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
John McCallfc207f22013-03-07 21:37:12 +0000640 llvm::AtomicRMWInst *RMWI =
Yaxun Liu39195062017-08-04 18:16:31 +0000641 CGF.Builder.CreateAtomicRMW(Op, Ptr.getPointer(), LoadVal1, Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000642 RMWI->setVolatile(E->isVolatile());
643
644 // For __atomic_*_fetch operations, perform the operation again to
645 // determine the value which was written.
646 llvm::Value *Result = RMWI;
647 if (PostOp)
648 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
649 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
650 Result = CGF.Builder.CreateNot(Result);
John McCall7f416cc2015-09-08 08:05:57 +0000651 CGF.Builder.CreateStore(Result, Dest);
John McCallfc207f22013-03-07 21:37:12 +0000652}
653
654// This function emits any expression (scalar, complex, or aggregate)
655// into a temporary alloca.
John McCall7f416cc2015-09-08 08:05:57 +0000656static Address
John McCallfc207f22013-03-07 21:37:12 +0000657EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
John McCall7f416cc2015-09-08 08:05:57 +0000658 Address DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
John McCallfc207f22013-03-07 21:37:12 +0000659 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
660 /*Init*/ true);
661 return DeclPtr;
662}
663
Yaxun Liu30d652a2017-08-15 16:02:49 +0000664static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *Expr, Address Dest,
665 Address Ptr, Address Val1, Address Val2,
666 llvm::Value *IsWeak, llvm::Value *FailureOrder,
667 uint64_t Size, llvm::AtomicOrdering Order,
668 llvm::Value *Scope) {
669 auto ScopeModel = Expr->getScopeModel();
670
671 // LLVM atomic instructions always have synch scope. If clang atomic
672 // expression has no scope operand, use default LLVM synch scope.
673 if (!ScopeModel) {
674 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
675 Order, CGF.CGM.getLLVMContext().getOrInsertSyncScopeID(""));
676 return;
677 }
678
679 // Handle constant scope.
680 if (auto SC = dyn_cast<llvm::ConstantInt>(Scope)) {
681 auto SCID = CGF.getTargetHooks().getLLVMSyncScopeID(
682 ScopeModel->map(SC->getZExtValue()), CGF.CGM.getLLVMContext());
683 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
684 Order, SCID);
685 return;
686 }
687
688 // Handle non-constant scope.
689 auto &Builder = CGF.Builder;
690 auto Scopes = ScopeModel->getRuntimeValues();
691 llvm::DenseMap<unsigned, llvm::BasicBlock *> BB;
692 for (auto S : Scopes)
693 BB[S] = CGF.createBasicBlock(getAsString(ScopeModel->map(S)), CGF.CurFn);
694
695 llvm::BasicBlock *ContBB =
696 CGF.createBasicBlock("atomic.scope.continue", CGF.CurFn);
697
698 auto *SC = Builder.CreateIntCast(Scope, Builder.getInt32Ty(), false);
699 // If unsupported synch scope is encountered at run time, assume a fallback
700 // synch scope value.
701 auto FallBack = ScopeModel->getFallBackValue();
702 llvm::SwitchInst *SI = Builder.CreateSwitch(SC, BB[FallBack]);
703 for (auto S : Scopes) {
704 auto *B = BB[S];
705 if (S != FallBack)
706 SI->addCase(Builder.getInt32(S), B);
707
708 Builder.SetInsertPoint(B);
709 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
710 Order,
711 CGF.getTargetHooks().getLLVMSyncScopeID(ScopeModel->map(S),
712 CGF.getLLVMContext()));
713 Builder.CreateBr(ContBB);
714 }
715
716 Builder.SetInsertPoint(ContBB);
717}
718
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000719static void
720AddDirectArgument(CodeGenFunction &CGF, CallArgList &Args,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000721 bool UseOptimizedLibcall, llvm::Value *Val, QualType ValTy,
David Majnemer0392cf82014-08-29 07:27:49 +0000722 SourceLocation Loc, CharUnits SizeInChars) {
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000723 if (UseOptimizedLibcall) {
724 // Load value and pass it to the function directly.
John McCall7f416cc2015-09-08 08:05:57 +0000725 CharUnits Align = CGF.getContext().getTypeAlignInChars(ValTy);
David Majnemer0392cf82014-08-29 07:27:49 +0000726 int64_t SizeInBits = CGF.getContext().toBits(SizeInChars);
727 ValTy =
728 CGF.getContext().getIntTypeForBitwidth(SizeInBits, /*Signed=*/false);
729 llvm::Type *IPtrTy = llvm::IntegerType::get(CGF.getLLVMContext(),
730 SizeInBits)->getPointerTo();
John McCall7f416cc2015-09-08 08:05:57 +0000731 Address Ptr = Address(CGF.Builder.CreateBitCast(Val, IPtrTy), Align);
732 Val = CGF.EmitLoadOfScalar(Ptr, false,
733 CGF.getContext().getPointerType(ValTy),
David Majnemer0392cf82014-08-29 07:27:49 +0000734 Loc);
735 // Coerce the value into an appropriately sized integer type.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000736 Args.add(RValue::get(Val), ValTy);
737 } else {
738 // Non-optimized functions always take a reference.
739 Args.add(RValue::get(CGF.EmitCastToVoidPtr(Val)),
740 CGF.getContext().VoidPtrTy);
741 }
742}
743
Tim Northovercc2a6e02015-11-09 19:56:35 +0000744RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
John McCallfc207f22013-03-07 21:37:12 +0000745 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
746 QualType MemTy = AtomicTy;
747 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
748 MemTy = AT->getValueType();
John McCall7f416cc2015-09-08 08:05:57 +0000749 llvm::Value *IsWeak = nullptr, *OrderFail = nullptr;
750
751 Address Val1 = Address::invalid();
752 Address Val2 = Address::invalid();
Tim Northovercc2a6e02015-11-09 19:56:35 +0000753 Address Dest = Address::invalid();
Wei Mi01414bd2017-09-25 19:57:59 +0000754 Address Ptr = EmitPointerWithAlignment(E->getPtr());
755
Tim Northover9dc1d0c2018-04-23 08:16:24 +0000756 if (E->getOp() == AtomicExpr::AO__c11_atomic_init ||
757 E->getOp() == AtomicExpr::AO__opencl_atomic_init) {
758 LValue lvalue = MakeAddrLValue(Ptr, AtomicTy);
759 EmitAtomicInit(E->getVal1(), lvalue);
760 return RValue::get(nullptr);
761 }
762
Wei Mi01414bd2017-09-25 19:57:59 +0000763 CharUnits sizeChars, alignChars;
764 std::tie(sizeChars, alignChars) = getContext().getTypeInfoInChars(AtomicTy);
765 uint64_t Size = sizeChars.getQuantity();
766 unsigned MaxInlineWidthInBits = getTarget().getMaxAtomicInlineWidth();
John McCallfc207f22013-03-07 21:37:12 +0000767
Richard Smithedb9fbb2018-09-07 21:24:27 +0000768 bool Oversized = getContext().toBits(sizeChars) > MaxInlineWidthInBits;
769 bool Misaligned = (Ptr.getAlignment() % sizeChars) != 0;
770 bool UseLibcall = Misaligned | Oversized;
771
772 if (UseLibcall) {
773 CGM.getDiags().Report(E->getBeginLoc(), diag::warn_atomic_op_misaligned)
774 << !Oversized;
775 }
John McCallfc207f22013-03-07 21:37:12 +0000776
Craig Topper8a13c412014-05-21 05:09:00 +0000777 llvm::Value *Order = EmitScalarExpr(E->getOrder());
Yaxun Liu30d652a2017-08-15 16:02:49 +0000778 llvm::Value *Scope =
779 E->getScopeModel() ? EmitScalarExpr(E->getScope()) : nullptr;
John McCallfc207f22013-03-07 21:37:12 +0000780
781 switch (E->getOp()) {
782 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000783 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000784 llvm_unreachable("Already handled above with EmitAtomicInit!");
John McCallfc207f22013-03-07 21:37:12 +0000785
786 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +0000787 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +0000788 case AtomicExpr::AO__atomic_load_n:
789 break;
790
791 case AtomicExpr::AO__atomic_load:
John McCall7f416cc2015-09-08 08:05:57 +0000792 Dest = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000793 break;
794
795 case AtomicExpr::AO__atomic_store:
John McCall7f416cc2015-09-08 08:05:57 +0000796 Val1 = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000797 break;
798
799 case AtomicExpr::AO__atomic_exchange:
John McCall7f416cc2015-09-08 08:05:57 +0000800 Val1 = EmitPointerWithAlignment(E->getVal1());
801 Dest = EmitPointerWithAlignment(E->getVal2());
John McCallfc207f22013-03-07 21:37:12 +0000802 break;
803
804 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
805 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +0000806 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
807 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
John McCallfc207f22013-03-07 21:37:12 +0000808 case AtomicExpr::AO__atomic_compare_exchange_n:
809 case AtomicExpr::AO__atomic_compare_exchange:
John McCall7f416cc2015-09-08 08:05:57 +0000810 Val1 = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000811 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
John McCall7f416cc2015-09-08 08:05:57 +0000812 Val2 = EmitPointerWithAlignment(E->getVal2());
John McCallfc207f22013-03-07 21:37:12 +0000813 else
814 Val2 = EmitValToTemp(*this, E->getVal2());
815 OrderFail = EmitScalarExpr(E->getOrderFail());
Yaxun Liu39195062017-08-04 18:16:31 +0000816 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
817 E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
Tim Northovercadbbe12014-06-13 19:43:04 +0000818 IsWeak = EmitScalarExpr(E->getWeak());
John McCallfc207f22013-03-07 21:37:12 +0000819 break;
820
821 case AtomicExpr::AO__c11_atomic_fetch_add:
822 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000823 case AtomicExpr::AO__opencl_atomic_fetch_add:
824 case AtomicExpr::AO__opencl_atomic_fetch_sub:
John McCallfc207f22013-03-07 21:37:12 +0000825 if (MemTy->isPointerType()) {
826 // For pointer arithmetic, we're required to do a bit of math:
827 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
828 // ... but only for the C11 builtins. The GNU builtins expect the
829 // user to multiply by sizeof(T).
830 QualType Val1Ty = E->getVal1()->getType();
831 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
832 CharUnits PointeeIncAmt =
833 getContext().getTypeSizeInChars(MemTy->getPointeeType());
834 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
John McCall7f416cc2015-09-08 08:05:57 +0000835 auto Temp = CreateMemTemp(Val1Ty, ".atomictmp");
836 Val1 = Temp;
837 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Temp, Val1Ty));
John McCallfc207f22013-03-07 21:37:12 +0000838 break;
839 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000840 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000841 case AtomicExpr::AO__atomic_fetch_add:
842 case AtomicExpr::AO__atomic_fetch_sub:
843 case AtomicExpr::AO__atomic_add_fetch:
844 case AtomicExpr::AO__atomic_sub_fetch:
845 case AtomicExpr::AO__c11_atomic_store:
846 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +0000847 case AtomicExpr::AO__opencl_atomic_store:
848 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +0000849 case AtomicExpr::AO__atomic_store_n:
850 case AtomicExpr::AO__atomic_exchange_n:
851 case AtomicExpr::AO__c11_atomic_fetch_and:
852 case AtomicExpr::AO__c11_atomic_fetch_or:
853 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +0000854 case AtomicExpr::AO__opencl_atomic_fetch_and:
855 case AtomicExpr::AO__opencl_atomic_fetch_or:
856 case AtomicExpr::AO__opencl_atomic_fetch_xor:
857 case AtomicExpr::AO__opencl_atomic_fetch_min:
858 case AtomicExpr::AO__opencl_atomic_fetch_max:
John McCallfc207f22013-03-07 21:37:12 +0000859 case AtomicExpr::AO__atomic_fetch_and:
860 case AtomicExpr::AO__atomic_fetch_or:
861 case AtomicExpr::AO__atomic_fetch_xor:
862 case AtomicExpr::AO__atomic_fetch_nand:
863 case AtomicExpr::AO__atomic_and_fetch:
864 case AtomicExpr::AO__atomic_or_fetch:
865 case AtomicExpr::AO__atomic_xor_fetch:
866 case AtomicExpr::AO__atomic_nand_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +0000867 case AtomicExpr::AO__atomic_fetch_min:
868 case AtomicExpr::AO__atomic_fetch_max:
John McCallfc207f22013-03-07 21:37:12 +0000869 Val1 = EmitValToTemp(*this, E->getVal1());
870 break;
871 }
872
David Majnemeree8d04d2014-12-12 08:16:09 +0000873 QualType RValTy = E->getType().getUnqualifiedType();
874
Tim Northovercc2a6e02015-11-09 19:56:35 +0000875 // The inlined atomics only function on iN types, where N is a power of 2. We
876 // need to make sure (via temporaries if necessary) that all incoming values
877 // are compatible.
878 LValue AtomicVal = MakeAddrLValue(Ptr, AtomicTy);
879 AtomicInfo Atomics(*this, AtomicVal);
880
881 Ptr = Atomics.emitCastToAtomicIntPointer(Ptr);
882 if (Val1.isValid()) Val1 = Atomics.convertToAtomicIntPointer(Val1);
883 if (Val2.isValid()) Val2 = Atomics.convertToAtomicIntPointer(Val2);
884 if (Dest.isValid())
885 Dest = Atomics.emitCastToAtomicIntPointer(Dest);
886 else if (E->isCmpXChg())
887 Dest = CreateMemTemp(RValTy, "cmpxchg.bool");
888 else if (!RValTy->isVoidType())
889 Dest = Atomics.emitCastToAtomicIntPointer(Atomics.CreateTempAlloca());
John McCallfc207f22013-03-07 21:37:12 +0000890
891 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
892 if (UseLibcall) {
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000893 bool UseOptimizedLibcall = false;
894 switch (E->getOp()) {
James Y Knight81167fb2015-08-05 16:57:36 +0000895 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000896 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000897 llvm_unreachable("Already handled above with EmitAtomicInit!");
898
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000899 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +0000900 case AtomicExpr::AO__opencl_atomic_fetch_add:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000901 case AtomicExpr::AO__atomic_fetch_add:
902 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +0000903 case AtomicExpr::AO__opencl_atomic_fetch_and:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000904 case AtomicExpr::AO__atomic_fetch_and:
905 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +0000906 case AtomicExpr::AO__opencl_atomic_fetch_or:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000907 case AtomicExpr::AO__atomic_fetch_or:
James Y Knight81167fb2015-08-05 16:57:36 +0000908 case AtomicExpr::AO__atomic_fetch_nand:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000909 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000910 case AtomicExpr::AO__opencl_atomic_fetch_sub:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000911 case AtomicExpr::AO__atomic_fetch_sub:
912 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +0000913 case AtomicExpr::AO__opencl_atomic_fetch_xor:
914 case AtomicExpr::AO__opencl_atomic_fetch_min:
915 case AtomicExpr::AO__opencl_atomic_fetch_max:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000916 case AtomicExpr::AO__atomic_fetch_xor:
James Y Knight81167fb2015-08-05 16:57:36 +0000917 case AtomicExpr::AO__atomic_add_fetch:
918 case AtomicExpr::AO__atomic_and_fetch:
919 case AtomicExpr::AO__atomic_nand_fetch:
920 case AtomicExpr::AO__atomic_or_fetch:
921 case AtomicExpr::AO__atomic_sub_fetch:
922 case AtomicExpr::AO__atomic_xor_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +0000923 case AtomicExpr::AO__atomic_fetch_min:
924 case AtomicExpr::AO__atomic_fetch_max:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000925 // For these, only library calls for certain sizes exist.
926 UseOptimizedLibcall = true;
927 break;
James Y Knight81167fb2015-08-05 16:57:36 +0000928
Richard Smithda3729d2018-09-07 23:57:54 +0000929 case AtomicExpr::AO__atomic_load:
930 case AtomicExpr::AO__atomic_store:
931 case AtomicExpr::AO__atomic_exchange:
932 case AtomicExpr::AO__atomic_compare_exchange:
933 // Use the generic version if we don't know that the operand will be
934 // suitably aligned for the optimized version.
935 if (Misaligned)
936 break;
937 LLVM_FALLTHROUGH;
James Y Knight81167fb2015-08-05 16:57:36 +0000938 case AtomicExpr::AO__c11_atomic_load:
939 case AtomicExpr::AO__c11_atomic_store:
940 case AtomicExpr::AO__c11_atomic_exchange:
941 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
942 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +0000943 case AtomicExpr::AO__opencl_atomic_load:
944 case AtomicExpr::AO__opencl_atomic_store:
945 case AtomicExpr::AO__opencl_atomic_exchange:
946 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
947 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
James Y Knight81167fb2015-08-05 16:57:36 +0000948 case AtomicExpr::AO__atomic_load_n:
James Y Knight81167fb2015-08-05 16:57:36 +0000949 case AtomicExpr::AO__atomic_store_n:
James Y Knight81167fb2015-08-05 16:57:36 +0000950 case AtomicExpr::AO__atomic_exchange_n:
James Y Knight81167fb2015-08-05 16:57:36 +0000951 case AtomicExpr::AO__atomic_compare_exchange_n:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000952 // Only use optimized library calls for sizes for which they exist.
Richard Smithda3729d2018-09-07 23:57:54 +0000953 // FIXME: Size == 16 optimized library functions exist too.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000954 if (Size == 1 || Size == 2 || Size == 4 || Size == 8)
955 UseOptimizedLibcall = true;
956 break;
957 }
John McCallfc207f22013-03-07 21:37:12 +0000958
John McCallfc207f22013-03-07 21:37:12 +0000959 CallArgList Args;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000960 if (!UseOptimizedLibcall) {
961 // For non-optimized library calls, the size is the first parameter
962 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
963 getContext().getSizeType());
964 }
965 // Atomic address is the first or second parameter
Yaxun Liu39195062017-08-04 18:16:31 +0000966 // The OpenCL atomic library functions only accept pointer arguments to
967 // generic address space.
968 auto CastToGenericAddrSpace = [&](llvm::Value *V, QualType PT) {
969 if (!E->isOpenCL())
970 return V;
971 auto AS = PT->getAs<PointerType>()->getPointeeType().getAddressSpace();
972 if (AS == LangAS::opencl_generic)
973 return V;
974 auto DestAS = getContext().getTargetAddressSpace(LangAS::opencl_generic);
975 auto T = V->getType();
976 auto *DestType = T->getPointerElementType()->getPointerTo(DestAS);
977
978 return getTargetHooks().performAddrSpaceCast(
979 *this, V, AS, LangAS::opencl_generic, DestType, false);
980 };
981
982 Args.add(RValue::get(CastToGenericAddrSpace(
983 EmitCastToVoidPtr(Ptr.getPointer()), E->getPtr()->getType())),
John McCall7f416cc2015-09-08 08:05:57 +0000984 getContext().VoidPtrTy);
John McCallfc207f22013-03-07 21:37:12 +0000985
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000986 std::string LibCallName;
Logan Chien74798a32014-03-26 17:35:01 +0000987 QualType LoweredMemTy =
988 MemTy->isPointerType() ? getContext().getIntPtrType() : MemTy;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000989 QualType RetTy;
990 bool HaveRetTy = false;
James Y Knight7aefb5b2015-11-12 18:37:29 +0000991 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
John McCallfc207f22013-03-07 21:37:12 +0000992 switch (E->getOp()) {
James Y Knight81167fb2015-08-05 16:57:36 +0000993 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000994 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000995 llvm_unreachable("Already handled!");
996
John McCallfc207f22013-03-07 21:37:12 +0000997 // There is only one libcall for compare an exchange, because there is no
998 // optimisation benefit possible from a libcall version of a weak compare
999 // and exchange.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001000 // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
John McCallfc207f22013-03-07 21:37:12 +00001001 // void *desired, int success, int failure)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001002 // bool __atomic_compare_exchange_N(T *mem, T *expected, T desired,
1003 // int success, int failure)
John McCallfc207f22013-03-07 21:37:12 +00001004 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1005 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +00001006 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1007 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
John McCallfc207f22013-03-07 21:37:12 +00001008 case AtomicExpr::AO__atomic_compare_exchange:
1009 case AtomicExpr::AO__atomic_compare_exchange_n:
1010 LibCallName = "__atomic_compare_exchange";
1011 RetTy = getContext().BoolTy;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001012 HaveRetTy = true;
Yaxun Liu39195062017-08-04 18:16:31 +00001013 Args.add(
1014 RValue::get(CastToGenericAddrSpace(
1015 EmitCastToVoidPtr(Val1.getPointer()), E->getVal1()->getType())),
1016 getContext().VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001017 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val2.getPointer(),
1018 MemTy, E->getExprLoc(), sizeChars);
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001019 Args.add(RValue::get(Order), getContext().IntTy);
John McCallfc207f22013-03-07 21:37:12 +00001020 Order = OrderFail;
1021 break;
1022 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
1023 // int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001024 // T __atomic_exchange_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +00001025 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00001026 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +00001027 case AtomicExpr::AO__atomic_exchange_n:
1028 case AtomicExpr::AO__atomic_exchange:
1029 LibCallName = "__atomic_exchange";
John McCall7f416cc2015-09-08 08:05:57 +00001030 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1031 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001032 break;
1033 // void __atomic_store(size_t size, void *mem, void *val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001034 // void __atomic_store_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +00001035 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00001036 case AtomicExpr::AO__opencl_atomic_store:
John McCallfc207f22013-03-07 21:37:12 +00001037 case AtomicExpr::AO__atomic_store:
1038 case AtomicExpr::AO__atomic_store_n:
1039 LibCallName = "__atomic_store";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001040 RetTy = getContext().VoidTy;
1041 HaveRetTy = true;
John McCall7f416cc2015-09-08 08:05:57 +00001042 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1043 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001044 break;
1045 // void __atomic_load(size_t size, void *mem, void *return, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001046 // T __atomic_load_N(T *mem, int order)
John McCallfc207f22013-03-07 21:37:12 +00001047 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00001048 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +00001049 case AtomicExpr::AO__atomic_load:
1050 case AtomicExpr::AO__atomic_load_n:
1051 LibCallName = "__atomic_load";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001052 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001053 // T __atomic_add_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001054 // T __atomic_fetch_add_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001055 case AtomicExpr::AO__atomic_add_fetch:
1056 PostOp = llvm::Instruction::Add;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001057 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001058 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +00001059 case AtomicExpr::AO__opencl_atomic_fetch_add:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001060 case AtomicExpr::AO__atomic_fetch_add:
1061 LibCallName = "__atomic_fetch_add";
John McCall7f416cc2015-09-08 08:05:57 +00001062 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1063 LoweredMemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001064 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001065 // T __atomic_and_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001066 // T __atomic_fetch_and_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001067 case AtomicExpr::AO__atomic_and_fetch:
1068 PostOp = llvm::Instruction::And;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001069 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001070 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +00001071 case AtomicExpr::AO__opencl_atomic_fetch_and:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001072 case AtomicExpr::AO__atomic_fetch_and:
1073 LibCallName = "__atomic_fetch_and";
John McCall7f416cc2015-09-08 08:05:57 +00001074 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1075 MemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001076 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001077 // T __atomic_or_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001078 // T __atomic_fetch_or_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001079 case AtomicExpr::AO__atomic_or_fetch:
1080 PostOp = llvm::Instruction::Or;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001081 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001082 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +00001083 case AtomicExpr::AO__opencl_atomic_fetch_or:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001084 case AtomicExpr::AO__atomic_fetch_or:
1085 LibCallName = "__atomic_fetch_or";
John McCall7f416cc2015-09-08 08:05:57 +00001086 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1087 MemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001088 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001089 // T __atomic_sub_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001090 // T __atomic_fetch_sub_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001091 case AtomicExpr::AO__atomic_sub_fetch:
1092 PostOp = llvm::Instruction::Sub;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001093 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001094 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00001095 case AtomicExpr::AO__opencl_atomic_fetch_sub:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001096 case AtomicExpr::AO__atomic_fetch_sub:
1097 LibCallName = "__atomic_fetch_sub";
John McCall7f416cc2015-09-08 08:05:57 +00001098 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1099 LoweredMemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001100 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001101 // T __atomic_xor_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001102 // T __atomic_fetch_xor_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001103 case AtomicExpr::AO__atomic_xor_fetch:
1104 PostOp = llvm::Instruction::Xor;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001105 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001106 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00001107 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001108 case AtomicExpr::AO__atomic_fetch_xor:
1109 LibCallName = "__atomic_fetch_xor";
John McCall7f416cc2015-09-08 08:05:57 +00001110 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1111 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001112 break;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00001113 case AtomicExpr::AO__atomic_fetch_min:
Yaxun Liu39195062017-08-04 18:16:31 +00001114 case AtomicExpr::AO__opencl_atomic_fetch_min:
1115 LibCallName = E->getValueType()->isSignedIntegerType()
1116 ? "__atomic_fetch_min"
1117 : "__atomic_fetch_umin";
1118 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1119 LoweredMemTy, E->getExprLoc(), sizeChars);
1120 break;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00001121 case AtomicExpr::AO__atomic_fetch_max:
Yaxun Liu39195062017-08-04 18:16:31 +00001122 case AtomicExpr::AO__opencl_atomic_fetch_max:
1123 LibCallName = E->getValueType()->isSignedIntegerType()
1124 ? "__atomic_fetch_max"
1125 : "__atomic_fetch_umax";
1126 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1127 LoweredMemTy, E->getExprLoc(), sizeChars);
1128 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001129 // T __atomic_nand_fetch_N(T *mem, T val, int order)
James Y Knight81167fb2015-08-05 16:57:36 +00001130 // T __atomic_fetch_nand_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001131 case AtomicExpr::AO__atomic_nand_fetch:
1132 PostOp = llvm::Instruction::And; // the NOT is special cased below
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001133 LLVM_FALLTHROUGH;
James Y Knight81167fb2015-08-05 16:57:36 +00001134 case AtomicExpr::AO__atomic_fetch_nand:
1135 LibCallName = "__atomic_fetch_nand";
John McCall7f416cc2015-09-08 08:05:57 +00001136 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1137 MemTy, E->getExprLoc(), sizeChars);
James Y Knight81167fb2015-08-05 16:57:36 +00001138 break;
John McCallfc207f22013-03-07 21:37:12 +00001139 }
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001140
Yaxun Liu39195062017-08-04 18:16:31 +00001141 if (E->isOpenCL()) {
1142 LibCallName = std::string("__opencl") +
1143 StringRef(LibCallName).drop_front(1).str();
1144
1145 }
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001146 // Optimized functions have the size in their name.
1147 if (UseOptimizedLibcall)
1148 LibCallName += "_" + llvm::utostr(Size);
1149 // By default, assume we return a value of the atomic type.
1150 if (!HaveRetTy) {
1151 if (UseOptimizedLibcall) {
1152 // Value is returned directly.
David Majnemer0392cf82014-08-29 07:27:49 +00001153 // The function returns an appropriately sized integer type.
1154 RetTy = getContext().getIntTypeForBitwidth(
1155 getContext().toBits(sizeChars), /*Signed=*/false);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001156 } else {
1157 // Value is returned through parameter before the order.
1158 RetTy = getContext().VoidTy;
John McCall7f416cc2015-09-08 08:05:57 +00001159 Args.add(RValue::get(EmitCastToVoidPtr(Dest.getPointer())),
1160 getContext().VoidPtrTy);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001161 }
1162 }
John McCallfc207f22013-03-07 21:37:12 +00001163 // order is always the last parameter
1164 Args.add(RValue::get(Order),
1165 getContext().IntTy);
Yaxun Liu39195062017-08-04 18:16:31 +00001166 if (E->isOpenCL())
1167 Args.add(RValue::get(Scope), getContext().IntTy);
John McCallfc207f22013-03-07 21:37:12 +00001168
James Y Knight7aefb5b2015-11-12 18:37:29 +00001169 // PostOp is only needed for the atomic_*_fetch operations, and
1170 // thus is only needed for and implemented in the
1171 // UseOptimizedLibcall codepath.
1172 assert(UseOptimizedLibcall || !PostOp);
1173
David Majnemer659be552014-11-25 23:44:32 +00001174 RValue Res = emitAtomicLibcall(*this, LibCallName, RetTy, Args);
1175 // The value is returned directly from the libcall.
Tim Northovercc2a6e02015-11-09 19:56:35 +00001176 if (E->isCmpXChg())
David Majnemer659be552014-11-25 23:44:32 +00001177 return Res;
Tim Northovercc2a6e02015-11-09 19:56:35 +00001178
1179 // The value is returned directly for optimized libcalls but the expr
1180 // provided an out-param.
1181 if (UseOptimizedLibcall && Res.getScalarVal()) {
David Majnemer659be552014-11-25 23:44:32 +00001182 llvm::Value *ResVal = Res.getScalarVal();
James Y Knight7aefb5b2015-11-12 18:37:29 +00001183 if (PostOp) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00001184 llvm::Value *LoadVal1 = Args[1].getRValue(*this).getScalarVal();
James Y Knight7aefb5b2015-11-12 18:37:29 +00001185 ResVal = Builder.CreateBinOp(PostOp, ResVal, LoadVal1);
1186 }
1187 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
1188 ResVal = Builder.CreateNot(ResVal);
1189
Tim Northovercc2a6e02015-11-09 19:56:35 +00001190 Builder.CreateStore(
1191 ResVal,
1192 Builder.CreateBitCast(Dest, ResVal->getType()->getPointerTo()));
David Majnemer659be552014-11-25 23:44:32 +00001193 }
Tim Northovercc2a6e02015-11-09 19:56:35 +00001194
1195 if (RValTy->isVoidType())
1196 return RValue::get(nullptr);
1197
1198 return convertTempToRValue(
1199 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo()),
1200 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001201 }
1202
1203 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
Yaxun Liu39195062017-08-04 18:16:31 +00001204 E->getOp() == AtomicExpr::AO__opencl_atomic_store ||
John McCallfc207f22013-03-07 21:37:12 +00001205 E->getOp() == AtomicExpr::AO__atomic_store ||
1206 E->getOp() == AtomicExpr::AO__atomic_store_n;
1207 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00001208 E->getOp() == AtomicExpr::AO__opencl_atomic_load ||
John McCallfc207f22013-03-07 21:37:12 +00001209 E->getOp() == AtomicExpr::AO__atomic_load ||
1210 E->getOp() == AtomicExpr::AO__atomic_load_n;
1211
John McCallfc207f22013-03-07 21:37:12 +00001212 if (isa<llvm::ConstantInt>(Order)) {
JF Bastiendda2cb12016-04-18 18:01:49 +00001213 auto ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
1214 // We should not ever get to a case where the ordering isn't a valid C ABI
1215 // value, but it's hard to enforce that in general.
1216 if (llvm::isValidAtomicOrderingCABI(ord))
1217 switch ((llvm::AtomicOrderingCABI)ord) {
1218 case llvm::AtomicOrderingCABI::relaxed:
1219 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001220 llvm::AtomicOrdering::Monotonic, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001221 break;
1222 case llvm::AtomicOrderingCABI::consume:
1223 case llvm::AtomicOrderingCABI::acquire:
1224 if (IsStore)
1225 break; // Avoid crashing on code with undefined behavior
1226 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001227 llvm::AtomicOrdering::Acquire, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001228 break;
1229 case llvm::AtomicOrderingCABI::release:
1230 if (IsLoad)
1231 break; // Avoid crashing on code with undefined behavior
1232 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001233 llvm::AtomicOrdering::Release, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001234 break;
1235 case llvm::AtomicOrderingCABI::acq_rel:
1236 if (IsLoad || IsStore)
1237 break; // Avoid crashing on code with undefined behavior
1238 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001239 llvm::AtomicOrdering::AcquireRelease, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001240 break;
1241 case llvm::AtomicOrderingCABI::seq_cst:
1242 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001243 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001244 break;
1245 }
David Majnemeree8d04d2014-12-12 08:16:09 +00001246 if (RValTy->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001247 return RValue::get(nullptr);
Tim Northovercc2a6e02015-11-09 19:56:35 +00001248
1249 return convertTempToRValue(
Yaxun Liu8ab5ab02017-10-17 14:19:29 +00001250 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1251 Dest.getAddressSpace())),
Tim Northovercc2a6e02015-11-09 19:56:35 +00001252 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001253 }
1254
1255 // Long case, when Order isn't obviously constant.
1256
1257 // Create all the relevant BB's
Craig Topper8a13c412014-05-21 05:09:00 +00001258 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
1259 *ReleaseBB = nullptr, *AcqRelBB = nullptr,
1260 *SeqCstBB = nullptr;
John McCallfc207f22013-03-07 21:37:12 +00001261 MonotonicBB = createBasicBlock("monotonic", CurFn);
1262 if (!IsStore)
1263 AcquireBB = createBasicBlock("acquire", CurFn);
1264 if (!IsLoad)
1265 ReleaseBB = createBasicBlock("release", CurFn);
1266 if (!IsLoad && !IsStore)
1267 AcqRelBB = createBasicBlock("acqrel", CurFn);
1268 SeqCstBB = createBasicBlock("seqcst", CurFn);
1269 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
1270
1271 // Create the switch for the split
1272 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
1273 // doesn't matter unless someone is crazy enough to use something that
1274 // doesn't fold to a constant for the ordering.
1275 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
1276 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
1277
1278 // Emit all the different atomics
1279 Builder.SetInsertPoint(MonotonicBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001280 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001281 llvm::AtomicOrdering::Monotonic, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001282 Builder.CreateBr(ContBB);
1283 if (!IsStore) {
1284 Builder.SetInsertPoint(AcquireBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001285 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001286 llvm::AtomicOrdering::Acquire, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001287 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001288 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
Tim Northover514fc612014-03-13 19:25:52 +00001289 AcquireBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001290 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
Tim Northover514fc612014-03-13 19:25:52 +00001291 AcquireBB);
John McCallfc207f22013-03-07 21:37:12 +00001292 }
1293 if (!IsLoad) {
1294 Builder.SetInsertPoint(ReleaseBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001295 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001296 llvm::AtomicOrdering::Release, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001297 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001298 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::release),
Tim Northover514fc612014-03-13 19:25:52 +00001299 ReleaseBB);
John McCallfc207f22013-03-07 21:37:12 +00001300 }
1301 if (!IsLoad && !IsStore) {
1302 Builder.SetInsertPoint(AcqRelBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001303 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001304 llvm::AtomicOrdering::AcquireRelease, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001305 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001306 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acq_rel),
Tim Northover514fc612014-03-13 19:25:52 +00001307 AcqRelBB);
John McCallfc207f22013-03-07 21:37:12 +00001308 }
1309 Builder.SetInsertPoint(SeqCstBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001310 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001311 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001312 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001313 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
Tim Northover514fc612014-03-13 19:25:52 +00001314 SeqCstBB);
John McCallfc207f22013-03-07 21:37:12 +00001315
1316 // Cleanup and return
1317 Builder.SetInsertPoint(ContBB);
David Majnemeree8d04d2014-12-12 08:16:09 +00001318 if (RValTy->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001319 return RValue::get(nullptr);
Tim Northovercc2a6e02015-11-09 19:56:35 +00001320
1321 assert(Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits());
1322 return convertTempToRValue(
Yaxun Liu8ab5ab02017-10-17 14:19:29 +00001323 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1324 Dest.getAddressSpace())),
Tim Northovercc2a6e02015-11-09 19:56:35 +00001325 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001326}
John McCalla8ec7eb2013-03-07 21:37:17 +00001327
John McCall7f416cc2015-09-08 08:05:57 +00001328Address AtomicInfo::emitCastToAtomicIntPointer(Address addr) const {
John McCalla8ec7eb2013-03-07 21:37:17 +00001329 unsigned addrspace =
John McCall7f416cc2015-09-08 08:05:57 +00001330 cast<llvm::PointerType>(addr.getPointer()->getType())->getAddressSpace();
John McCalla8ec7eb2013-03-07 21:37:17 +00001331 llvm::IntegerType *ty =
1332 llvm::IntegerType::get(CGF.getLLVMContext(), AtomicSizeInBits);
1333 return CGF.Builder.CreateBitCast(addr, ty->getPointerTo(addrspace));
1334}
1335
Tim Northovercc2a6e02015-11-09 19:56:35 +00001336Address AtomicInfo::convertToAtomicIntPointer(Address Addr) const {
1337 llvm::Type *Ty = Addr.getElementType();
1338 uint64_t SourceSizeInBits = CGF.CGM.getDataLayout().getTypeSizeInBits(Ty);
1339 if (SourceSizeInBits != AtomicSizeInBits) {
1340 Address Tmp = CreateTempAlloca();
1341 CGF.Builder.CreateMemCpy(Tmp, Addr,
1342 std::min(AtomicSizeInBits, SourceSizeInBits) / 8);
1343 Addr = Tmp;
1344 }
1345
1346 return emitCastToAtomicIntPointer(Addr);
1347}
1348
John McCall7f416cc2015-09-08 08:05:57 +00001349RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
1350 AggValueSlot resultSlot,
1351 SourceLocation loc,
1352 bool asValue) const {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001353 if (LVal.isSimple()) {
1354 if (EvaluationKind == TEK_Aggregate)
1355 return resultSlot.asRValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001356
Alexey Bataevb57056f2015-01-22 06:17:56 +00001357 // Drill into the padding structure if we have one.
1358 if (hasPadding())
John McCall7f416cc2015-09-08 08:05:57 +00001359 addr = CGF.Builder.CreateStructGEP(addr, 0, CharUnits());
John McCalla8ec7eb2013-03-07 21:37:17 +00001360
Alexey Bataevb57056f2015-01-22 06:17:56 +00001361 // Otherwise, just convert the temporary to an r-value using the
1362 // normal conversion routine.
1363 return CGF.convertTempToRValue(addr, getValueType(), loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001364 }
John McCall7f416cc2015-09-08 08:05:57 +00001365 if (!asValue)
Alexey Bataevb8329262015-02-27 06:33:30 +00001366 // Get RValue from temp memory as atomic for non-simple lvalues
John McCall7f416cc2015-09-08 08:05:57 +00001367 return RValue::get(CGF.Builder.CreateLoad(addr));
David Blaikie1ed728c2015-04-05 22:45:47 +00001368 if (LVal.isBitField())
John McCall7f416cc2015-09-08 08:05:57 +00001369 return CGF.EmitLoadOfBitfieldLValue(
1370 LValue::MakeBitfield(addr, LVal.getBitFieldInfo(), LVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001371 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001372 if (LVal.isVectorElt())
John McCall7f416cc2015-09-08 08:05:57 +00001373 return CGF.EmitLoadOfLValue(
1374 LValue::MakeVectorElt(addr, LVal.getVectorIdx(), LVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001375 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001376 assert(LVal.isExtVectorElt());
1377 return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
John McCall7f416cc2015-09-08 08:05:57 +00001378 addr, LVal.getExtVectorElts(), LVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001379 LVal.getBaseInfo(), TBAAAccessInfo()));
John McCalla8ec7eb2013-03-07 21:37:17 +00001380}
1381
Alexey Bataevb8329262015-02-27 06:33:30 +00001382RValue AtomicInfo::ConvertIntToValueOrAtomic(llvm::Value *IntVal,
1383 AggValueSlot ResultSlot,
1384 SourceLocation Loc,
1385 bool AsValue) const {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001386 // Try not to in some easy cases.
1387 assert(IntVal->getType()->isIntegerTy() && "Expected integer value");
Alexey Bataevb8329262015-02-27 06:33:30 +00001388 if (getEvaluationKind() == TEK_Scalar &&
1389 (((!LVal.isBitField() ||
1390 LVal.getBitFieldInfo().Size == ValueSizeInBits) &&
1391 !hasPadding()) ||
1392 !AsValue)) {
1393 auto *ValTy = AsValue
1394 ? CGF.ConvertTypeForMem(ValueTy)
John McCall7f416cc2015-09-08 08:05:57 +00001395 : getAtomicAddress().getType()->getPointerElementType();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001396 if (ValTy->isIntegerTy()) {
1397 assert(IntVal->getType() == ValTy && "Different integer types.");
David Majnemereeaec262015-02-14 02:18:14 +00001398 return RValue::get(CGF.EmitFromMemory(IntVal, ValueTy));
Alexey Bataev452d8e12014-12-15 05:25:25 +00001399 } else if (ValTy->isPointerTy())
1400 return RValue::get(CGF.Builder.CreateIntToPtr(IntVal, ValTy));
1401 else if (llvm::CastInst::isBitCastable(IntVal->getType(), ValTy))
1402 return RValue::get(CGF.Builder.CreateBitCast(IntVal, ValTy));
1403 }
1404
1405 // Create a temporary. This needs to be big enough to hold the
1406 // atomic integer.
John McCall7f416cc2015-09-08 08:05:57 +00001407 Address Temp = Address::invalid();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001408 bool TempIsVolatile = false;
Alexey Bataevb8329262015-02-27 06:33:30 +00001409 if (AsValue && getEvaluationKind() == TEK_Aggregate) {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001410 assert(!ResultSlot.isIgnored());
John McCall7f416cc2015-09-08 08:05:57 +00001411 Temp = ResultSlot.getAddress();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001412 TempIsVolatile = ResultSlot.isVolatile();
1413 } else {
Alexey Bataevb8329262015-02-27 06:33:30 +00001414 Temp = CreateTempAlloca();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001415 }
1416
1417 // Slam the integer into the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00001418 Address CastTemp = emitCastToAtomicIntPointer(Temp);
1419 CGF.Builder.CreateStore(IntVal, CastTemp)
Alexey Bataev452d8e12014-12-15 05:25:25 +00001420 ->setVolatile(TempIsVolatile);
1421
John McCall7f416cc2015-09-08 08:05:57 +00001422 return convertAtomicTempToRValue(Temp, ResultSlot, Loc, AsValue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001423}
1424
1425void AtomicInfo::EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
1426 llvm::AtomicOrdering AO, bool) {
1427 // void __atomic_load(size_t size, void *mem, void *return, int order);
1428 CallArgList Args;
1429 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001430 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001431 CGF.getContext().VoidPtrTy);
1432 Args.add(RValue::get(CGF.EmitCastToVoidPtr(AddForLoaded)),
1433 CGF.getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001434 Args.add(
1435 RValue::get(llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(AO))),
1436 CGF.getContext().IntTy);
Alexey Bataevb8329262015-02-27 06:33:30 +00001437 emitAtomicLibcall(CGF, "__atomic_load", CGF.getContext().VoidTy, Args);
1438}
1439
1440llvm::Value *AtomicInfo::EmitAtomicLoadOp(llvm::AtomicOrdering AO,
1441 bool IsVolatile) {
1442 // Okay, we're doing this natively.
John McCall7f416cc2015-09-08 08:05:57 +00001443 Address Addr = getAtomicAddressAsAtomicIntPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +00001444 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Addr, "atomic-load");
1445 Load->setAtomic(AO);
1446
1447 // Other decoration.
Alexey Bataevb8329262015-02-27 06:33:30 +00001448 if (IsVolatile)
1449 Load->setVolatile(true);
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001450 CGF.CGM.DecorateInstructionWithTBAA(Load, LVal.getTBAAInfo());
Alexey Bataevb8329262015-02-27 06:33:30 +00001451 return Load;
Alexey Bataev452d8e12014-12-15 05:25:25 +00001452}
1453
David Majnemera5b195a2015-02-14 01:35:12 +00001454/// An LValue is a candidate for having its loads and stores be made atomic if
1455/// we are operating under /volatile:ms *and* the LValue itself is volatile and
1456/// performing such an operation can be performed without a libcall.
1457bool CodeGenFunction::LValueIsSuitableForInlineAtomic(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001458 if (!CGM.getCodeGenOpts().MSVolatile) return false;
David Majnemera5b195a2015-02-14 01:35:12 +00001459 AtomicInfo AI(*this, LV);
1460 bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
1461 // An atomic is inline if we don't need to use a libcall.
1462 bool AtomicIsInline = !AI.shouldUseLibcall();
David Majnemerfc80b6e2016-01-22 16:36:44 +00001463 // MSVC doesn't seem to do this for types wider than a pointer.
David Majnemera38c9f12016-05-24 16:09:25 +00001464 if (getContext().getTypeSize(LV.getType()) >
David Majnemerfc80b6e2016-01-22 16:36:44 +00001465 getContext().getTypeSize(getContext().getIntPtrType()))
1466 return false;
David Majnemera38c9f12016-05-24 16:09:25 +00001467 return IsVolatile && AtomicIsInline;
David Majnemera5b195a2015-02-14 01:35:12 +00001468}
1469
1470RValue CodeGenFunction::EmitAtomicLoad(LValue LV, SourceLocation SL,
1471 AggValueSlot Slot) {
1472 llvm::AtomicOrdering AO;
1473 bool IsVolatile = LV.isVolatileQualified();
1474 if (LV.getType()->isAtomicType()) {
JF Bastien92f4ef12016-04-06 17:26:42 +00001475 AO = llvm::AtomicOrdering::SequentiallyConsistent;
David Majnemera5b195a2015-02-14 01:35:12 +00001476 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00001477 AO = llvm::AtomicOrdering::Acquire;
David Majnemera5b195a2015-02-14 01:35:12 +00001478 IsVolatile = true;
1479 }
1480 return EmitAtomicLoad(LV, SL, AO, IsVolatile, Slot);
1481}
1482
Alexey Bataevb8329262015-02-27 06:33:30 +00001483RValue AtomicInfo::EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
1484 bool AsValue, llvm::AtomicOrdering AO,
1485 bool IsVolatile) {
1486 // Check whether we should use a library call.
1487 if (shouldUseLibcall()) {
John McCall7f416cc2015-09-08 08:05:57 +00001488 Address TempAddr = Address::invalid();
Alexey Bataevb8329262015-02-27 06:33:30 +00001489 if (LVal.isSimple() && !ResultSlot.isIgnored()) {
1490 assert(getEvaluationKind() == TEK_Aggregate);
John McCall7f416cc2015-09-08 08:05:57 +00001491 TempAddr = ResultSlot.getAddress();
Alexey Bataevb8329262015-02-27 06:33:30 +00001492 } else
1493 TempAddr = CreateTempAlloca();
1494
John McCall7f416cc2015-09-08 08:05:57 +00001495 EmitAtomicLoadLibcall(TempAddr.getPointer(), AO, IsVolatile);
Alexey Bataevb8329262015-02-27 06:33:30 +00001496
1497 // Okay, turn that back into the original value or whole atomic (for
1498 // non-simple lvalues) type.
John McCall7f416cc2015-09-08 08:05:57 +00001499 return convertAtomicTempToRValue(TempAddr, ResultSlot, Loc, AsValue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001500 }
1501
1502 // Okay, we're doing this natively.
1503 auto *Load = EmitAtomicLoadOp(AO, IsVolatile);
1504
1505 // If we're ignoring an aggregate return, don't do anything.
1506 if (getEvaluationKind() == TEK_Aggregate && ResultSlot.isIgnored())
John McCall7f416cc2015-09-08 08:05:57 +00001507 return RValue::getAggregate(Address::invalid(), false);
Alexey Bataevb8329262015-02-27 06:33:30 +00001508
1509 // Okay, turn that back into the original value or atomic (for non-simple
1510 // lvalues) type.
1511 return ConvertIntToValueOrAtomic(Load, ResultSlot, Loc, AsValue);
1512}
1513
John McCalla8ec7eb2013-03-07 21:37:17 +00001514/// Emit a load from an l-value of atomic type. Note that the r-value
1515/// we produce is an r-value of the atomic *value* type.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001516RValue CodeGenFunction::EmitAtomicLoad(LValue src, SourceLocation loc,
David Majnemera5b195a2015-02-14 01:35:12 +00001517 llvm::AtomicOrdering AO, bool IsVolatile,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001518 AggValueSlot resultSlot) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001519 AtomicInfo Atomics(*this, src);
1520 return Atomics.EmitAtomicLoad(resultSlot, loc, /*AsValue=*/true, AO,
1521 IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001522}
1523
John McCalla8ec7eb2013-03-07 21:37:17 +00001524/// Copy an r-value into memory as part of storing to an atomic type.
1525/// This needs to create a bit-pattern suitable for atomic operations.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001526void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
1527 assert(LVal.isSimple());
John McCalla8ec7eb2013-03-07 21:37:17 +00001528 // If we have an r-value, the rvalue should be of the atomic type,
1529 // which means that the caller is responsible for having zeroed
1530 // any padding. Just do an aggregate copy of that type.
1531 if (rvalue.isAggregate()) {
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001532 LValue Dest = CGF.MakeAddrLValue(getAtomicAddress(), getAtomicType());
1533 LValue Src = CGF.MakeAddrLValue(rvalue.getAggregateAddress(),
1534 getAtomicType());
1535 bool IsVolatile = rvalue.isVolatileQualified() ||
1536 LVal.isVolatileQualified();
Richard Smithe78fac52018-04-05 20:52:58 +00001537 CGF.EmitAggregateCopy(Dest, Src, getAtomicType(),
1538 AggValueSlot::DoesNotOverlap, IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001539 return;
1540 }
1541
1542 // Okay, otherwise we're copying stuff.
1543
1544 // Zero out the buffer if necessary.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001545 emitMemSetZeroIfNecessary();
John McCalla8ec7eb2013-03-07 21:37:17 +00001546
1547 // Drill past the padding if present.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001548 LValue TempLVal = projectValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001549
1550 // Okay, store the rvalue in.
1551 if (rvalue.isScalar()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001552 CGF.EmitStoreOfScalar(rvalue.getScalarVal(), TempLVal, /*init*/ true);
John McCalla8ec7eb2013-03-07 21:37:17 +00001553 } else {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001554 CGF.EmitStoreOfComplex(rvalue.getComplexVal(), TempLVal, /*init*/ true);
John McCalla8ec7eb2013-03-07 21:37:17 +00001555 }
1556}
1557
1558
1559/// Materialize an r-value into memory for the purposes of storing it
1560/// to an atomic type.
John McCall7f416cc2015-09-08 08:05:57 +00001561Address AtomicInfo::materializeRValue(RValue rvalue) const {
John McCalla8ec7eb2013-03-07 21:37:17 +00001562 // Aggregate r-values are already in memory, and EmitAtomicStore
1563 // requires them to be values of the atomic type.
1564 if (rvalue.isAggregate())
John McCall7f416cc2015-09-08 08:05:57 +00001565 return rvalue.getAggregateAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +00001566
1567 // Otherwise, make a temporary and materialize into it.
John McCall7f416cc2015-09-08 08:05:57 +00001568 LValue TempLV = CGF.MakeAddrLValue(CreateTempAlloca(), getAtomicType());
Alexey Bataevb8329262015-02-27 06:33:30 +00001569 AtomicInfo Atomics(CGF, TempLV);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001570 Atomics.emitCopyIntoMemory(rvalue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001571 return TempLV.getAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +00001572}
1573
Alexey Bataev452d8e12014-12-15 05:25:25 +00001574llvm::Value *AtomicInfo::convertRValueToInt(RValue RVal) const {
1575 // If we've got a scalar value of the right size, try to avoid going
1576 // through memory.
Alexey Bataevb8329262015-02-27 06:33:30 +00001577 if (RVal.isScalar() && (!hasPadding() || !LVal.isSimple())) {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001578 llvm::Value *Value = RVal.getScalarVal();
1579 if (isa<llvm::IntegerType>(Value->getType()))
Alexey Bataevb4505a72015-03-30 05:20:59 +00001580 return CGF.EmitToMemory(Value, ValueTy);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001581 else {
Alexey Bataevb8329262015-02-27 06:33:30 +00001582 llvm::IntegerType *InputIntTy = llvm::IntegerType::get(
1583 CGF.getLLVMContext(),
1584 LVal.isSimple() ? getValueSizeInBits() : getAtomicSizeInBits());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001585 if (isa<llvm::PointerType>(Value->getType()))
1586 return CGF.Builder.CreatePtrToInt(Value, InputIntTy);
1587 else if (llvm::BitCastInst::isBitCastable(Value->getType(), InputIntTy))
1588 return CGF.Builder.CreateBitCast(Value, InputIntTy);
1589 }
1590 }
1591 // Otherwise, we need to go through memory.
1592 // Put the r-value in memory.
John McCall7f416cc2015-09-08 08:05:57 +00001593 Address Addr = materializeRValue(RVal);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001594
1595 // Cast the temporary to the atomic int type and pull a value out.
1596 Addr = emitCastToAtomicIntPointer(Addr);
John McCall7f416cc2015-09-08 08:05:57 +00001597 return CGF.Builder.CreateLoad(Addr);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001598}
1599
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001600std::pair<llvm::Value *, llvm::Value *> AtomicInfo::EmitAtomicCompareExchangeOp(
1601 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
1602 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001603 // Do the atomic store.
John McCall7f416cc2015-09-08 08:05:57 +00001604 Address Addr = getAtomicAddressAsAtomicIntPointer();
1605 auto *Inst = CGF.Builder.CreateAtomicCmpXchg(Addr.getPointer(),
1606 ExpectedVal, DesiredVal,
Alexey Bataevb4505a72015-03-30 05:20:59 +00001607 Success, Failure);
Alexey Bataevb8329262015-02-27 06:33:30 +00001608 // Other decoration.
1609 Inst->setVolatile(LVal.isVolatileQualified());
1610 Inst->setWeak(IsWeak);
1611
1612 // Okay, turn that back into the original value type.
1613 auto *PreviousVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/0);
1614 auto *SuccessFailureVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/1);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001615 return std::make_pair(PreviousVal, SuccessFailureVal);
Alexey Bataevb8329262015-02-27 06:33:30 +00001616}
1617
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001618llvm::Value *
1619AtomicInfo::EmitAtomicCompareExchangeLibcall(llvm::Value *ExpectedAddr,
1620 llvm::Value *DesiredAddr,
Alexey Bataevb8329262015-02-27 06:33:30 +00001621 llvm::AtomicOrdering Success,
1622 llvm::AtomicOrdering Failure) {
1623 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
1624 // void *desired, int success, int failure);
1625 CallArgList Args;
1626 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001627 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001628 CGF.getContext().VoidPtrTy);
1629 Args.add(RValue::get(CGF.EmitCastToVoidPtr(ExpectedAddr)),
1630 CGF.getContext().VoidPtrTy);
1631 Args.add(RValue::get(CGF.EmitCastToVoidPtr(DesiredAddr)),
1632 CGF.getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001633 Args.add(RValue::get(
1634 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Success))),
Alexey Bataevb8329262015-02-27 06:33:30 +00001635 CGF.getContext().IntTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001636 Args.add(RValue::get(
1637 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Failure))),
Alexey Bataevb8329262015-02-27 06:33:30 +00001638 CGF.getContext().IntTy);
1639 auto SuccessFailureRVal = emitAtomicLibcall(CGF, "__atomic_compare_exchange",
1640 CGF.getContext().BoolTy, Args);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001641
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001642 return SuccessFailureRVal.getScalarVal();
Alexey Bataevb8329262015-02-27 06:33:30 +00001643}
1644
Alexey Bataevb4505a72015-03-30 05:20:59 +00001645std::pair<RValue, llvm::Value *> AtomicInfo::EmitAtomicCompareExchange(
Alexey Bataevb8329262015-02-27 06:33:30 +00001646 RValue Expected, RValue Desired, llvm::AtomicOrdering Success,
1647 llvm::AtomicOrdering Failure, bool IsWeak) {
JF Bastiendd11ee72016-04-06 23:37:36 +00001648 if (isStrongerThan(Failure, Success))
1649 // Don't assert on undefined behavior "failure argument shall be no stronger
1650 // than the success argument".
Alexey Bataevb8329262015-02-27 06:33:30 +00001651 Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(Success);
1652
1653 // Check whether we should use a library call.
1654 if (shouldUseLibcall()) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001655 // Produce a source address.
John McCall7f416cc2015-09-08 08:05:57 +00001656 Address ExpectedAddr = materializeRValue(Expected);
1657 Address DesiredAddr = materializeRValue(Desired);
1658 auto *Res = EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1659 DesiredAddr.getPointer(),
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001660 Success, Failure);
1661 return std::make_pair(
John McCall7f416cc2015-09-08 08:05:57 +00001662 convertAtomicTempToRValue(ExpectedAddr, AggValueSlot::ignored(),
1663 SourceLocation(), /*AsValue=*/false),
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001664 Res);
Alexey Bataevb8329262015-02-27 06:33:30 +00001665 }
1666
1667 // If we've got a scalar value of the right size, try to avoid going
1668 // through memory.
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001669 auto *ExpectedVal = convertRValueToInt(Expected);
1670 auto *DesiredVal = convertRValueToInt(Desired);
1671 auto Res = EmitAtomicCompareExchangeOp(ExpectedVal, DesiredVal, Success,
1672 Failure, IsWeak);
1673 return std::make_pair(
1674 ConvertIntToValueOrAtomic(Res.first, AggValueSlot::ignored(),
1675 SourceLocation(), /*AsValue=*/false),
1676 Res.second);
1677}
1678
1679static void
1680EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal,
1681 const llvm::function_ref<RValue(RValue)> &UpdateOp,
John McCall7f416cc2015-09-08 08:05:57 +00001682 Address DesiredAddr) {
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001683 RValue UpRVal;
1684 LValue AtomicLVal = Atomics.getAtomicLValue();
1685 LValue DesiredLVal;
1686 if (AtomicLVal.isSimple()) {
1687 UpRVal = OldRVal;
John McCall7f416cc2015-09-08 08:05:57 +00001688 DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001689 } else {
1690 // Build new lvalue for temp address
John McCall7f416cc2015-09-08 08:05:57 +00001691 Address Ptr = Atomics.materializeRValue(OldRVal);
1692 LValue UpdateLVal;
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001693 if (AtomicLVal.isBitField()) {
1694 UpdateLVal =
1695 LValue::MakeBitfield(Ptr, AtomicLVal.getBitFieldInfo(),
John McCall7f416cc2015-09-08 08:05:57 +00001696 AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001697 AtomicLVal.getBaseInfo(),
1698 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001699 DesiredLVal =
1700 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001701 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1702 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001703 } else if (AtomicLVal.isVectorElt()) {
1704 UpdateLVal = LValue::MakeVectorElt(Ptr, AtomicLVal.getVectorIdx(),
1705 AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001706 AtomicLVal.getBaseInfo(),
1707 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001708 DesiredLVal = LValue::MakeVectorElt(
1709 DesiredAddr, AtomicLVal.getVectorIdx(), AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001710 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001711 } else {
1712 assert(AtomicLVal.isExtVectorElt());
1713 UpdateLVal = LValue::MakeExtVectorElt(Ptr, AtomicLVal.getExtVectorElts(),
1714 AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001715 AtomicLVal.getBaseInfo(),
1716 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001717 DesiredLVal = LValue::MakeExtVectorElt(
1718 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001719 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001720 }
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001721 UpRVal = CGF.EmitLoadOfLValue(UpdateLVal, SourceLocation());
1722 }
1723 // Store new value in the corresponding memory area
1724 RValue NewRVal = UpdateOp(UpRVal);
1725 if (NewRVal.isScalar()) {
1726 CGF.EmitStoreThroughLValue(NewRVal, DesiredLVal);
1727 } else {
1728 assert(NewRVal.isComplex());
1729 CGF.EmitStoreOfComplex(NewRVal.getComplexVal(), DesiredLVal,
1730 /*isInit=*/false);
1731 }
1732}
1733
1734void AtomicInfo::EmitAtomicUpdateLibcall(
1735 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1736 bool IsVolatile) {
1737 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1738
John McCall7f416cc2015-09-08 08:05:57 +00001739 Address ExpectedAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001740
John McCall7f416cc2015-09-08 08:05:57 +00001741 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001742 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1743 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1744 CGF.EmitBlock(ContBB);
John McCall7f416cc2015-09-08 08:05:57 +00001745 Address DesiredAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001746 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001747 requiresMemSetZero(getAtomicAddress().getElementType())) {
1748 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1749 CGF.Builder.CreateStore(OldVal, DesiredAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001750 }
John McCall7f416cc2015-09-08 08:05:57 +00001751 auto OldRVal = convertAtomicTempToRValue(ExpectedAddr,
1752 AggValueSlot::ignored(),
1753 SourceLocation(), /*AsValue=*/false);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001754 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, DesiredAddr);
1755 auto *Res =
John McCall7f416cc2015-09-08 08:05:57 +00001756 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1757 DesiredAddr.getPointer(),
1758 AO, Failure);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001759 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1760 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1761}
1762
1763void AtomicInfo::EmitAtomicUpdateOp(
1764 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1765 bool IsVolatile) {
1766 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1767
1768 // Do the atomic load.
1769 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1770 // For non-simple lvalues perform compare-and-swap procedure.
1771 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1772 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1773 auto *CurBB = CGF.Builder.GetInsertBlock();
1774 CGF.EmitBlock(ContBB);
1775 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1776 /*NumReservedValues=*/2);
1777 PHI->addIncoming(OldVal, CurBB);
John McCall7f416cc2015-09-08 08:05:57 +00001778 Address NewAtomicAddr = CreateTempAlloca();
1779 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001780 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001781 requiresMemSetZero(getAtomicAddress().getElementType())) {
1782 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001783 }
1784 auto OldRVal = ConvertIntToValueOrAtomic(PHI, AggValueSlot::ignored(),
1785 SourceLocation(), /*AsValue=*/false);
1786 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, NewAtomicAddr);
John McCall7f416cc2015-09-08 08:05:57 +00001787 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001788 // Try to write new value using cmpxchg operation
1789 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1790 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1791 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1792 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1793}
1794
1795static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics,
John McCall7f416cc2015-09-08 08:05:57 +00001796 RValue UpdateRVal, Address DesiredAddr) {
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001797 LValue AtomicLVal = Atomics.getAtomicLValue();
1798 LValue DesiredLVal;
1799 // Build new lvalue for temp address
1800 if (AtomicLVal.isBitField()) {
1801 DesiredLVal =
1802 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001803 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1804 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001805 } else if (AtomicLVal.isVectorElt()) {
1806 DesiredLVal =
1807 LValue::MakeVectorElt(DesiredAddr, AtomicLVal.getVectorIdx(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001808 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1809 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001810 } else {
1811 assert(AtomicLVal.isExtVectorElt());
1812 DesiredLVal = LValue::MakeExtVectorElt(
1813 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001814 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001815 }
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001816 // Store new value in the corresponding memory area
1817 assert(UpdateRVal.isScalar());
1818 CGF.EmitStoreThroughLValue(UpdateRVal, DesiredLVal);
1819}
1820
1821void AtomicInfo::EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
1822 RValue UpdateRVal, bool IsVolatile) {
1823 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1824
John McCall7f416cc2015-09-08 08:05:57 +00001825 Address ExpectedAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001826
John McCall7f416cc2015-09-08 08:05:57 +00001827 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001828 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1829 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1830 CGF.EmitBlock(ContBB);
John McCall7f416cc2015-09-08 08:05:57 +00001831 Address DesiredAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001832 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001833 requiresMemSetZero(getAtomicAddress().getElementType())) {
1834 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1835 CGF.Builder.CreateStore(OldVal, DesiredAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001836 }
1837 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, DesiredAddr);
1838 auto *Res =
John McCall7f416cc2015-09-08 08:05:57 +00001839 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1840 DesiredAddr.getPointer(),
1841 AO, Failure);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001842 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1843 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1844}
1845
1846void AtomicInfo::EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRVal,
1847 bool IsVolatile) {
1848 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1849
1850 // Do the atomic load.
1851 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1852 // For non-simple lvalues perform compare-and-swap procedure.
1853 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1854 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1855 auto *CurBB = CGF.Builder.GetInsertBlock();
1856 CGF.EmitBlock(ContBB);
1857 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1858 /*NumReservedValues=*/2);
1859 PHI->addIncoming(OldVal, CurBB);
John McCall7f416cc2015-09-08 08:05:57 +00001860 Address NewAtomicAddr = CreateTempAlloca();
1861 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001862 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001863 requiresMemSetZero(getAtomicAddress().getElementType())) {
1864 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001865 }
1866 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, NewAtomicAddr);
John McCall7f416cc2015-09-08 08:05:57 +00001867 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001868 // Try to write new value using cmpxchg operation
1869 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1870 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1871 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1872 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1873}
1874
1875void AtomicInfo::EmitAtomicUpdate(
1876 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1877 bool IsVolatile) {
1878 if (shouldUseLibcall()) {
1879 EmitAtomicUpdateLibcall(AO, UpdateOp, IsVolatile);
1880 } else {
1881 EmitAtomicUpdateOp(AO, UpdateOp, IsVolatile);
1882 }
1883}
1884
1885void AtomicInfo::EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
1886 bool IsVolatile) {
1887 if (shouldUseLibcall()) {
1888 EmitAtomicUpdateLibcall(AO, UpdateRVal, IsVolatile);
1889 } else {
1890 EmitAtomicUpdateOp(AO, UpdateRVal, IsVolatile);
1891 }
Alexey Bataevb8329262015-02-27 06:33:30 +00001892}
1893
David Majnemera5b195a2015-02-14 01:35:12 +00001894void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue lvalue,
1895 bool isInit) {
1896 bool IsVolatile = lvalue.isVolatileQualified();
1897 llvm::AtomicOrdering AO;
1898 if (lvalue.getType()->isAtomicType()) {
JF Bastien92f4ef12016-04-06 17:26:42 +00001899 AO = llvm::AtomicOrdering::SequentiallyConsistent;
David Majnemera5b195a2015-02-14 01:35:12 +00001900 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00001901 AO = llvm::AtomicOrdering::Release;
David Majnemera5b195a2015-02-14 01:35:12 +00001902 IsVolatile = true;
1903 }
1904 return EmitAtomicStore(rvalue, lvalue, AO, IsVolatile, isInit);
1905}
1906
John McCalla8ec7eb2013-03-07 21:37:17 +00001907/// Emit a store to an l-value of atomic type.
1908///
1909/// Note that the r-value is expected to be an r-value *of the atomic
1910/// type*; this means that for aggregate r-values, it should include
1911/// storage for any padding that was necessary.
David Majnemera5b195a2015-02-14 01:35:12 +00001912void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue dest,
1913 llvm::AtomicOrdering AO, bool IsVolatile,
1914 bool isInit) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001915 // If this is an aggregate r-value, it should agree in type except
1916 // maybe for address-space qualification.
1917 assert(!rvalue.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001918 rvalue.getAggregateAddress().getElementType()
1919 == dest.getAddress().getElementType());
John McCalla8ec7eb2013-03-07 21:37:17 +00001920
1921 AtomicInfo atomics(*this, dest);
Alexey Bataevb8329262015-02-27 06:33:30 +00001922 LValue LVal = atomics.getAtomicLValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001923
1924 // If this is an initialization, just put the value there normally.
Alexey Bataevb8329262015-02-27 06:33:30 +00001925 if (LVal.isSimple()) {
1926 if (isInit) {
1927 atomics.emitCopyIntoMemory(rvalue);
1928 return;
1929 }
1930
1931 // Check whether we should use a library call.
1932 if (atomics.shouldUseLibcall()) {
1933 // Produce a source address.
John McCall7f416cc2015-09-08 08:05:57 +00001934 Address srcAddr = atomics.materializeRValue(rvalue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001935
1936 // void __atomic_store(size_t size, void *mem, void *val, int order)
1937 CallArgList args;
1938 args.add(RValue::get(atomics.getAtomicSizeValue()),
1939 getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001940 args.add(RValue::get(EmitCastToVoidPtr(atomics.getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001941 getContext().VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001942 args.add(RValue::get(EmitCastToVoidPtr(srcAddr.getPointer())),
1943 getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001944 args.add(
1945 RValue::get(llvm::ConstantInt::get(IntTy, (int)llvm::toCABI(AO))),
1946 getContext().IntTy);
Alexey Bataevb8329262015-02-27 06:33:30 +00001947 emitAtomicLibcall(*this, "__atomic_store", getContext().VoidTy, args);
1948 return;
1949 }
1950
1951 // Okay, we're doing this natively.
1952 llvm::Value *intValue = atomics.convertRValueToInt(rvalue);
1953
1954 // Do the atomic store.
John McCall7f416cc2015-09-08 08:05:57 +00001955 Address addr =
Alexey Bataevb8329262015-02-27 06:33:30 +00001956 atomics.emitCastToAtomicIntPointer(atomics.getAtomicAddress());
1957 intValue = Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00001958 intValue, addr.getElementType(), /*isSigned=*/false);
Alexey Bataevb8329262015-02-27 06:33:30 +00001959 llvm::StoreInst *store = Builder.CreateStore(intValue, addr);
1960
1961 // Initializations don't need to be atomic.
1962 if (!isInit)
1963 store->setAtomic(AO);
1964
1965 // Other decoration.
Alexey Bataevb8329262015-02-27 06:33:30 +00001966 if (IsVolatile)
1967 store->setVolatile(true);
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001968 CGM.DecorateInstructionWithTBAA(store, dest.getTBAAInfo());
John McCalla8ec7eb2013-03-07 21:37:17 +00001969 return;
1970 }
1971
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001972 // Emit simple atomic update operation.
1973 atomics.EmitAtomicUpdate(AO, rvalue, IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001974}
1975
Alexey Bataev452d8e12014-12-15 05:25:25 +00001976/// Emit a compare-and-exchange op for atomic type.
1977///
Alexey Bataevb4505a72015-03-30 05:20:59 +00001978std::pair<RValue, llvm::Value *> CodeGenFunction::EmitAtomicCompareExchange(
Alexey Bataev452d8e12014-12-15 05:25:25 +00001979 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
1980 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak,
1981 AggValueSlot Slot) {
1982 // If this is an aggregate r-value, it should agree in type except
1983 // maybe for address-space qualification.
1984 assert(!Expected.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001985 Expected.getAggregateAddress().getElementType() ==
1986 Obj.getAddress().getElementType());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001987 assert(!Desired.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001988 Desired.getAggregateAddress().getElementType() ==
1989 Obj.getAddress().getElementType());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001990 AtomicInfo Atomics(*this, Obj);
1991
Alexey Bataevb4505a72015-03-30 05:20:59 +00001992 return Atomics.EmitAtomicCompareExchange(Expected, Desired, Success, Failure,
1993 IsWeak);
1994}
1995
1996void CodeGenFunction::EmitAtomicUpdate(
1997 LValue LVal, llvm::AtomicOrdering AO,
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001998 const llvm::function_ref<RValue(RValue)> &UpdateOp, bool IsVolatile) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00001999 AtomicInfo Atomics(*this, LVal);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00002000 Atomics.EmitAtomicUpdate(AO, UpdateOp, IsVolatile);
Alexey Bataev452d8e12014-12-15 05:25:25 +00002001}
2002
John McCalla8ec7eb2013-03-07 21:37:17 +00002003void CodeGenFunction::EmitAtomicInit(Expr *init, LValue dest) {
2004 AtomicInfo atomics(*this, dest);
2005
2006 switch (atomics.getEvaluationKind()) {
2007 case TEK_Scalar: {
2008 llvm::Value *value = EmitScalarExpr(init);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002009 atomics.emitCopyIntoMemory(RValue::get(value));
John McCalla8ec7eb2013-03-07 21:37:17 +00002010 return;
2011 }
2012
2013 case TEK_Complex: {
2014 ComplexPairTy value = EmitComplexExpr(init);
Alexey Bataevb57056f2015-01-22 06:17:56 +00002015 atomics.emitCopyIntoMemory(RValue::getComplex(value));
John McCalla8ec7eb2013-03-07 21:37:17 +00002016 return;
2017 }
2018
2019 case TEK_Aggregate: {
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002020 // Fix up the destination if the initializer isn't an expression
2021 // of atomic type.
2022 bool Zeroed = false;
John McCalla8ec7eb2013-03-07 21:37:17 +00002023 if (!init->getType()->isAtomicType()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002024 Zeroed = atomics.emitMemSetZeroIfNecessary();
2025 dest = atomics.projectValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00002026 }
2027
2028 // Evaluate the expression directly into the destination.
2029 AggValueSlot slot = AggValueSlot::forLValue(dest,
2030 AggValueSlot::IsNotDestructed,
2031 AggValueSlot::DoesNotNeedGCBarriers,
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002032 AggValueSlot::IsNotAliased,
Richard Smithe78fac52018-04-05 20:52:58 +00002033 AggValueSlot::DoesNotOverlap,
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002034 Zeroed ? AggValueSlot::IsZeroed :
2035 AggValueSlot::IsNotZeroed);
2036
John McCalla8ec7eb2013-03-07 21:37:17 +00002037 EmitAggExpr(init, slot);
2038 return;
2039 }
2040 }
2041 llvm_unreachable("bad evaluation kind");
2042}