blob: 68437866e478014213d335683c3fd23fadbafbc1 [file] [log] [blame]
John McCallfc207f22013-03-07 21:37:12 +00001//===--- CGAtomic.cpp - Emit LLVM IR for atomic operations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the code for emitting atomic operations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CGCall.h"
16#include "CodeGenModule.h"
17#include "clang/AST/ASTContext.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000018#include "clang/CodeGen/CGFunctionInfo.h"
Ed Schoutenc7e82bd2013-05-31 19:27:59 +000019#include "llvm/ADT/StringExtras.h"
John McCallfc207f22013-03-07 21:37:12 +000020#include "llvm/IR/DataLayout.h"
21#include "llvm/IR/Intrinsics.h"
John McCalla8ec7eb2013-03-07 21:37:17 +000022#include "llvm/IR/Operator.h"
John McCallfc207f22013-03-07 21:37:12 +000023
24using namespace clang;
25using namespace CodeGen;
26
John McCalla8ec7eb2013-03-07 21:37:17 +000027namespace {
28 class AtomicInfo {
29 CodeGenFunction &CGF;
30 QualType AtomicTy;
31 QualType ValueTy;
32 uint64_t AtomicSizeInBits;
33 uint64_t ValueSizeInBits;
34 CharUnits AtomicAlign;
35 CharUnits ValueAlign;
36 CharUnits LValueAlign;
37 TypeEvaluationKind EvaluationKind;
38 bool UseLibcall;
39 public:
40 AtomicInfo(CodeGenFunction &CGF, LValue &lvalue) : CGF(CGF) {
41 assert(lvalue.isSimple());
42
43 AtomicTy = lvalue.getType();
44 ValueTy = AtomicTy->castAs<AtomicType>()->getValueType();
45 EvaluationKind = CGF.getEvaluationKind(ValueTy);
46
47 ASTContext &C = CGF.getContext();
48
49 uint64_t valueAlignInBits;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +000050 std::tie(ValueSizeInBits, valueAlignInBits) = C.getTypeInfo(ValueTy);
John McCalla8ec7eb2013-03-07 21:37:17 +000051
52 uint64_t atomicAlignInBits;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +000053 std::tie(AtomicSizeInBits, atomicAlignInBits) = C.getTypeInfo(AtomicTy);
John McCalla8ec7eb2013-03-07 21:37:17 +000054
55 assert(ValueSizeInBits <= AtomicSizeInBits);
56 assert(valueAlignInBits <= atomicAlignInBits);
57
58 AtomicAlign = C.toCharUnitsFromBits(atomicAlignInBits);
59 ValueAlign = C.toCharUnitsFromBits(valueAlignInBits);
60 if (lvalue.getAlignment().isZero())
61 lvalue.setAlignment(AtomicAlign);
62
63 UseLibcall =
64 (AtomicSizeInBits > uint64_t(C.toBits(lvalue.getAlignment())) ||
65 AtomicSizeInBits > C.getTargetInfo().getMaxAtomicInlineWidth());
66 }
67
68 QualType getAtomicType() const { return AtomicTy; }
69 QualType getValueType() const { return ValueTy; }
70 CharUnits getAtomicAlignment() const { return AtomicAlign; }
71 CharUnits getValueAlignment() const { return ValueAlign; }
72 uint64_t getAtomicSizeInBits() const { return AtomicSizeInBits; }
73 uint64_t getValueSizeInBits() const { return AtomicSizeInBits; }
74 TypeEvaluationKind getEvaluationKind() const { return EvaluationKind; }
75 bool shouldUseLibcall() const { return UseLibcall; }
76
77 /// Is the atomic size larger than the underlying value type?
78 ///
79 /// Note that the absence of padding does not mean that atomic
80 /// objects are completely interchangeable with non-atomic
81 /// objects: we might have promoted the alignment of a type
82 /// without making it bigger.
83 bool hasPadding() const {
84 return (ValueSizeInBits != AtomicSizeInBits);
85 }
86
Eli Friedmanbe4504d2013-07-11 01:32:21 +000087 bool emitMemSetZeroIfNecessary(LValue dest) const;
John McCalla8ec7eb2013-03-07 21:37:17 +000088
89 llvm::Value *getAtomicSizeValue() const {
90 CharUnits size = CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits);
91 return CGF.CGM.getSize(size);
92 }
93
94 /// Cast the given pointer to an integer pointer suitable for
95 /// atomic operations.
96 llvm::Value *emitCastToAtomicIntPointer(llvm::Value *addr) const;
97
98 /// Turn an atomic-layout object into an r-value.
99 RValue convertTempToRValue(llvm::Value *addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000100 AggValueSlot resultSlot,
101 SourceLocation loc) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000102
103 /// Copy an atomic r-value into atomic-layout memory.
104 void emitCopyIntoMemory(RValue rvalue, LValue lvalue) const;
105
106 /// Project an l-value down to the value field.
107 LValue projectValue(LValue lvalue) const {
108 llvm::Value *addr = lvalue.getAddress();
109 if (hasPadding())
110 addr = CGF.Builder.CreateStructGEP(addr, 0);
111
112 return LValue::MakeAddr(addr, getValueType(), lvalue.getAlignment(),
113 CGF.getContext(), lvalue.getTBAAInfo());
114 }
115
116 /// Materialize an atomic r-value in atomic-layout memory.
117 llvm::Value *materializeRValue(RValue rvalue) const;
118
119 private:
120 bool requiresMemSetZero(llvm::Type *type) const;
121 };
122}
123
124static RValue emitAtomicLibcall(CodeGenFunction &CGF,
125 StringRef fnName,
126 QualType resultType,
127 CallArgList &args) {
128 const CGFunctionInfo &fnInfo =
129 CGF.CGM.getTypes().arrangeFreeFunctionCall(resultType, args,
130 FunctionType::ExtInfo(), RequiredArgs::All);
131 llvm::FunctionType *fnTy = CGF.CGM.getTypes().GetFunctionType(fnInfo);
132 llvm::Constant *fn = CGF.CGM.CreateRuntimeFunction(fnTy, fnName);
133 return CGF.EmitCall(fnInfo, fn, ReturnValueSlot(), args);
134}
135
136/// Does a store of the given IR type modify the full expected width?
137static bool isFullSizeType(CodeGenModule &CGM, llvm::Type *type,
138 uint64_t expectedSize) {
139 return (CGM.getDataLayout().getTypeStoreSize(type) * 8 == expectedSize);
140}
141
142/// Does the atomic type require memsetting to zero before initialization?
143///
144/// The IR type is provided as a way of making certain queries faster.
145bool AtomicInfo::requiresMemSetZero(llvm::Type *type) const {
146 // If the atomic type has size padding, we definitely need a memset.
147 if (hasPadding()) return true;
148
149 // Otherwise, do some simple heuristics to try to avoid it:
150 switch (getEvaluationKind()) {
151 // For scalars and complexes, check whether the store size of the
152 // type uses the full size.
153 case TEK_Scalar:
154 return !isFullSizeType(CGF.CGM, type, AtomicSizeInBits);
155 case TEK_Complex:
156 return !isFullSizeType(CGF.CGM, type->getStructElementType(0),
157 AtomicSizeInBits / 2);
158
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000159 // Padding in structs has an undefined bit pattern. User beware.
John McCalla8ec7eb2013-03-07 21:37:17 +0000160 case TEK_Aggregate:
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000161 return false;
John McCalla8ec7eb2013-03-07 21:37:17 +0000162 }
163 llvm_unreachable("bad evaluation kind");
164}
165
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000166bool AtomicInfo::emitMemSetZeroIfNecessary(LValue dest) const {
John McCalla8ec7eb2013-03-07 21:37:17 +0000167 llvm::Value *addr = dest.getAddress();
168 if (!requiresMemSetZero(addr->getType()->getPointerElementType()))
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000169 return false;
John McCalla8ec7eb2013-03-07 21:37:17 +0000170
171 CGF.Builder.CreateMemSet(addr, llvm::ConstantInt::get(CGF.Int8Ty, 0),
172 AtomicSizeInBits / 8,
173 dest.getAlignment().getQuantity());
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000174 return true;
John McCalla8ec7eb2013-03-07 21:37:17 +0000175}
176
Tim Northover9c177222014-03-13 19:25:48 +0000177static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E,
178 llvm::Value *Dest, llvm::Value *Ptr,
179 llvm::Value *Val1, llvm::Value *Val2,
180 uint64_t Size, unsigned Align,
181 llvm::AtomicOrdering SuccessOrder,
182 llvm::AtomicOrdering FailureOrder) {
183 // Note that cmpxchg doesn't support weak cmpxchg, at least at the moment.
184 llvm::LoadInst *Expected = CGF.Builder.CreateLoad(Val1);
185 Expected->setAlignment(Align);
186 llvm::LoadInst *Desired = CGF.Builder.CreateLoad(Val2);
187 Desired->setAlignment(Align);
188
189 llvm::AtomicCmpXchgInst *Old = CGF.Builder.CreateAtomicCmpXchg(
190 Ptr, Expected, Desired, SuccessOrder, FailureOrder);
191 Old->setVolatile(E->isVolatile());
192
193 // Cmp holds the result of the compare-exchange operation: true on success,
194 // false on failure.
195 llvm::Value *Cmp = CGF.Builder.CreateICmpEQ(Old, Expected);
196
197 // This basic block is used to hold the store instruction if the operation
198 // failed.
199 llvm::BasicBlock *StoreExpectedBB =
200 CGF.createBasicBlock("cmpxchg.store_expected", CGF.CurFn);
201
202 // This basic block is the exit point of the operation, we should end up
203 // here regardless of whether or not the operation succeeded.
204 llvm::BasicBlock *ContinueBB =
205 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
206
207 // Update Expected if Expected isn't equal to Old, otherwise branch to the
208 // exit point.
209 CGF.Builder.CreateCondBr(Cmp, ContinueBB, StoreExpectedBB);
210
211 CGF.Builder.SetInsertPoint(StoreExpectedBB);
212 // Update the memory at Expected with Old's value.
213 llvm::StoreInst *StoreExpected = CGF.Builder.CreateStore(Old, Val1);
214 StoreExpected->setAlignment(Align);
215 // Finally, branch to the exit point.
216 CGF.Builder.CreateBr(ContinueBB);
217
218 CGF.Builder.SetInsertPoint(ContinueBB);
219 // Update the memory at Dest with Cmp's value.
220 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
221 return;
222}
223
224/// Given an ordering required on success, emit all possible cmpxchg
225/// instructions to cope with the provided (but possibly only dynamically known)
226/// FailureOrder.
227static void emitAtomicCmpXchgFailureSet(CodeGenFunction &CGF, AtomicExpr *E,
228 llvm::Value *Dest, llvm::Value *Ptr,
229 llvm::Value *Val1, llvm::Value *Val2,
230 llvm::Value *FailureOrderVal,
231 uint64_t Size, unsigned Align,
232 llvm::AtomicOrdering SuccessOrder) {
233 llvm::AtomicOrdering FailureOrder;
234 if (llvm::ConstantInt *FO = dyn_cast<llvm::ConstantInt>(FailureOrderVal)) {
235 switch (FO->getSExtValue()) {
236 default:
237 FailureOrder = llvm::Monotonic;
238 break;
239 case AtomicExpr::AO_ABI_memory_order_consume:
240 case AtomicExpr::AO_ABI_memory_order_acquire:
241 FailureOrder = llvm::Acquire;
242 break;
243 case AtomicExpr::AO_ABI_memory_order_seq_cst:
244 FailureOrder = llvm::SequentiallyConsistent;
245 break;
246 }
247 if (FailureOrder >= SuccessOrder) {
248 // Don't assert on undefined behaviour.
249 FailureOrder =
250 llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrder);
251 }
252 emitAtomicCmpXchg(CGF, E, Dest, Ptr, Val1, Val2, Size, Align, SuccessOrder,
253 FailureOrder);
254 return;
255 }
256
257 // Create all the relevant BB's
258 llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *SeqCstBB = 0;
259 MonotonicBB = CGF.createBasicBlock("monotonic_fail", CGF.CurFn);
260 if (SuccessOrder != llvm::Monotonic && SuccessOrder != llvm::Release)
261 AcquireBB = CGF.createBasicBlock("acquire_fail", CGF.CurFn);
262 if (SuccessOrder == llvm::SequentiallyConsistent)
263 SeqCstBB = CGF.createBasicBlock("seqcst_fail", CGF.CurFn);
264
265 llvm::BasicBlock *ContBB = CGF.createBasicBlock("atomic.continue", CGF.CurFn);
266
267 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(FailureOrderVal, MonotonicBB);
268
269 // Emit all the different atomics
270
271 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
272 // doesn't matter unless someone is crazy enough to use something that
273 // doesn't fold to a constant for the ordering.
274 CGF.Builder.SetInsertPoint(MonotonicBB);
275 emitAtomicCmpXchg(CGF, E, Dest, Ptr, Val1, Val2,
276 Size, Align, SuccessOrder, llvm::Monotonic);
277 CGF.Builder.CreateBr(ContBB);
278
279 if (AcquireBB) {
280 CGF.Builder.SetInsertPoint(AcquireBB);
281 emitAtomicCmpXchg(CGF, E, Dest, Ptr, Val1, Val2,
282 Size, Align, SuccessOrder, llvm::Acquire);
283 CGF.Builder.CreateBr(ContBB);
284 SI->addCase(CGF.Builder.getInt32(AtomicExpr::AO_ABI_memory_order_consume),
285 AcquireBB);
286 SI->addCase(CGF.Builder.getInt32(AtomicExpr::AO_ABI_memory_order_acquire),
287 AcquireBB);
288 }
289 if (SeqCstBB) {
290 CGF.Builder.SetInsertPoint(SeqCstBB);
291 emitAtomicCmpXchg(CGF, E, Dest, Ptr, Val1, Val2,
292 Size, Align, SuccessOrder, llvm::SequentiallyConsistent);
293 CGF.Builder.CreateBr(ContBB);
294 SI->addCase(CGF.Builder.getInt32(AtomicExpr::AO_ABI_memory_order_seq_cst),
295 SeqCstBB);
296 }
297
298 CGF.Builder.SetInsertPoint(ContBB);
299}
300
301static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest,
302 llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2,
303 llvm::Value *FailureOrder, uint64_t Size,
304 unsigned Align, llvm::AtomicOrdering Order) {
John McCallfc207f22013-03-07 21:37:12 +0000305 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
306 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
307
308 switch (E->getOp()) {
309 case AtomicExpr::AO__c11_atomic_init:
310 llvm_unreachable("Already handled!");
311
312 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
313 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
314 case AtomicExpr::AO__atomic_compare_exchange:
Tim Northover9c177222014-03-13 19:25:48 +0000315 case AtomicExpr::AO__atomic_compare_exchange_n:
316 emitAtomicCmpXchgFailureSet(CGF, E, Dest, Ptr, Val1, Val2, FailureOrder,
317 Size, Align, Order);
John McCallfc207f22013-03-07 21:37:12 +0000318 return;
John McCallfc207f22013-03-07 21:37:12 +0000319 case AtomicExpr::AO__c11_atomic_load:
320 case AtomicExpr::AO__atomic_load_n:
321 case AtomicExpr::AO__atomic_load: {
322 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
323 Load->setAtomic(Order);
324 Load->setAlignment(Size);
325 Load->setVolatile(E->isVolatile());
326 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Load, Dest);
327 StoreDest->setAlignment(Align);
328 return;
329 }
330
331 case AtomicExpr::AO__c11_atomic_store:
332 case AtomicExpr::AO__atomic_store:
333 case AtomicExpr::AO__atomic_store_n: {
334 assert(!Dest && "Store does not return a value");
335 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
336 LoadVal1->setAlignment(Align);
337 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
338 Store->setAtomic(Order);
339 Store->setAlignment(Size);
340 Store->setVolatile(E->isVolatile());
341 return;
342 }
343
344 case AtomicExpr::AO__c11_atomic_exchange:
345 case AtomicExpr::AO__atomic_exchange_n:
346 case AtomicExpr::AO__atomic_exchange:
347 Op = llvm::AtomicRMWInst::Xchg;
348 break;
349
350 case AtomicExpr::AO__atomic_add_fetch:
351 PostOp = llvm::Instruction::Add;
352 // Fall through.
353 case AtomicExpr::AO__c11_atomic_fetch_add:
354 case AtomicExpr::AO__atomic_fetch_add:
355 Op = llvm::AtomicRMWInst::Add;
356 break;
357
358 case AtomicExpr::AO__atomic_sub_fetch:
359 PostOp = llvm::Instruction::Sub;
360 // Fall through.
361 case AtomicExpr::AO__c11_atomic_fetch_sub:
362 case AtomicExpr::AO__atomic_fetch_sub:
363 Op = llvm::AtomicRMWInst::Sub;
364 break;
365
366 case AtomicExpr::AO__atomic_and_fetch:
367 PostOp = llvm::Instruction::And;
368 // Fall through.
369 case AtomicExpr::AO__c11_atomic_fetch_and:
370 case AtomicExpr::AO__atomic_fetch_and:
371 Op = llvm::AtomicRMWInst::And;
372 break;
373
374 case AtomicExpr::AO__atomic_or_fetch:
375 PostOp = llvm::Instruction::Or;
376 // Fall through.
377 case AtomicExpr::AO__c11_atomic_fetch_or:
378 case AtomicExpr::AO__atomic_fetch_or:
379 Op = llvm::AtomicRMWInst::Or;
380 break;
381
382 case AtomicExpr::AO__atomic_xor_fetch:
383 PostOp = llvm::Instruction::Xor;
384 // Fall through.
385 case AtomicExpr::AO__c11_atomic_fetch_xor:
386 case AtomicExpr::AO__atomic_fetch_xor:
387 Op = llvm::AtomicRMWInst::Xor;
388 break;
389
390 case AtomicExpr::AO__atomic_nand_fetch:
391 PostOp = llvm::Instruction::And;
392 // Fall through.
393 case AtomicExpr::AO__atomic_fetch_nand:
394 Op = llvm::AtomicRMWInst::Nand;
395 break;
396 }
397
398 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
399 LoadVal1->setAlignment(Align);
400 llvm::AtomicRMWInst *RMWI =
401 CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order);
402 RMWI->setVolatile(E->isVolatile());
403
404 // For __atomic_*_fetch operations, perform the operation again to
405 // determine the value which was written.
406 llvm::Value *Result = RMWI;
407 if (PostOp)
408 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
409 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
410 Result = CGF.Builder.CreateNot(Result);
411 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Result, Dest);
412 StoreDest->setAlignment(Align);
413}
414
415// This function emits any expression (scalar, complex, or aggregate)
416// into a temporary alloca.
417static llvm::Value *
418EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
419 llvm::Value *DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
420 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
421 /*Init*/ true);
422 return DeclPtr;
423}
424
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000425static void
426AddDirectArgument(CodeGenFunction &CGF, CallArgList &Args,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000427 bool UseOptimizedLibcall, llvm::Value *Val, QualType ValTy,
428 SourceLocation Loc) {
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000429 if (UseOptimizedLibcall) {
430 // Load value and pass it to the function directly.
431 unsigned Align = CGF.getContext().getTypeAlignInChars(ValTy).getQuantity();
Nick Lewycky2d84e842013-10-02 02:29:49 +0000432 Val = CGF.EmitLoadOfScalar(Val, false, Align, ValTy, Loc);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000433 Args.add(RValue::get(Val), ValTy);
434 } else {
435 // Non-optimized functions always take a reference.
436 Args.add(RValue::get(CGF.EmitCastToVoidPtr(Val)),
437 CGF.getContext().VoidPtrTy);
438 }
439}
440
John McCallfc207f22013-03-07 21:37:12 +0000441RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
442 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
443 QualType MemTy = AtomicTy;
444 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
445 MemTy = AT->getValueType();
446 CharUnits sizeChars = getContext().getTypeSizeInChars(AtomicTy);
447 uint64_t Size = sizeChars.getQuantity();
448 CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy);
449 unsigned Align = alignChars.getQuantity();
450 unsigned MaxInlineWidthInBits =
John McCallc8e01702013-04-16 22:48:15 +0000451 getTarget().getMaxAtomicInlineWidth();
John McCallfc207f22013-03-07 21:37:12 +0000452 bool UseLibcall = (Size != Align ||
453 getContext().toBits(sizeChars) > MaxInlineWidthInBits);
454
455 llvm::Value *Ptr, *Order, *OrderFail = 0, *Val1 = 0, *Val2 = 0;
456 Ptr = EmitScalarExpr(E->getPtr());
457
458 if (E->getOp() == AtomicExpr::AO__c11_atomic_init) {
459 assert(!Dest && "Init does not return a value");
John McCalla8ec7eb2013-03-07 21:37:17 +0000460 LValue lvalue = LValue::MakeAddr(Ptr, AtomicTy, alignChars, getContext());
461 EmitAtomicInit(E->getVal1(), lvalue);
462 return RValue::get(0);
John McCallfc207f22013-03-07 21:37:12 +0000463 }
464
465 Order = EmitScalarExpr(E->getOrder());
466
467 switch (E->getOp()) {
468 case AtomicExpr::AO__c11_atomic_init:
469 llvm_unreachable("Already handled!");
470
471 case AtomicExpr::AO__c11_atomic_load:
472 case AtomicExpr::AO__atomic_load_n:
473 break;
474
475 case AtomicExpr::AO__atomic_load:
476 Dest = EmitScalarExpr(E->getVal1());
477 break;
478
479 case AtomicExpr::AO__atomic_store:
480 Val1 = EmitScalarExpr(E->getVal1());
481 break;
482
483 case AtomicExpr::AO__atomic_exchange:
484 Val1 = EmitScalarExpr(E->getVal1());
485 Dest = EmitScalarExpr(E->getVal2());
486 break;
487
488 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
489 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
490 case AtomicExpr::AO__atomic_compare_exchange_n:
491 case AtomicExpr::AO__atomic_compare_exchange:
492 Val1 = EmitScalarExpr(E->getVal1());
493 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
494 Val2 = EmitScalarExpr(E->getVal2());
495 else
496 Val2 = EmitValToTemp(*this, E->getVal2());
497 OrderFail = EmitScalarExpr(E->getOrderFail());
498 // Evaluate and discard the 'weak' argument.
499 if (E->getNumSubExprs() == 6)
500 EmitScalarExpr(E->getWeak());
501 break;
502
503 case AtomicExpr::AO__c11_atomic_fetch_add:
504 case AtomicExpr::AO__c11_atomic_fetch_sub:
505 if (MemTy->isPointerType()) {
506 // For pointer arithmetic, we're required to do a bit of math:
507 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
508 // ... but only for the C11 builtins. The GNU builtins expect the
509 // user to multiply by sizeof(T).
510 QualType Val1Ty = E->getVal1()->getType();
511 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
512 CharUnits PointeeIncAmt =
513 getContext().getTypeSizeInChars(MemTy->getPointeeType());
514 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
515 Val1 = CreateMemTemp(Val1Ty, ".atomictmp");
516 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty));
517 break;
518 }
519 // Fall through.
520 case AtomicExpr::AO__atomic_fetch_add:
521 case AtomicExpr::AO__atomic_fetch_sub:
522 case AtomicExpr::AO__atomic_add_fetch:
523 case AtomicExpr::AO__atomic_sub_fetch:
524 case AtomicExpr::AO__c11_atomic_store:
525 case AtomicExpr::AO__c11_atomic_exchange:
526 case AtomicExpr::AO__atomic_store_n:
527 case AtomicExpr::AO__atomic_exchange_n:
528 case AtomicExpr::AO__c11_atomic_fetch_and:
529 case AtomicExpr::AO__c11_atomic_fetch_or:
530 case AtomicExpr::AO__c11_atomic_fetch_xor:
531 case AtomicExpr::AO__atomic_fetch_and:
532 case AtomicExpr::AO__atomic_fetch_or:
533 case AtomicExpr::AO__atomic_fetch_xor:
534 case AtomicExpr::AO__atomic_fetch_nand:
535 case AtomicExpr::AO__atomic_and_fetch:
536 case AtomicExpr::AO__atomic_or_fetch:
537 case AtomicExpr::AO__atomic_xor_fetch:
538 case AtomicExpr::AO__atomic_nand_fetch:
539 Val1 = EmitValToTemp(*this, E->getVal1());
540 break;
541 }
542
543 if (!E->getType()->isVoidType() && !Dest)
544 Dest = CreateMemTemp(E->getType(), ".atomicdst");
545
546 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
547 if (UseLibcall) {
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000548 bool UseOptimizedLibcall = false;
549 switch (E->getOp()) {
550 case AtomicExpr::AO__c11_atomic_fetch_add:
551 case AtomicExpr::AO__atomic_fetch_add:
552 case AtomicExpr::AO__c11_atomic_fetch_and:
553 case AtomicExpr::AO__atomic_fetch_and:
554 case AtomicExpr::AO__c11_atomic_fetch_or:
555 case AtomicExpr::AO__atomic_fetch_or:
556 case AtomicExpr::AO__c11_atomic_fetch_sub:
557 case AtomicExpr::AO__atomic_fetch_sub:
558 case AtomicExpr::AO__c11_atomic_fetch_xor:
559 case AtomicExpr::AO__atomic_fetch_xor:
560 // For these, only library calls for certain sizes exist.
561 UseOptimizedLibcall = true;
562 break;
563 default:
564 // Only use optimized library calls for sizes for which they exist.
565 if (Size == 1 || Size == 2 || Size == 4 || Size == 8)
566 UseOptimizedLibcall = true;
567 break;
568 }
John McCallfc207f22013-03-07 21:37:12 +0000569
John McCallfc207f22013-03-07 21:37:12 +0000570 CallArgList Args;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000571 if (!UseOptimizedLibcall) {
572 // For non-optimized library calls, the size is the first parameter
573 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
574 getContext().getSizeType());
575 }
576 // Atomic address is the first or second parameter
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000577 Args.add(RValue::get(EmitCastToVoidPtr(Ptr)), getContext().VoidPtrTy);
John McCallfc207f22013-03-07 21:37:12 +0000578
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000579 std::string LibCallName;
580 QualType RetTy;
581 bool HaveRetTy = false;
John McCallfc207f22013-03-07 21:37:12 +0000582 switch (E->getOp()) {
583 // There is only one libcall for compare an exchange, because there is no
584 // optimisation benefit possible from a libcall version of a weak compare
585 // and exchange.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000586 // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
John McCallfc207f22013-03-07 21:37:12 +0000587 // void *desired, int success, int failure)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000588 // bool __atomic_compare_exchange_N(T *mem, T *expected, T desired,
589 // int success, int failure)
John McCallfc207f22013-03-07 21:37:12 +0000590 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
591 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
592 case AtomicExpr::AO__atomic_compare_exchange:
593 case AtomicExpr::AO__atomic_compare_exchange_n:
594 LibCallName = "__atomic_compare_exchange";
595 RetTy = getContext().BoolTy;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000596 HaveRetTy = true;
Nick Lewycky2d84e842013-10-02 02:29:49 +0000597 Args.add(RValue::get(EmitCastToVoidPtr(Val1)), getContext().VoidPtrTy);
598 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val2, MemTy,
599 E->getExprLoc());
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000600 Args.add(RValue::get(Order), getContext().IntTy);
John McCallfc207f22013-03-07 21:37:12 +0000601 Order = OrderFail;
602 break;
603 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
604 // int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000605 // T __atomic_exchange_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +0000606 case AtomicExpr::AO__c11_atomic_exchange:
607 case AtomicExpr::AO__atomic_exchange_n:
608 case AtomicExpr::AO__atomic_exchange:
609 LibCallName = "__atomic_exchange";
Nick Lewycky2d84e842013-10-02 02:29:49 +0000610 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1, MemTy,
611 E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +0000612 break;
613 // void __atomic_store(size_t size, void *mem, void *val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000614 // void __atomic_store_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +0000615 case AtomicExpr::AO__c11_atomic_store:
616 case AtomicExpr::AO__atomic_store:
617 case AtomicExpr::AO__atomic_store_n:
618 LibCallName = "__atomic_store";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000619 RetTy = getContext().VoidTy;
620 HaveRetTy = true;
Nick Lewycky2d84e842013-10-02 02:29:49 +0000621 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1, MemTy,
622 E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +0000623 break;
624 // void __atomic_load(size_t size, void *mem, void *return, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000625 // T __atomic_load_N(T *mem, int order)
John McCallfc207f22013-03-07 21:37:12 +0000626 case AtomicExpr::AO__c11_atomic_load:
627 case AtomicExpr::AO__atomic_load:
628 case AtomicExpr::AO__atomic_load_n:
629 LibCallName = "__atomic_load";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000630 break;
631 // T __atomic_fetch_add_N(T *mem, T val, int order)
632 case AtomicExpr::AO__c11_atomic_fetch_add:
633 case AtomicExpr::AO__atomic_fetch_add:
634 LibCallName = "__atomic_fetch_add";
Nick Lewycky2d84e842013-10-02 02:29:49 +0000635 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1, MemTy,
636 E->getExprLoc());
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000637 break;
638 // T __atomic_fetch_and_N(T *mem, T val, int order)
639 case AtomicExpr::AO__c11_atomic_fetch_and:
640 case AtomicExpr::AO__atomic_fetch_and:
641 LibCallName = "__atomic_fetch_and";
Nick Lewycky2d84e842013-10-02 02:29:49 +0000642 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1, MemTy,
643 E->getExprLoc());
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000644 break;
645 // T __atomic_fetch_or_N(T *mem, T val, int order)
646 case AtomicExpr::AO__c11_atomic_fetch_or:
647 case AtomicExpr::AO__atomic_fetch_or:
648 LibCallName = "__atomic_fetch_or";
Nick Lewycky2d84e842013-10-02 02:29:49 +0000649 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1, MemTy,
650 E->getExprLoc());
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000651 break;
652 // T __atomic_fetch_sub_N(T *mem, T val, int order)
653 case AtomicExpr::AO__c11_atomic_fetch_sub:
654 case AtomicExpr::AO__atomic_fetch_sub:
655 LibCallName = "__atomic_fetch_sub";
Nick Lewycky2d84e842013-10-02 02:29:49 +0000656 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1, MemTy,
657 E->getExprLoc());
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000658 break;
659 // T __atomic_fetch_xor_N(T *mem, T val, int order)
660 case AtomicExpr::AO__c11_atomic_fetch_xor:
661 case AtomicExpr::AO__atomic_fetch_xor:
662 LibCallName = "__atomic_fetch_xor";
Nick Lewycky2d84e842013-10-02 02:29:49 +0000663 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1, MemTy,
664 E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +0000665 break;
John McCallfc207f22013-03-07 21:37:12 +0000666 default: return EmitUnsupportedRValue(E, "atomic library call");
667 }
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000668
669 // Optimized functions have the size in their name.
670 if (UseOptimizedLibcall)
671 LibCallName += "_" + llvm::utostr(Size);
672 // By default, assume we return a value of the atomic type.
673 if (!HaveRetTy) {
674 if (UseOptimizedLibcall) {
675 // Value is returned directly.
676 RetTy = MemTy;
677 } else {
678 // Value is returned through parameter before the order.
679 RetTy = getContext().VoidTy;
680 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
681 getContext().VoidPtrTy);
682 }
683 }
John McCallfc207f22013-03-07 21:37:12 +0000684 // order is always the last parameter
685 Args.add(RValue::get(Order),
686 getContext().IntTy);
687
688 const CGFunctionInfo &FuncInfo =
689 CGM.getTypes().arrangeFreeFunctionCall(RetTy, Args,
690 FunctionType::ExtInfo(), RequiredArgs::All);
691 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
692 llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
693 RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000694 if (!RetTy->isVoidType())
John McCallfc207f22013-03-07 21:37:12 +0000695 return Res;
696 if (E->getType()->isVoidType())
697 return RValue::get(0);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000698 return convertTempToRValue(Dest, E->getType(), E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +0000699 }
700
701 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
702 E->getOp() == AtomicExpr::AO__atomic_store ||
703 E->getOp() == AtomicExpr::AO__atomic_store_n;
704 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
705 E->getOp() == AtomicExpr::AO__atomic_load ||
706 E->getOp() == AtomicExpr::AO__atomic_load_n;
707
708 llvm::Type *IPtrTy =
709 llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo();
710 llvm::Value *OrigDest = Dest;
711 Ptr = Builder.CreateBitCast(Ptr, IPtrTy);
712 if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy);
713 if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy);
714 if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy);
715
716 if (isa<llvm::ConstantInt>(Order)) {
717 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
718 switch (ord) {
Tim Northovere94a34c2014-03-11 10:49:14 +0000719 case AtomicExpr::AO_ABI_memory_order_relaxed:
Tim Northover9c177222014-03-13 19:25:48 +0000720 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OrderFail,
721 Size, Align, llvm::Monotonic);
John McCallfc207f22013-03-07 21:37:12 +0000722 break;
Tim Northovere94a34c2014-03-11 10:49:14 +0000723 case AtomicExpr::AO_ABI_memory_order_consume:
724 case AtomicExpr::AO_ABI_memory_order_acquire:
John McCallfc207f22013-03-07 21:37:12 +0000725 if (IsStore)
726 break; // Avoid crashing on code with undefined behavior
Tim Northover9c177222014-03-13 19:25:48 +0000727 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OrderFail,
728 Size, Align, llvm::Acquire);
John McCallfc207f22013-03-07 21:37:12 +0000729 break;
Tim Northovere94a34c2014-03-11 10:49:14 +0000730 case AtomicExpr::AO_ABI_memory_order_release:
John McCallfc207f22013-03-07 21:37:12 +0000731 if (IsLoad)
732 break; // Avoid crashing on code with undefined behavior
Tim Northover9c177222014-03-13 19:25:48 +0000733 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OrderFail,
734 Size, Align, llvm::Release);
John McCallfc207f22013-03-07 21:37:12 +0000735 break;
Tim Northovere94a34c2014-03-11 10:49:14 +0000736 case AtomicExpr::AO_ABI_memory_order_acq_rel:
John McCallfc207f22013-03-07 21:37:12 +0000737 if (IsLoad || IsStore)
738 break; // Avoid crashing on code with undefined behavior
Tim Northover9c177222014-03-13 19:25:48 +0000739 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OrderFail,
740 Size, Align, llvm::AcquireRelease);
John McCallfc207f22013-03-07 21:37:12 +0000741 break;
Tim Northovere94a34c2014-03-11 10:49:14 +0000742 case AtomicExpr::AO_ABI_memory_order_seq_cst:
Tim Northover9c177222014-03-13 19:25:48 +0000743 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OrderFail,
744 Size, Align, llvm::SequentiallyConsistent);
John McCallfc207f22013-03-07 21:37:12 +0000745 break;
746 default: // invalid order
747 // We should not ever get here normally, but it's hard to
748 // enforce that in general.
749 break;
750 }
751 if (E->getType()->isVoidType())
752 return RValue::get(0);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000753 return convertTempToRValue(OrigDest, E->getType(), E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +0000754 }
755
756 // Long case, when Order isn't obviously constant.
757
758 // Create all the relevant BB's
759 llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *ReleaseBB = 0,
760 *AcqRelBB = 0, *SeqCstBB = 0;
761 MonotonicBB = createBasicBlock("monotonic", CurFn);
762 if (!IsStore)
763 AcquireBB = createBasicBlock("acquire", CurFn);
764 if (!IsLoad)
765 ReleaseBB = createBasicBlock("release", CurFn);
766 if (!IsLoad && !IsStore)
767 AcqRelBB = createBasicBlock("acqrel", CurFn);
768 SeqCstBB = createBasicBlock("seqcst", CurFn);
769 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
770
771 // Create the switch for the split
772 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
773 // doesn't matter unless someone is crazy enough to use something that
774 // doesn't fold to a constant for the ordering.
775 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
776 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
777
778 // Emit all the different atomics
779 Builder.SetInsertPoint(MonotonicBB);
Tim Northover9c177222014-03-13 19:25:48 +0000780 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OrderFail,
781 Size, Align, llvm::Monotonic);
John McCallfc207f22013-03-07 21:37:12 +0000782 Builder.CreateBr(ContBB);
783 if (!IsStore) {
784 Builder.SetInsertPoint(AcquireBB);
Tim Northover9c177222014-03-13 19:25:48 +0000785 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OrderFail,
786 Size, Align, llvm::Acquire);
John McCallfc207f22013-03-07 21:37:12 +0000787 Builder.CreateBr(ContBB);
788 SI->addCase(Builder.getInt32(1), AcquireBB);
789 SI->addCase(Builder.getInt32(2), AcquireBB);
790 }
791 if (!IsLoad) {
792 Builder.SetInsertPoint(ReleaseBB);
Tim Northover9c177222014-03-13 19:25:48 +0000793 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OrderFail,
794 Size, Align, llvm::Release);
John McCallfc207f22013-03-07 21:37:12 +0000795 Builder.CreateBr(ContBB);
796 SI->addCase(Builder.getInt32(3), ReleaseBB);
797 }
798 if (!IsLoad && !IsStore) {
799 Builder.SetInsertPoint(AcqRelBB);
Tim Northover9c177222014-03-13 19:25:48 +0000800 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OrderFail,
801 Size, Align, llvm::AcquireRelease);
John McCallfc207f22013-03-07 21:37:12 +0000802 Builder.CreateBr(ContBB);
803 SI->addCase(Builder.getInt32(4), AcqRelBB);
804 }
805 Builder.SetInsertPoint(SeqCstBB);
Tim Northover9c177222014-03-13 19:25:48 +0000806 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OrderFail,
807 Size, Align, llvm::SequentiallyConsistent);
John McCallfc207f22013-03-07 21:37:12 +0000808 Builder.CreateBr(ContBB);
809 SI->addCase(Builder.getInt32(5), SeqCstBB);
810
811 // Cleanup and return
812 Builder.SetInsertPoint(ContBB);
813 if (E->getType()->isVoidType())
814 return RValue::get(0);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000815 return convertTempToRValue(OrigDest, E->getType(), E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +0000816}
John McCalla8ec7eb2013-03-07 21:37:17 +0000817
818llvm::Value *AtomicInfo::emitCastToAtomicIntPointer(llvm::Value *addr) const {
819 unsigned addrspace =
820 cast<llvm::PointerType>(addr->getType())->getAddressSpace();
821 llvm::IntegerType *ty =
822 llvm::IntegerType::get(CGF.getLLVMContext(), AtomicSizeInBits);
823 return CGF.Builder.CreateBitCast(addr, ty->getPointerTo(addrspace));
824}
825
826RValue AtomicInfo::convertTempToRValue(llvm::Value *addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000827 AggValueSlot resultSlot,
828 SourceLocation loc) const {
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000829 if (EvaluationKind == TEK_Aggregate)
830 return resultSlot.asRValue();
John McCalla8ec7eb2013-03-07 21:37:17 +0000831
832 // Drill into the padding structure if we have one.
833 if (hasPadding())
834 addr = CGF.Builder.CreateStructGEP(addr, 0);
835
John McCalla8ec7eb2013-03-07 21:37:17 +0000836 // Otherwise, just convert the temporary to an r-value using the
837 // normal conversion routine.
Nick Lewycky2d84e842013-10-02 02:29:49 +0000838 return CGF.convertTempToRValue(addr, getValueType(), loc);
John McCalla8ec7eb2013-03-07 21:37:17 +0000839}
840
841/// Emit a load from an l-value of atomic type. Note that the r-value
842/// we produce is an r-value of the atomic *value* type.
Nick Lewycky2d84e842013-10-02 02:29:49 +0000843RValue CodeGenFunction::EmitAtomicLoad(LValue src, SourceLocation loc,
844 AggValueSlot resultSlot) {
John McCalla8ec7eb2013-03-07 21:37:17 +0000845 AtomicInfo atomics(*this, src);
846
847 // Check whether we should use a library call.
848 if (atomics.shouldUseLibcall()) {
849 llvm::Value *tempAddr;
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000850 if (!resultSlot.isIgnored()) {
John McCalla8ec7eb2013-03-07 21:37:17 +0000851 assert(atomics.getEvaluationKind() == TEK_Aggregate);
852 tempAddr = resultSlot.getAddr();
853 } else {
854 tempAddr = CreateMemTemp(atomics.getAtomicType(), "atomic-load-temp");
855 }
856
857 // void __atomic_load(size_t size, void *mem, void *return, int order);
858 CallArgList args;
859 args.add(RValue::get(atomics.getAtomicSizeValue()),
860 getContext().getSizeType());
861 args.add(RValue::get(EmitCastToVoidPtr(src.getAddress())),
862 getContext().VoidPtrTy);
863 args.add(RValue::get(EmitCastToVoidPtr(tempAddr)),
864 getContext().VoidPtrTy);
Tim Northovere94a34c2014-03-11 10:49:14 +0000865 args.add(RValue::get(llvm::ConstantInt::get(
866 IntTy, AtomicExpr::AO_ABI_memory_order_seq_cst)),
John McCalla8ec7eb2013-03-07 21:37:17 +0000867 getContext().IntTy);
868 emitAtomicLibcall(*this, "__atomic_load", getContext().VoidTy, args);
869
870 // Produce the r-value.
Nick Lewycky2d84e842013-10-02 02:29:49 +0000871 return atomics.convertTempToRValue(tempAddr, resultSlot, loc);
John McCalla8ec7eb2013-03-07 21:37:17 +0000872 }
873
874 // Okay, we're doing this natively.
875 llvm::Value *addr = atomics.emitCastToAtomicIntPointer(src.getAddress());
876 llvm::LoadInst *load = Builder.CreateLoad(addr, "atomic-load");
877 load->setAtomic(llvm::SequentiallyConsistent);
878
879 // Other decoration.
880 load->setAlignment(src.getAlignment().getQuantity());
881 if (src.isVolatileQualified())
882 load->setVolatile(true);
883 if (src.getTBAAInfo())
884 CGM.DecorateInstruction(load, src.getTBAAInfo());
885
886 // Okay, turn that back into the original value type.
887 QualType valueType = atomics.getValueType();
888 llvm::Value *result = load;
889
890 // If we're ignoring an aggregate return, don't do anything.
891 if (atomics.getEvaluationKind() == TEK_Aggregate && resultSlot.isIgnored())
892 return RValue::getAggregate(0, false);
893
894 // The easiest way to do this this is to go through memory, but we
895 // try not to in some easy cases.
896 if (atomics.getEvaluationKind() == TEK_Scalar && !atomics.hasPadding()) {
897 llvm::Type *resultTy = CGM.getTypes().ConvertTypeForMem(valueType);
898 if (isa<llvm::IntegerType>(resultTy)) {
899 assert(result->getType() == resultTy);
900 result = EmitFromMemory(result, valueType);
901 } else if (isa<llvm::PointerType>(resultTy)) {
902 result = Builder.CreateIntToPtr(result, resultTy);
903 } else {
904 result = Builder.CreateBitCast(result, resultTy);
905 }
906 return RValue::get(result);
907 }
908
909 // Create a temporary. This needs to be big enough to hold the
910 // atomic integer.
911 llvm::Value *temp;
912 bool tempIsVolatile = false;
913 CharUnits tempAlignment;
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000914 if (atomics.getEvaluationKind() == TEK_Aggregate) {
John McCalla8ec7eb2013-03-07 21:37:17 +0000915 assert(!resultSlot.isIgnored());
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000916 temp = resultSlot.getAddr();
917 tempAlignment = atomics.getValueAlignment();
John McCalla8ec7eb2013-03-07 21:37:17 +0000918 tempIsVolatile = resultSlot.isVolatile();
919 } else {
920 temp = CreateMemTemp(atomics.getAtomicType(), "atomic-load-temp");
921 tempAlignment = atomics.getAtomicAlignment();
922 }
923
924 // Slam the integer into the temporary.
925 llvm::Value *castTemp = atomics.emitCastToAtomicIntPointer(temp);
926 Builder.CreateAlignedStore(result, castTemp, tempAlignment.getQuantity())
927 ->setVolatile(tempIsVolatile);
928
Nick Lewycky2d84e842013-10-02 02:29:49 +0000929 return atomics.convertTempToRValue(temp, resultSlot, loc);
John McCalla8ec7eb2013-03-07 21:37:17 +0000930}
931
932
933
934/// Copy an r-value into memory as part of storing to an atomic type.
935/// This needs to create a bit-pattern suitable for atomic operations.
936void AtomicInfo::emitCopyIntoMemory(RValue rvalue, LValue dest) const {
937 // If we have an r-value, the rvalue should be of the atomic type,
938 // which means that the caller is responsible for having zeroed
939 // any padding. Just do an aggregate copy of that type.
940 if (rvalue.isAggregate()) {
941 CGF.EmitAggregateCopy(dest.getAddress(),
942 rvalue.getAggregateAddr(),
943 getAtomicType(),
944 (rvalue.isVolatileQualified()
945 || dest.isVolatileQualified()),
946 dest.getAlignment());
947 return;
948 }
949
950 // Okay, otherwise we're copying stuff.
951
952 // Zero out the buffer if necessary.
953 emitMemSetZeroIfNecessary(dest);
954
955 // Drill past the padding if present.
956 dest = projectValue(dest);
957
958 // Okay, store the rvalue in.
959 if (rvalue.isScalar()) {
960 CGF.EmitStoreOfScalar(rvalue.getScalarVal(), dest, /*init*/ true);
961 } else {
962 CGF.EmitStoreOfComplex(rvalue.getComplexVal(), dest, /*init*/ true);
963 }
964}
965
966
967/// Materialize an r-value into memory for the purposes of storing it
968/// to an atomic type.
969llvm::Value *AtomicInfo::materializeRValue(RValue rvalue) const {
970 // Aggregate r-values are already in memory, and EmitAtomicStore
971 // requires them to be values of the atomic type.
972 if (rvalue.isAggregate())
973 return rvalue.getAggregateAddr();
974
975 // Otherwise, make a temporary and materialize into it.
976 llvm::Value *temp = CGF.CreateMemTemp(getAtomicType(), "atomic-store-temp");
977 LValue tempLV = CGF.MakeAddrLValue(temp, getAtomicType(), getAtomicAlignment());
978 emitCopyIntoMemory(rvalue, tempLV);
979 return temp;
980}
981
982/// Emit a store to an l-value of atomic type.
983///
984/// Note that the r-value is expected to be an r-value *of the atomic
985/// type*; this means that for aggregate r-values, it should include
986/// storage for any padding that was necessary.
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000987void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue dest, bool isInit) {
John McCalla8ec7eb2013-03-07 21:37:17 +0000988 // If this is an aggregate r-value, it should agree in type except
989 // maybe for address-space qualification.
990 assert(!rvalue.isAggregate() ||
991 rvalue.getAggregateAddr()->getType()->getPointerElementType()
992 == dest.getAddress()->getType()->getPointerElementType());
993
994 AtomicInfo atomics(*this, dest);
995
996 // If this is an initialization, just put the value there normally.
997 if (isInit) {
998 atomics.emitCopyIntoMemory(rvalue, dest);
999 return;
1000 }
1001
1002 // Check whether we should use a library call.
1003 if (atomics.shouldUseLibcall()) {
1004 // Produce a source address.
1005 llvm::Value *srcAddr = atomics.materializeRValue(rvalue);
1006
1007 // void __atomic_store(size_t size, void *mem, void *val, int order)
1008 CallArgList args;
1009 args.add(RValue::get(atomics.getAtomicSizeValue()),
1010 getContext().getSizeType());
1011 args.add(RValue::get(EmitCastToVoidPtr(dest.getAddress())),
1012 getContext().VoidPtrTy);
1013 args.add(RValue::get(EmitCastToVoidPtr(srcAddr)),
1014 getContext().VoidPtrTy);
Tim Northovere94a34c2014-03-11 10:49:14 +00001015 args.add(RValue::get(llvm::ConstantInt::get(
1016 IntTy, AtomicExpr::AO_ABI_memory_order_seq_cst)),
John McCalla8ec7eb2013-03-07 21:37:17 +00001017 getContext().IntTy);
1018 emitAtomicLibcall(*this, "__atomic_store", getContext().VoidTy, args);
1019 return;
1020 }
1021
1022 // Okay, we're doing this natively.
1023 llvm::Value *intValue;
1024
1025 // If we've got a scalar value of the right size, try to avoid going
1026 // through memory.
1027 if (rvalue.isScalar() && !atomics.hasPadding()) {
1028 llvm::Value *value = rvalue.getScalarVal();
1029 if (isa<llvm::IntegerType>(value->getType())) {
1030 intValue = value;
1031 } else {
1032 llvm::IntegerType *inputIntTy =
1033 llvm::IntegerType::get(getLLVMContext(), atomics.getValueSizeInBits());
1034 if (isa<llvm::PointerType>(value->getType())) {
1035 intValue = Builder.CreatePtrToInt(value, inputIntTy);
1036 } else {
1037 intValue = Builder.CreateBitCast(value, inputIntTy);
1038 }
1039 }
1040
1041 // Otherwise, we need to go through memory.
1042 } else {
1043 // Put the r-value in memory.
1044 llvm::Value *addr = atomics.materializeRValue(rvalue);
1045
1046 // Cast the temporary to the atomic int type and pull a value out.
1047 addr = atomics.emitCastToAtomicIntPointer(addr);
1048 intValue = Builder.CreateAlignedLoad(addr,
1049 atomics.getAtomicAlignment().getQuantity());
1050 }
1051
1052 // Do the atomic store.
1053 llvm::Value *addr = atomics.emitCastToAtomicIntPointer(dest.getAddress());
1054 llvm::StoreInst *store = Builder.CreateStore(intValue, addr);
1055
1056 // Initializations don't need to be atomic.
1057 if (!isInit) store->setAtomic(llvm::SequentiallyConsistent);
1058
1059 // Other decoration.
1060 store->setAlignment(dest.getAlignment().getQuantity());
1061 if (dest.isVolatileQualified())
1062 store->setVolatile(true);
1063 if (dest.getTBAAInfo())
1064 CGM.DecorateInstruction(store, dest.getTBAAInfo());
1065}
1066
1067void CodeGenFunction::EmitAtomicInit(Expr *init, LValue dest) {
1068 AtomicInfo atomics(*this, dest);
1069
1070 switch (atomics.getEvaluationKind()) {
1071 case TEK_Scalar: {
1072 llvm::Value *value = EmitScalarExpr(init);
1073 atomics.emitCopyIntoMemory(RValue::get(value), dest);
1074 return;
1075 }
1076
1077 case TEK_Complex: {
1078 ComplexPairTy value = EmitComplexExpr(init);
1079 atomics.emitCopyIntoMemory(RValue::getComplex(value), dest);
1080 return;
1081 }
1082
1083 case TEK_Aggregate: {
Eli Friedmanbe4504d2013-07-11 01:32:21 +00001084 // Fix up the destination if the initializer isn't an expression
1085 // of atomic type.
1086 bool Zeroed = false;
John McCalla8ec7eb2013-03-07 21:37:17 +00001087 if (!init->getType()->isAtomicType()) {
Eli Friedmanbe4504d2013-07-11 01:32:21 +00001088 Zeroed = atomics.emitMemSetZeroIfNecessary(dest);
John McCalla8ec7eb2013-03-07 21:37:17 +00001089 dest = atomics.projectValue(dest);
1090 }
1091
1092 // Evaluate the expression directly into the destination.
1093 AggValueSlot slot = AggValueSlot::forLValue(dest,
1094 AggValueSlot::IsNotDestructed,
1095 AggValueSlot::DoesNotNeedGCBarriers,
Eli Friedmanbe4504d2013-07-11 01:32:21 +00001096 AggValueSlot::IsNotAliased,
1097 Zeroed ? AggValueSlot::IsZeroed :
1098 AggValueSlot::IsNotZeroed);
1099
John McCalla8ec7eb2013-03-07 21:37:17 +00001100 EmitAggExpr(init, slot);
1101 return;
1102 }
1103 }
1104 llvm_unreachable("bad evaluation kind");
1105}