clang 24.0.0git
CGAtomic.cpp
Go to the documentation of this file.
1//===--- CGAtomic.cpp - Emit LLVM IR for atomic operations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the code for emitting atomic operations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCall.h"
14#include "CGRecordLayout.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "TargetInfo.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Intrinsics.h"
24
25using namespace clang;
26using namespace CodeGen;
27
28namespace {
29 class AtomicInfo {
30 CodeGenFunction &CGF;
31 QualType AtomicTy;
32 QualType ValueTy;
33 uint64_t AtomicSizeInBits;
34 uint64_t ValueSizeInBits;
35 CharUnits AtomicAlign;
36 CharUnits ValueAlign;
38 bool UseLibcall;
39 LValue LVal;
40 CGBitFieldInfo BFI;
41 public:
42 AtomicInfo(CodeGenFunction &CGF, LValue &lvalue)
43 : CGF(CGF), AtomicSizeInBits(0), ValueSizeInBits(0),
44 EvaluationKind(TEK_Scalar), UseLibcall(true) {
45 assert(!lvalue.isGlobalReg());
46 ASTContext &C = CGF.getContext();
47 if (lvalue.isSimple()) {
48 AtomicTy = lvalue.getType();
49 if (auto *ATy = AtomicTy->getAs<AtomicType>())
50 ValueTy = ATy->getValueType();
51 else
52 ValueTy = AtomicTy;
53 EvaluationKind = CGF.getEvaluationKind(ValueTy);
54
55 uint64_t ValueAlignInBits;
56 uint64_t AtomicAlignInBits;
57 TypeInfo ValueTI = C.getTypeInfo(ValueTy);
58 ValueSizeInBits = ValueTI.Width;
59 ValueAlignInBits = ValueTI.Align;
60
61 TypeInfo AtomicTI = C.getTypeInfo(AtomicTy);
62 AtomicSizeInBits = AtomicTI.Width;
63 AtomicAlignInBits = AtomicTI.Align;
64
65 assert(ValueSizeInBits <= AtomicSizeInBits);
66 assert(ValueAlignInBits <= AtomicAlignInBits);
67
68 AtomicAlign = C.toCharUnitsFromBits(AtomicAlignInBits);
69 ValueAlign = C.toCharUnitsFromBits(ValueAlignInBits);
70 if (lvalue.getAlignment().isZero())
71 lvalue.setAlignment(AtomicAlign);
72
73 LVal = lvalue;
74 } else if (lvalue.isBitField()) {
75 ValueTy = lvalue.getType();
76 ValueSizeInBits = C.getTypeSize(ValueTy);
77 auto &OrigBFI = lvalue.getBitFieldInfo();
78 auto Offset = OrigBFI.Offset % C.toBits(lvalue.getAlignment());
79 AtomicSizeInBits = C.toBits(
80 C.toCharUnitsFromBits(Offset + OrigBFI.Size + C.getCharWidth() - 1)
81 .alignTo(lvalue.getAlignment()));
82 llvm::Value *BitFieldPtr = lvalue.getRawBitFieldPointer(CGF);
83 auto OffsetInChars =
84 (C.toCharUnitsFromBits(OrigBFI.Offset) / lvalue.getAlignment()) *
85 lvalue.getAlignment();
86 llvm::Value *StoragePtr = CGF.Builder.CreateConstGEP1_64(
87 CGF.Int8Ty, BitFieldPtr, OffsetInChars.getQuantity());
88 StoragePtr = CGF.Builder.CreateAddrSpaceCast(
89 StoragePtr, CGF.DefaultPtrTy, "atomic_bitfield_base");
90 BFI = OrigBFI;
91 BFI.Offset = Offset;
92 BFI.StorageSize = AtomicSizeInBits;
93 BFI.StorageOffset += OffsetInChars;
94 llvm::Type *StorageTy = CGF.Builder.getIntNTy(AtomicSizeInBits);
95 LVal = LValue::MakeBitfield(
96 Address(StoragePtr, StorageTy, lvalue.getAlignment()), BFI,
97 lvalue.getType(), lvalue.getBaseInfo(), lvalue.getTBAAInfo());
98 AtomicTy = C.getIntTypeForBitwidth(AtomicSizeInBits, OrigBFI.IsSigned);
99 if (AtomicTy.isNull()) {
100 llvm::APInt Size(
101 /*numBits=*/32,
102 C.toCharUnitsFromBits(AtomicSizeInBits).getQuantity());
103 AtomicTy = C.getConstantArrayType(C.CharTy, Size, nullptr,
104 ArraySizeModifier::Normal,
105 /*IndexTypeQuals=*/0);
106 }
107 AtomicAlign = ValueAlign = lvalue.getAlignment();
108 } else if (lvalue.isVectorElt()) {
109 ValueTy = lvalue.getType()->castAs<VectorType>()->getElementType();
110 ValueSizeInBits = C.getTypeSize(ValueTy);
111 AtomicTy = lvalue.getType();
112 AtomicSizeInBits = C.getTypeSize(AtomicTy);
113 AtomicAlign = ValueAlign = lvalue.getAlignment();
114 LVal = lvalue;
115 } else {
116 assert(lvalue.isExtVectorElt());
117 ValueTy = lvalue.getType();
118 ValueSizeInBits = C.getTypeSize(ValueTy);
119 AtomicTy = ValueTy = CGF.getContext().getExtVectorType(
120 lvalue.getType(), cast<llvm::FixedVectorType>(
121 lvalue.getExtVectorAddress().getElementType())
122 ->getNumElements());
123 AtomicSizeInBits = C.getTypeSize(AtomicTy);
124 AtomicAlign = ValueAlign = lvalue.getAlignment();
125 LVal = lvalue;
126 }
127 UseLibcall = !C.getTargetInfo().hasBuiltinAtomic(
128 AtomicSizeInBits, C.toBits(lvalue.getAlignment()));
129 }
130
131 QualType getAtomicType() const { return AtomicTy; }
132 QualType getValueType() const { return ValueTy; }
133 CharUnits getAtomicAlignment() const { return AtomicAlign; }
134 uint64_t getAtomicSizeInBits() const { return AtomicSizeInBits; }
135 uint64_t getValueSizeInBits() const { return ValueSizeInBits; }
136 TypeEvaluationKind getEvaluationKind() const { return EvaluationKind; }
137 bool shouldUseLibcall() const { return UseLibcall; }
138 const LValue &getAtomicLValue() const { return LVal; }
139 llvm::Value *getAtomicPointer() const {
140 if (LVal.isSimple())
141 return LVal.emitRawPointer(CGF);
142 else if (LVal.isBitField())
143 return LVal.getRawBitFieldPointer(CGF);
144 else if (LVal.isVectorElt())
145 return LVal.getRawVectorPointer(CGF);
146 assert(LVal.isExtVectorElt());
147 return LVal.getRawExtVectorPointer(CGF);
148 }
149 Address getAtomicAddress() const {
150 llvm::Type *ElTy;
151 if (LVal.isSimple())
152 ElTy = LVal.getAddress().getElementType();
153 else if (LVal.isBitField())
154 ElTy = LVal.getBitFieldAddress().getElementType();
155 else if (LVal.isVectorElt())
156 ElTy = LVal.getVectorAddress().getElementType();
157 else
158 ElTy = LVal.getExtVectorAddress().getElementType();
159 return Address(getAtomicPointer(), ElTy, getAtomicAlignment());
160 }
161
162 Address getAtomicAddressAsAtomicIntPointer() const {
163 return castToAtomicIntPointer(getAtomicAddress());
164 }
165
166 /// Is the atomic size larger than the underlying value type?
167 ///
168 /// Note that the absence of padding does not mean that atomic
169 /// objects are completely interchangeable with non-atomic
170 /// objects: we might have promoted the alignment of a type
171 /// without making it bigger.
172 bool hasPadding() const {
173 return (ValueSizeInBits != AtomicSizeInBits);
174 }
175
176 bool emitMemSetZeroIfNecessary() const;
177
178 llvm::Value *getAtomicSizeValue() const {
179 CharUnits size = CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits);
180 return CGF.CGM.getSize(size);
181 }
182
183 /// Cast the given pointer to an integer pointer suitable for atomic
184 /// operations if the source.
185 Address castToAtomicIntPointer(Address Addr) const;
186
187 /// If Addr is compatible with the iN that will be used for an atomic
188 /// operation, bitcast it. Otherwise, create a temporary that is suitable
189 /// and copy the value across.
190 Address convertToAtomicIntPointer(Address Addr) const;
191
192 /// Turn an atomic-layout object into an r-value.
193 RValue convertAtomicTempToRValue(Address addr, AggValueSlot resultSlot,
194 SourceLocation loc, bool AsValue) const;
195
196 llvm::Value *getScalarRValValueOrNull(RValue RVal) const;
197
198 /// Converts an rvalue to integer value if needed.
199 llvm::Value *convertRValueToInt(RValue RVal, bool CmpXchg = false) const;
200
201 RValue ConvertToValueOrAtomic(llvm::Value *IntVal, AggValueSlot ResultSlot,
202 SourceLocation Loc, bool AsValue,
203 bool CmpXchg = false) const;
204
205 /// Copy an atomic r-value into atomic-layout memory.
206 void emitCopyIntoMemory(RValue rvalue) const;
207
208 /// Project an l-value down to the value field.
209 LValue projectValue() const {
210 assert(LVal.isSimple());
211 Address addr = getAtomicAddress();
212 if (hasPadding())
213 addr = CGF.Builder.CreateStructGEP(addr, 0);
214
215 return LValue::MakeAddr(addr, getValueType(), CGF.getContext(),
216 LVal.getBaseInfo(), LVal.getTBAAInfo());
217 }
218
219 /// Emits atomic load.
220 /// \returns Loaded value.
221 RValue EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
222 bool AsValue, llvm::AtomicOrdering AO,
223 bool IsVolatile);
224
225 /// Emits atomic compare-and-exchange sequence.
226 /// \param Expected Expected value.
227 /// \param Desired Desired value.
228 /// \param Success Atomic ordering for success operation.
229 /// \param Failure Atomic ordering for failed operation.
230 /// \param IsWeak true if atomic operation is weak, false otherwise.
231 /// \returns Pair of values: previous value from storage (value type) and
232 /// boolean flag (i1 type) with true if success and false otherwise.
233 std::pair<RValue, llvm::Value *>
234 EmitAtomicCompareExchange(RValue Expected, RValue Desired,
235 llvm::AtomicOrdering Success =
236 llvm::AtomicOrdering::SequentiallyConsistent,
237 llvm::AtomicOrdering Failure =
238 llvm::AtomicOrdering::SequentiallyConsistent,
239 bool IsWeak = false);
240
241 /// Emits atomic update.
242 /// \param AO Atomic ordering.
243 /// \param UpdateOp Update operation for the current lvalue.
244 void EmitAtomicUpdate(llvm::AtomicOrdering AO,
245 const llvm::function_ref<RValue(RValue)> &UpdateOp,
246 bool IsVolatile);
247 /// Emits atomic update.
248 /// \param AO Atomic ordering.
249 void EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
250 bool IsVolatile);
251
252 /// Materialize an atomic r-value in atomic-layout memory.
253 Address materializeRValue(RValue rvalue) const;
254
255 /// Creates temp alloca for intermediate operations on atomic value.
256 Address CreateTempAlloca() const;
257 private:
258 bool requiresMemSetZero(llvm::Type *type) const;
259
260
261 /// Emits atomic load as a libcall.
262 void EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
263 llvm::AtomicOrdering AO, bool IsVolatile);
264 /// Emits atomic load as LLVM instruction.
265 llvm::Value *EmitAtomicLoadOp(llvm::AtomicOrdering AO, bool IsVolatile,
266 bool CmpXchg = false);
267 /// Emits atomic compare-and-exchange op as a libcall.
268 llvm::Value *EmitAtomicCompareExchangeLibcall(
269 llvm::Value *ExpectedAddr, llvm::Value *DesiredAddr,
270 llvm::AtomicOrdering Success =
271 llvm::AtomicOrdering::SequentiallyConsistent,
272 llvm::AtomicOrdering Failure =
273 llvm::AtomicOrdering::SequentiallyConsistent);
274 /// Emits atomic compare-and-exchange op as LLVM instruction.
275 std::pair<llvm::Value *, llvm::Value *> EmitAtomicCompareExchangeOp(
276 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
277 llvm::AtomicOrdering Success =
278 llvm::AtomicOrdering::SequentiallyConsistent,
279 llvm::AtomicOrdering Failure =
280 llvm::AtomicOrdering::SequentiallyConsistent,
281 bool IsWeak = false);
282 /// Emit atomic update as libcalls.
283 void
284 EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
285 const llvm::function_ref<RValue(RValue)> &UpdateOp,
286 bool IsVolatile);
287 /// Emit atomic update as LLVM instructions.
288 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO,
289 const llvm::function_ref<RValue(RValue)> &UpdateOp,
290 bool IsVolatile);
291 /// Emit atomic update as libcalls.
292 void EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO, RValue UpdateRVal,
293 bool IsVolatile);
294 /// Emit atomic update as LLVM instructions.
295 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRal,
296 bool IsVolatile);
297 };
298}
299
300Address AtomicInfo::CreateTempAlloca() const {
301 // Remove addrspace info from the atomic pointer element when making the
302 // alloca pointer element.
303 QualType TmpTy = (LVal.isBitField() && ValueSizeInBits > AtomicSizeInBits)
304 ? ValueTy
305 : AtomicTy.getUnqualifiedType();
306 Address TempAlloca =
307 CGF.CreateMemTempWithoutCast(TmpTy, getAtomicAlignment(), "atomic-temp");
308 // Cast to pointer to value type for bitfields.
309 if (LVal.isBitField())
311 TempAlloca, getAtomicAddress().getType(),
312 getAtomicAddress().getElementType());
313 return TempAlloca;
314}
315
317 StringRef fnName,
318 QualType resultType,
319 CallArgList &args) {
320 const CGFunctionInfo &fnInfo =
321 CGF.CGM.getTypes().arrangeBuiltinFunctionCall(resultType, args);
322 llvm::FunctionType *fnTy = CGF.CGM.getTypes().GetFunctionType(fnInfo);
323 llvm::AttrBuilder fnAttrB(CGF.getLLVMContext());
324 fnAttrB.addAttribute(llvm::Attribute::NoUnwind);
325 fnAttrB.addAttribute(llvm::Attribute::WillReturn);
326 llvm::AttributeList fnAttrs = llvm::AttributeList::get(
327 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, fnAttrB);
328
329 llvm::FunctionCallee fn =
330 CGF.CGM.CreateRuntimeFunction(fnTy, fnName, fnAttrs);
331 auto callee = CGCallee::forDirect(fn);
332 return CGF.EmitCall(fnInfo, callee, ReturnValueSlot(), args);
333}
334
335/// Does a store of the given IR type modify the full expected width?
336static bool isFullSizeType(CodeGenModule &CGM, llvm::Type *type,
337 uint64_t expectedSize) {
338 return (CGM.getDataLayout().getTypeStoreSize(type) * 8 == expectedSize);
339}
340
341/// Does the atomic type require memsetting to zero before initialization?
342///
343/// The IR type is provided as a way of making certain queries faster.
344bool AtomicInfo::requiresMemSetZero(llvm::Type *type) const {
345 // If the atomic type has size padding, we definitely need a memset.
346 if (hasPadding()) return true;
347
348 // Otherwise, do some simple heuristics to try to avoid it:
349 switch (getEvaluationKind()) {
350 // For scalars and complexes, check whether the store size of the
351 // type uses the full size.
352 case TEK_Scalar:
353 return !isFullSizeType(CGF.CGM, type, AtomicSizeInBits);
354 case TEK_Complex:
355 return !isFullSizeType(CGF.CGM, type->getStructElementType(0),
356 AtomicSizeInBits / 2);
357
358 // Padding in structs has an undefined bit pattern. User beware.
359 case TEK_Aggregate:
360 return false;
361 }
362 llvm_unreachable("bad evaluation kind");
363}
364
365bool AtomicInfo::emitMemSetZeroIfNecessary() const {
366 assert(LVal.isSimple());
367 Address addr = LVal.getAddress();
368 if (!requiresMemSetZero(addr.getElementType()))
369 return false;
370
372 addr.emitRawPointer(CGF), llvm::ConstantInt::get(CGF.Int8Ty, 0),
373 CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits).getQuantity(),
374 LVal.getAlignment().getAsAlign());
375 return true;
376}
377
378static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak,
379 Address Dest, Address Ptr, Address Val1,
380 Address Val2, Address ExpectedResult,
381 uint64_t Size, llvm::AtomicOrdering SuccessOrder,
382 llvm::AtomicOrdering FailureOrder,
383 llvm::SyncScope::ID Scope) {
384 // Note that cmpxchg doesn't support weak cmpxchg, at least at the moment.
385 llvm::Value *Expected = CGF.Builder.CreateLoad(Val1);
386 llvm::Value *Desired = CGF.Builder.CreateLoad(Val2);
387
388 llvm::AtomicCmpXchgInst *Pair = CGF.Builder.CreateAtomicCmpXchg(
389 Ptr, Expected, Desired, SuccessOrder, FailureOrder, Scope);
390 Pair->setVolatile(E->isVolatile());
391 Pair->setWeak(IsWeak);
392 CGF.getTargetHooks().setTargetAtomicMetadata(CGF, *Pair, E);
393
394 // Cmp holds the result of the compare-exchange operation: true on success,
395 // false on failure.
396 llvm::Value *Old = CGF.Builder.CreateExtractValue(Pair, 0);
397 llvm::Value *Cmp = CGF.Builder.CreateExtractValue(Pair, 1);
398
399 // This basic block is used to hold the store instruction if the operation
400 // failed.
401 llvm::BasicBlock *StoreExpectedBB =
402 CGF.createBasicBlock("cmpxchg.store_expected", CGF.CurFn);
403
404 // This basic block is the exit point of the operation, we should end up
405 // here regardless of whether or not the operation succeeded.
406 llvm::BasicBlock *ContinueBB =
407 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
408
409 // Update Expected if Expected isn't equal to Old, otherwise branch to the
410 // exit point.
411 CGF.Builder.CreateCondBr(Cmp, ContinueBB, StoreExpectedBB);
412
413 CGF.Builder.SetInsertPoint(StoreExpectedBB);
414 // Update the memory at Expected with Old's value.
415 llvm::Type *ExpectedType = ExpectedResult.getElementType();
416 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
417 uint64_t ExpectedSizeInBytes = DL.getTypeStoreSize(ExpectedType);
418
419 if (ExpectedSizeInBytes == Size) {
420 // Sizes match: store directly
421 auto *I = CGF.Builder.CreateStore(Old, ExpectedResult);
422 CGF.addInstToCurrentSourceAtom(I, Old);
423 } else {
424 // store only the first ExpectedSizeInBytes bytes of Old
425 llvm::Type *OldType = Old->getType();
426
427 // Allocate temporary storage for Old value
428 Address OldTmp =
429 CGF.CreateTempAlloca(OldType, Ptr.getAlignment(), "old.tmp");
430
431 // Store Old into this temporary
432 auto *I = CGF.Builder.CreateStore(Old, OldTmp);
433 CGF.addInstToCurrentSourceAtom(I, Old);
434
435 // Perform memcpy for first ExpectedSizeInBytes bytes
436 CGF.Builder.CreateMemCpy(ExpectedResult, OldTmp, ExpectedSizeInBytes,
437 /*isVolatile=*/false);
438 }
439
440 // Finally, branch to the exit point.
441 CGF.Builder.CreateBr(ContinueBB);
442
443 CGF.Builder.SetInsertPoint(ContinueBB);
444 // Update the memory at Dest with Cmp's value.
445 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
446}
447
448/// Given an ordering required on success, emit all possible cmpxchg
449/// instructions to cope with the provided (but possibly only dynamically known)
450/// FailureOrder.
452 CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak, Address Dest, Address Ptr,
453 Address Val1, Address Val2, Address ExpectedResult,
454 llvm::Value *FailureOrderVal, uint64_t Size,
455 llvm::AtomicOrdering SuccessOrder, llvm::SyncScope::ID Scope) {
456 llvm::AtomicOrdering FailureOrder;
457 if (llvm::ConstantInt *FO = dyn_cast<llvm::ConstantInt>(FailureOrderVal)) {
458 auto FOS = FO->getSExtValue();
459 if (!llvm::isValidAtomicOrderingCABI(FOS))
460 FailureOrder = llvm::AtomicOrdering::Monotonic;
461 else
462 switch ((llvm::AtomicOrderingCABI)FOS) {
463 case llvm::AtomicOrderingCABI::relaxed:
464 // 31.7.2.18: "The failure argument shall not be memory_order_release
465 // nor memory_order_acq_rel". Fallback to monotonic.
466 case llvm::AtomicOrderingCABI::release:
467 case llvm::AtomicOrderingCABI::acq_rel:
468 FailureOrder = llvm::AtomicOrdering::Monotonic;
469 break;
470 case llvm::AtomicOrderingCABI::consume:
471 case llvm::AtomicOrderingCABI::acquire:
472 FailureOrder = llvm::AtomicOrdering::Acquire;
473 break;
474 case llvm::AtomicOrderingCABI::seq_cst:
475 FailureOrder = llvm::AtomicOrdering::SequentiallyConsistent;
476 break;
477 }
478 // Prior to c++17, "the failure argument shall be no stronger than the
479 // success argument". This condition has been lifted and the only
480 // precondition is 31.7.2.18. Effectively treat this as a DR and skip
481 // language version checks.
482 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
483 Size, SuccessOrder, FailureOrder, Scope);
484 return;
485 }
486
487 // Create all the relevant BB's
488 auto *MonotonicBB = CGF.createBasicBlock("monotonic_fail", CGF.CurFn);
489 auto *AcquireBB = CGF.createBasicBlock("acquire_fail", CGF.CurFn);
490 auto *SeqCstBB = CGF.createBasicBlock("seqcst_fail", CGF.CurFn);
491 auto *ContBB = CGF.createBasicBlock("atomic.continue", CGF.CurFn);
492
493 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
494 // doesn't matter unless someone is crazy enough to use something that
495 // doesn't fold to a constant for the ordering.
496 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(FailureOrderVal, MonotonicBB);
497 // Implemented as acquire, since it's the closest in LLVM.
498 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
499 AcquireBB);
500 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
501 AcquireBB);
502 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
503 SeqCstBB);
504
505 // Emit all the different atomics
506 CGF.Builder.SetInsertPoint(MonotonicBB);
507 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult, Size,
508 SuccessOrder, llvm::AtomicOrdering::Monotonic, Scope);
509 CGF.Builder.CreateBr(ContBB);
510
511 CGF.Builder.SetInsertPoint(AcquireBB);
512 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult, Size,
513 SuccessOrder, llvm::AtomicOrdering::Acquire, Scope);
514 CGF.Builder.CreateBr(ContBB);
515
516 CGF.Builder.SetInsertPoint(SeqCstBB);
517 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult, Size,
518 SuccessOrder, llvm::AtomicOrdering::SequentiallyConsistent,
519 Scope);
520 CGF.Builder.CreateBr(ContBB);
521
522 CGF.Builder.SetInsertPoint(ContBB);
523}
524
525/// Duplicate the atomic min/max operation in conventional IR for the builtin
526/// variants that return the new rather than the original value.
527static llvm::Value *EmitPostAtomicMinMax(CGBuilderTy &Builder,
529 bool IsSigned,
530 llvm::Value *OldVal,
531 llvm::Value *RHS) {
532 const bool IsFP = OldVal->getType()->isFloatingPointTy();
533
534 if (IsFP) {
535 llvm::Intrinsic::ID IID = (Op == AtomicExpr::AO__atomic_max_fetch ||
536 Op == AtomicExpr::AO__scoped_atomic_max_fetch)
537 ? llvm::Intrinsic::maxnum
538 : llvm::Intrinsic::minnum;
539 return Builder.CreateBinaryIntrinsic(IID, OldVal, RHS, llvm::FMFSource(),
540 "newval");
541 }
542
543 llvm::CmpInst::Predicate Pred;
544 switch (Op) {
545 default:
546 llvm_unreachable("Unexpected min/max operation");
547 case AtomicExpr::AO__atomic_max_fetch:
548 case AtomicExpr::AO__scoped_atomic_max_fetch:
549 Pred = IsSigned ? llvm::CmpInst::ICMP_SGT : llvm::CmpInst::ICMP_UGT;
550 break;
551 case AtomicExpr::AO__atomic_min_fetch:
552 case AtomicExpr::AO__scoped_atomic_min_fetch:
553 Pred = IsSigned ? llvm::CmpInst::ICMP_SLT : llvm::CmpInst::ICMP_ULT;
554 break;
555 }
556 llvm::Value *Cmp = Builder.CreateICmp(Pred, OldVal, RHS, "tst");
557 return Builder.CreateSelect(Cmp, OldVal, RHS, "newval");
558}
559
561 Address Ptr, Address Val1, Address Val2,
562 Address ExpectedResult, llvm::Value *IsWeak,
563 llvm::Value *FailureOrder, uint64_t Size,
564 llvm::AtomicOrdering Order,
565 llvm::SyncScope::ID Scope) {
566 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
567 bool PostOpMinMax = false;
568 unsigned PostOp = 0;
569
570 switch (E->getOp()) {
571 case AtomicExpr::AO__c11_atomic_init:
572 case AtomicExpr::AO__opencl_atomic_init:
573 llvm_unreachable("Already handled!");
574
575 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
576 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
577 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
578 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
579 ExpectedResult, FailureOrder, Size, Order,
580 Scope);
581 return;
582 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
583 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
584 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
585 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
586 ExpectedResult, FailureOrder, Size, Order,
587 Scope);
588 return;
589 case AtomicExpr::AO__atomic_compare_exchange:
590 case AtomicExpr::AO__atomic_compare_exchange_n:
591 case AtomicExpr::AO__scoped_atomic_compare_exchange:
592 case AtomicExpr::AO__scoped_atomic_compare_exchange_n: {
593 if (llvm::ConstantInt *IsWeakC = dyn_cast<llvm::ConstantInt>(IsWeak)) {
594 emitAtomicCmpXchgFailureSet(CGF, E, IsWeakC->getZExtValue(), Dest, Ptr,
595 Val1, Val2, ExpectedResult, FailureOrder,
596 Size, Order, Scope);
597 } else {
598 // Create all the relevant BB's
599 llvm::BasicBlock *StrongBB =
600 CGF.createBasicBlock("cmpxchg.strong", CGF.CurFn);
601 llvm::BasicBlock *WeakBB = CGF.createBasicBlock("cmxchg.weak", CGF.CurFn);
602 llvm::BasicBlock *ContBB =
603 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
604
605 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(IsWeak, WeakBB);
606 SI->addCase(CGF.Builder.getInt1(false), StrongBB);
607
608 CGF.Builder.SetInsertPoint(StrongBB);
609 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
610 ExpectedResult, FailureOrder, Size, Order,
611 Scope);
612 CGF.Builder.CreateBr(ContBB);
613
614 CGF.Builder.SetInsertPoint(WeakBB);
615 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
616 ExpectedResult, FailureOrder, Size, Order,
617 Scope);
618 CGF.Builder.CreateBr(ContBB);
619
620 CGF.Builder.SetInsertPoint(ContBB);
621 }
622 return;
623 }
624 case AtomicExpr::AO__c11_atomic_load:
625 case AtomicExpr::AO__opencl_atomic_load:
626 case AtomicExpr::AO__hip_atomic_load:
627 case AtomicExpr::AO__atomic_load_n:
628 case AtomicExpr::AO__atomic_load:
629 case AtomicExpr::AO__scoped_atomic_load_n:
630 case AtomicExpr::AO__scoped_atomic_load: {
631 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
632 Load->setAtomic(Order, Scope);
633 Load->setVolatile(E->isVolatile());
634 CGF.getTargetHooks().setTargetAtomicMetadata(CGF, *Load, E);
635 CGF.maybeAttachRangeForLoad(Load, E->getValueType(), E->getExprLoc());
636 auto *I = CGF.Builder.CreateStore(Load, Dest);
637 CGF.addInstToCurrentSourceAtom(I, Load);
638 return;
639 }
640
641 case AtomicExpr::AO__c11_atomic_store:
642 case AtomicExpr::AO__opencl_atomic_store:
643 case AtomicExpr::AO__hip_atomic_store:
644 case AtomicExpr::AO__atomic_store:
645 case AtomicExpr::AO__atomic_store_n:
646 case AtomicExpr::AO__scoped_atomic_store:
647 case AtomicExpr::AO__scoped_atomic_store_n: {
648 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
649 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
650 Store->setAtomic(Order, Scope);
651 Store->setVolatile(E->isVolatile());
652 CGF.getTargetHooks().setTargetAtomicMetadata(CGF, *Store, E);
653 CGF.addInstToCurrentSourceAtom(Store, LoadVal1);
654 return;
655 }
656
657 case AtomicExpr::AO__c11_atomic_exchange:
658 case AtomicExpr::AO__hip_atomic_exchange:
659 case AtomicExpr::AO__opencl_atomic_exchange:
660 case AtomicExpr::AO__atomic_exchange_n:
661 case AtomicExpr::AO__atomic_exchange:
662 case AtomicExpr::AO__scoped_atomic_exchange_n:
663 case AtomicExpr::AO__scoped_atomic_exchange:
664 Op = llvm::AtomicRMWInst::Xchg;
665 break;
666
667 case AtomicExpr::AO__atomic_add_fetch:
668 case AtomicExpr::AO__scoped_atomic_add_fetch:
669 PostOp = E->getValueType()->isFloatingType() ? llvm::Instruction::FAdd
670 : llvm::Instruction::Add;
671 [[fallthrough]];
672 case AtomicExpr::AO__c11_atomic_fetch_add:
673 case AtomicExpr::AO__hip_atomic_fetch_add:
674 case AtomicExpr::AO__opencl_atomic_fetch_add:
675 case AtomicExpr::AO__atomic_fetch_add:
676 case AtomicExpr::AO__scoped_atomic_fetch_add:
677 Op = E->getValueType()->isFloatingType() ? llvm::AtomicRMWInst::FAdd
678 : llvm::AtomicRMWInst::Add;
679 break;
680
681 case AtomicExpr::AO__atomic_sub_fetch:
682 case AtomicExpr::AO__scoped_atomic_sub_fetch:
683 PostOp = E->getValueType()->isFloatingType() ? llvm::Instruction::FSub
684 : llvm::Instruction::Sub;
685 [[fallthrough]];
686 case AtomicExpr::AO__c11_atomic_fetch_sub:
687 case AtomicExpr::AO__hip_atomic_fetch_sub:
688 case AtomicExpr::AO__opencl_atomic_fetch_sub:
689 case AtomicExpr::AO__atomic_fetch_sub:
690 case AtomicExpr::AO__scoped_atomic_fetch_sub:
691 Op = E->getValueType()->isFloatingType() ? llvm::AtomicRMWInst::FSub
692 : llvm::AtomicRMWInst::Sub;
693 break;
694
695 case AtomicExpr::AO__atomic_min_fetch:
696 case AtomicExpr::AO__scoped_atomic_min_fetch:
697 PostOpMinMax = true;
698 [[fallthrough]];
699 case AtomicExpr::AO__c11_atomic_fetch_min:
700 case AtomicExpr::AO__hip_atomic_fetch_min:
701 case AtomicExpr::AO__opencl_atomic_fetch_min:
702 case AtomicExpr::AO__atomic_fetch_min:
703 case AtomicExpr::AO__scoped_atomic_fetch_min:
704 Op = E->getValueType()->isFloatingType()
705 ? llvm::AtomicRMWInst::FMin
706 : (E->getValueType()->isSignedIntegerType()
707 ? llvm::AtomicRMWInst::Min
708 : llvm::AtomicRMWInst::UMin);
709 break;
710
711 case AtomicExpr::AO__atomic_fetch_fminimum:
712 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
713 assert(E->getValueType()->isFloatingType() &&
714 "fminimum operations only support floating-point types");
715 Op = llvm::AtomicRMWInst::FMinimum;
716 break;
717
718 case AtomicExpr::AO__atomic_fetch_fminimum_num:
719 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
720 assert(E->getValueType()->isFloatingType() &&
721 "fminimum_num operations only support floating-point types");
722 Op = llvm::AtomicRMWInst::FMinimumNum;
723 break;
724
725 case AtomicExpr::AO__atomic_max_fetch:
726 case AtomicExpr::AO__scoped_atomic_max_fetch:
727 PostOpMinMax = true;
728 [[fallthrough]];
729 case AtomicExpr::AO__c11_atomic_fetch_max:
730 case AtomicExpr::AO__hip_atomic_fetch_max:
731 case AtomicExpr::AO__opencl_atomic_fetch_max:
732 case AtomicExpr::AO__atomic_fetch_max:
733 case AtomicExpr::AO__scoped_atomic_fetch_max:
734 Op = E->getValueType()->isFloatingType()
735 ? llvm::AtomicRMWInst::FMax
736 : (E->getValueType()->isSignedIntegerType()
737 ? llvm::AtomicRMWInst::Max
738 : llvm::AtomicRMWInst::UMax);
739 break;
740
741 case AtomicExpr::AO__atomic_fetch_fmaximum:
742 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
743 assert(E->getValueType()->isFloatingType() &&
744 "fmaximum operations only support floating-point types");
745 Op = llvm::AtomicRMWInst::FMaximum;
746 break;
747
748 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
749 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
750 assert(E->getValueType()->isFloatingType() &&
751 "fmaximum_num operations only support floating-point types");
752 Op = llvm::AtomicRMWInst::FMaximumNum;
753 break;
754
755 case AtomicExpr::AO__atomic_and_fetch:
756 case AtomicExpr::AO__scoped_atomic_and_fetch:
757 PostOp = llvm::Instruction::And;
758 [[fallthrough]];
759 case AtomicExpr::AO__c11_atomic_fetch_and:
760 case AtomicExpr::AO__hip_atomic_fetch_and:
761 case AtomicExpr::AO__opencl_atomic_fetch_and:
762 case AtomicExpr::AO__atomic_fetch_and:
763 case AtomicExpr::AO__scoped_atomic_fetch_and:
764 Op = llvm::AtomicRMWInst::And;
765 break;
766
767 case AtomicExpr::AO__atomic_or_fetch:
768 case AtomicExpr::AO__scoped_atomic_or_fetch:
769 PostOp = llvm::Instruction::Or;
770 [[fallthrough]];
771 case AtomicExpr::AO__c11_atomic_fetch_or:
772 case AtomicExpr::AO__hip_atomic_fetch_or:
773 case AtomicExpr::AO__opencl_atomic_fetch_or:
774 case AtomicExpr::AO__atomic_fetch_or:
775 case AtomicExpr::AO__scoped_atomic_fetch_or:
776 Op = llvm::AtomicRMWInst::Or;
777 break;
778
779 case AtomicExpr::AO__atomic_xor_fetch:
780 case AtomicExpr::AO__scoped_atomic_xor_fetch:
781 PostOp = llvm::Instruction::Xor;
782 [[fallthrough]];
783 case AtomicExpr::AO__c11_atomic_fetch_xor:
784 case AtomicExpr::AO__hip_atomic_fetch_xor:
785 case AtomicExpr::AO__opencl_atomic_fetch_xor:
786 case AtomicExpr::AO__atomic_fetch_xor:
787 case AtomicExpr::AO__scoped_atomic_fetch_xor:
788 Op = llvm::AtomicRMWInst::Xor;
789 break;
790
791 case AtomicExpr::AO__atomic_nand_fetch:
792 case AtomicExpr::AO__scoped_atomic_nand_fetch:
793 PostOp = llvm::Instruction::And; // the NOT is special cased below
794 [[fallthrough]];
795 case AtomicExpr::AO__c11_atomic_fetch_nand:
796 case AtomicExpr::AO__atomic_fetch_nand:
797 case AtomicExpr::AO__scoped_atomic_fetch_nand:
798 Op = llvm::AtomicRMWInst::Nand;
799 break;
800
801 case AtomicExpr::AO__atomic_fetch_uinc:
802 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
803 Op = llvm::AtomicRMWInst::UIncWrap;
804 break;
805 case AtomicExpr::AO__atomic_fetch_udec:
806 case AtomicExpr::AO__scoped_atomic_fetch_udec:
807 Op = llvm::AtomicRMWInst::UDecWrap;
808 break;
809
810 case AtomicExpr::AO__atomic_test_and_set: {
811 llvm::AtomicRMWInst *RMWI =
812 CGF.emitAtomicRMWInst(llvm::AtomicRMWInst::Xchg, Ptr,
813 CGF.Builder.getInt8(1), Order, Scope, E);
814 RMWI->setVolatile(E->isVolatile());
815 llvm::Value *Result = CGF.EmitToMemory(
816 CGF.Builder.CreateIsNotNull(RMWI, "tobool"), E->getType());
817 auto *I = CGF.Builder.CreateStore(Result, Dest);
819 return;
820 }
821
822 case AtomicExpr::AO__atomic_clear: {
823 llvm::StoreInst *Store =
824 CGF.Builder.CreateStore(CGF.Builder.getInt8(0), Ptr);
825 Store->setAtomic(Order, Scope);
826 Store->setVolatile(E->isVolatile());
827 CGF.getTargetHooks().setTargetAtomicMetadata(CGF, *Store, E);
828 CGF.addInstToCurrentSourceAtom(Store, nullptr);
829 return;
830 }
831 }
832
833 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
834 llvm::AtomicRMWInst *RMWI =
835 CGF.emitAtomicRMWInst(Op, Ptr, LoadVal1, Order, Scope, E);
836 RMWI->setVolatile(E->isVolatile());
837
838 // For __atomic_*_fetch operations, perform the operation again to
839 // determine the value which was written.
840 llvm::Value *Result = RMWI;
841 if (PostOpMinMax)
844 RMWI, LoadVal1);
845 else if (PostOp)
846 Result = CGF.Builder.CreateBinOp((llvm::Instruction::BinaryOps)PostOp, RMWI,
847 LoadVal1);
848 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch ||
849 E->getOp() == AtomicExpr::AO__scoped_atomic_nand_fetch)
850 Result = CGF.Builder.CreateNot(Result);
851 auto *I = CGF.Builder.CreateStore(Result, Dest);
853}
854
855// This function emits any expression (scalar, complex, or aggregate)
856// into a temporary alloca.
857static Address
859 Address DeclPtr = CGF.CreateMemTempWithoutCast(E->getType(), ".atomictmp");
860 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
861 /*Init*/ true);
862 return DeclPtr;
863}
864
865/// Return true if \param ValTy is a type that should be casted to integer
866/// around the atomic memory operation. If \param CmpXchg is true, then the
867/// cast of a floating point type is made as that instruction can not have
868/// floating point operands. TODO: Allow compare-and-exchange and FP - see
869/// comment in AtomicExpandPass.cpp.
870static bool shouldCastToInt(llvm::Type *ValTy, bool CmpXchg) {
871 if (ValTy->isFloatingPointTy())
872 return ValTy->isX86_FP80Ty() || CmpXchg;
873 return !ValTy->isIntegerTy() && !ValTy->isPointerTy();
874}
875
877 Address Ptr, Address Val1, Address Val2,
878 Address OriginalVal1, llvm::Value *IsWeak,
879 llvm::Value *FailureOrder, uint64_t Size,
880 llvm::AtomicOrdering Order, llvm::Value *Scope) {
881 auto ScopeModel = Expr->getScopeModel();
882
883 // LLVM atomic instructions always have sync scope. If clang atomic
884 // expression has no scope operand, use default LLVM sync scope.
885 if (!ScopeModel) {
886 llvm::SyncScope::ID SS;
887 if (CGF.getLangOpts().OpenCL)
888 // OpenCL approach is: "The functions that do not have memory_scope
889 // argument have the same semantics as the corresponding functions with
890 // the memory_scope argument set to memory_scope_device." See ref.:
891 // https://registry.khronos.org/OpenCL/specs/3.0-unified/html/OpenCL_C.html#atomic-functions
894 Order, CGF.getLLVMContext());
895 else
896 SS = llvm::SyncScope::System;
897 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
898 FailureOrder, Size, Order, SS);
899 return;
900 }
901
902 // Handle constant scope.
903 if (auto SC = dyn_cast<llvm::ConstantInt>(Scope)) {
904 auto SCID = CGF.getTargetHooks().getLLVMSyncScopeID(
905 CGF.CGM.getLangOpts(), ScopeModel->map(SC->getZExtValue()),
906 Order, CGF.CGM.getLLVMContext());
907 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
908 FailureOrder, Size, Order, SCID);
909 return;
910 }
911
912 // Handle non-constant scope.
913 auto &Builder = CGF.Builder;
914 auto Scopes = ScopeModel->getRuntimeValues();
915 llvm::DenseMap<unsigned, llvm::BasicBlock *> BB;
916 for (auto S : Scopes)
917 BB[S] = CGF.createBasicBlock(getAsString(ScopeModel->map(S)), CGF.CurFn);
918
919 llvm::BasicBlock *ContBB =
920 CGF.createBasicBlock("atomic.scope.continue", CGF.CurFn);
921
922 auto *SC = Builder.CreateIntCast(Scope, Builder.getInt32Ty(), false);
923 // If unsupported sync scope is encountered at run time, assume a fallback
924 // sync scope value.
925 auto FallBack = ScopeModel->getFallBackValue();
926 llvm::SwitchInst *SI = Builder.CreateSwitch(SC, BB[FallBack]);
927 for (auto S : Scopes) {
928 auto *B = BB[S];
929 if (S != FallBack)
930 SI->addCase(Builder.getInt32(S), B);
931
932 Builder.SetInsertPoint(B);
933 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
934 FailureOrder, Size, Order,
936 CGF.CGM.getLangOpts(), ScopeModel->map(S), Order,
937 CGF.getLLVMContext()));
938 Builder.CreateBr(ContBB);
939 }
940
941 Builder.SetInsertPoint(ContBB);
942}
943
946
947 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
948 QualType MemTy = AtomicTy;
949 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
950 MemTy = AT->getValueType();
951 llvm::Value *IsWeak = nullptr, *OrderFail = nullptr;
952
953 Address Val1 = Address::invalid();
954 Address Val2 = Address::invalid();
955 Address Dest = Address::invalid();
957
958 if (E->getOp() == AtomicExpr::AO__c11_atomic_init ||
959 E->getOp() == AtomicExpr::AO__opencl_atomic_init) {
960 LValue lvalue = MakeAddrLValue(Ptr, AtomicTy);
961 EmitAtomicInit(E->getVal1(), lvalue);
962 return RValue::get(nullptr);
963 }
964
965 auto TInfo = getContext().getTypeInfoInChars(AtomicTy);
966 uint64_t Size = TInfo.Width.getQuantity();
967 unsigned MaxInlineWidthInBits = getTarget().getMaxAtomicInlineWidth();
968
969 CharUnits MaxInlineWidth =
970 getContext().toCharUnitsFromBits(MaxInlineWidthInBits);
971 DiagnosticsEngine &Diags = CGM.getDiags();
972 bool Misaligned = !Ptr.getAlignment().isMultipleOf(TInfo.Width);
973 bool Oversized = getContext().toBits(TInfo.Width) > MaxInlineWidthInBits;
974 if (Misaligned) {
975 Diags.Report(E->getBeginLoc(), diag::warn_atomic_op_misaligned)
976 << (int)TInfo.Width.getQuantity()
977 << (int)Ptr.getAlignment().getQuantity();
978 }
979 if (Oversized) {
980 Diags.Report(E->getBeginLoc(), diag::warn_atomic_op_oversized)
981 << (int)TInfo.Width.getQuantity() << (int)MaxInlineWidth.getQuantity();
982 }
983
984 llvm::Value *Order = EmitScalarExpr(E->getOrder());
985 llvm::Value *Scope =
986 E->getScopeModel() ? EmitScalarExpr(E->getScope()) : nullptr;
987
988 switch (E->getOp()) {
989 case AtomicExpr::AO__c11_atomic_init:
990 case AtomicExpr::AO__opencl_atomic_init:
991 llvm_unreachable("Already handled above with EmitAtomicInit!");
992
993 case AtomicExpr::AO__atomic_load_n:
994 case AtomicExpr::AO__scoped_atomic_load_n:
995 case AtomicExpr::AO__c11_atomic_load:
996 case AtomicExpr::AO__opencl_atomic_load:
997 case AtomicExpr::AO__hip_atomic_load:
998 case AtomicExpr::AO__atomic_test_and_set:
999 case AtomicExpr::AO__atomic_clear:
1000 break;
1001
1002 case AtomicExpr::AO__atomic_load:
1003 case AtomicExpr::AO__scoped_atomic_load:
1004 Dest = EmitPointerWithAlignment(E->getVal1());
1005 break;
1006
1007 case AtomicExpr::AO__atomic_store:
1008 case AtomicExpr::AO__scoped_atomic_store:
1009 Val1 = EmitPointerWithAlignment(E->getVal1());
1010 break;
1011
1012 case AtomicExpr::AO__atomic_exchange:
1013 case AtomicExpr::AO__scoped_atomic_exchange:
1014 Val1 = EmitPointerWithAlignment(E->getVal1());
1015 Dest = EmitPointerWithAlignment(E->getVal2());
1016 break;
1017
1018 case AtomicExpr::AO__atomic_compare_exchange:
1019 case AtomicExpr::AO__atomic_compare_exchange_n:
1020 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1021 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1022 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
1023 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
1024 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1025 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
1026 case AtomicExpr::AO__scoped_atomic_compare_exchange:
1027 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
1028 Val1 = EmitPointerWithAlignment(E->getVal1());
1029 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
1030 E->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange)
1031 Val2 = EmitPointerWithAlignment(E->getVal2());
1032 else
1033 Val2 = EmitValToTemp(*this, E->getVal2());
1034 OrderFail = EmitScalarExpr(E->getOrderFail());
1035 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
1036 E->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
1037 E->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange_n ||
1038 E->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange)
1039 IsWeak = EmitScalarExpr(E->getWeak());
1040 break;
1041
1042 case AtomicExpr::AO__c11_atomic_fetch_add:
1043 case AtomicExpr::AO__c11_atomic_fetch_sub:
1044 case AtomicExpr::AO__hip_atomic_fetch_add:
1045 case AtomicExpr::AO__hip_atomic_fetch_sub:
1046 case AtomicExpr::AO__opencl_atomic_fetch_add:
1047 case AtomicExpr::AO__opencl_atomic_fetch_sub:
1048 if (MemTy->isPointerType()) {
1049 // For pointer arithmetic, we're required to do a bit of math:
1050 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
1051 // ... but only for the C11 builtins. The GNU builtins expect the
1052 // user to multiply by sizeof(T).
1053 QualType Val1Ty = E->getVal1()->getType();
1054 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
1055 CharUnits PointeeIncAmt =
1056 getContext().getTypeSizeInChars(MemTy->getPointeeType());
1057 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
1058 auto Temp = CreateMemTempWithoutCast(Val1Ty, ".atomictmp");
1059 Val1 = Temp;
1060 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Temp, Val1Ty));
1061 break;
1062 }
1063 [[fallthrough]];
1064 case AtomicExpr::AO__atomic_fetch_add:
1065 case AtomicExpr::AO__atomic_fetch_max:
1066 case AtomicExpr::AO__atomic_fetch_min:
1067 case AtomicExpr::AO__atomic_fetch_sub:
1068 case AtomicExpr::AO__atomic_add_fetch:
1069 case AtomicExpr::AO__atomic_max_fetch:
1070 case AtomicExpr::AO__atomic_min_fetch:
1071 case AtomicExpr::AO__atomic_sub_fetch:
1072 case AtomicExpr::AO__c11_atomic_fetch_max:
1073 case AtomicExpr::AO__c11_atomic_fetch_min:
1074 case AtomicExpr::AO__opencl_atomic_fetch_max:
1075 case AtomicExpr::AO__opencl_atomic_fetch_min:
1076 case AtomicExpr::AO__hip_atomic_fetch_max:
1077 case AtomicExpr::AO__hip_atomic_fetch_min:
1078 case AtomicExpr::AO__scoped_atomic_fetch_add:
1079 case AtomicExpr::AO__scoped_atomic_fetch_max:
1080 case AtomicExpr::AO__scoped_atomic_fetch_min:
1081 case AtomicExpr::AO__scoped_atomic_fetch_sub:
1082 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
1083 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
1084 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
1085 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
1086 case AtomicExpr::AO__scoped_atomic_add_fetch:
1087 case AtomicExpr::AO__scoped_atomic_max_fetch:
1088 case AtomicExpr::AO__scoped_atomic_min_fetch:
1089 case AtomicExpr::AO__scoped_atomic_sub_fetch:
1090 [[fallthrough]];
1091
1092 case AtomicExpr::AO__atomic_fetch_and:
1093 case AtomicExpr::AO__atomic_fetch_nand:
1094 case AtomicExpr::AO__atomic_fetch_or:
1095 case AtomicExpr::AO__atomic_fetch_xor:
1096 case AtomicExpr::AO__atomic_fetch_uinc:
1097 case AtomicExpr::AO__atomic_fetch_udec:
1098 case AtomicExpr::AO__atomic_and_fetch:
1099 case AtomicExpr::AO__atomic_nand_fetch:
1100 case AtomicExpr::AO__atomic_or_fetch:
1101 case AtomicExpr::AO__atomic_xor_fetch:
1102 case AtomicExpr::AO__atomic_store_n:
1103 case AtomicExpr::AO__atomic_exchange_n:
1104 case AtomicExpr::AO__c11_atomic_fetch_and:
1105 case AtomicExpr::AO__c11_atomic_fetch_nand:
1106 case AtomicExpr::AO__c11_atomic_fetch_or:
1107 case AtomicExpr::AO__c11_atomic_fetch_xor:
1108 case AtomicExpr::AO__c11_atomic_store:
1109 case AtomicExpr::AO__c11_atomic_exchange:
1110 case AtomicExpr::AO__hip_atomic_fetch_and:
1111 case AtomicExpr::AO__hip_atomic_fetch_or:
1112 case AtomicExpr::AO__hip_atomic_fetch_xor:
1113 case AtomicExpr::AO__hip_atomic_store:
1114 case AtomicExpr::AO__hip_atomic_exchange:
1115 case AtomicExpr::AO__opencl_atomic_fetch_and:
1116 case AtomicExpr::AO__opencl_atomic_fetch_or:
1117 case AtomicExpr::AO__opencl_atomic_fetch_xor:
1118 case AtomicExpr::AO__opencl_atomic_store:
1119 case AtomicExpr::AO__opencl_atomic_exchange:
1120 case AtomicExpr::AO__scoped_atomic_fetch_and:
1121 case AtomicExpr::AO__scoped_atomic_fetch_nand:
1122 case AtomicExpr::AO__scoped_atomic_fetch_or:
1123 case AtomicExpr::AO__scoped_atomic_fetch_xor:
1124 case AtomicExpr::AO__scoped_atomic_and_fetch:
1125 case AtomicExpr::AO__scoped_atomic_nand_fetch:
1126 case AtomicExpr::AO__scoped_atomic_or_fetch:
1127 case AtomicExpr::AO__scoped_atomic_xor_fetch:
1128 case AtomicExpr::AO__scoped_atomic_store_n:
1129 case AtomicExpr::AO__scoped_atomic_exchange_n:
1130 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
1131 case AtomicExpr::AO__scoped_atomic_fetch_udec:
1132 case AtomicExpr::AO__atomic_fetch_fminimum:
1133 case AtomicExpr::AO__atomic_fetch_fmaximum:
1134 case AtomicExpr::AO__atomic_fetch_fminimum_num:
1135 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
1136 Val1 = EmitValToTemp(*this, E->getVal1());
1137 break;
1138 }
1139
1140 QualType RValTy = E->getType().getUnqualifiedType();
1141 bool ShouldCastToIntPtrTy =
1143
1144 // The inlined atomics only function on iN types, where N is a power of 2. We
1145 // need to make sure (via temporaries if necessary) that all incoming values
1146 // are compatible.
1147 LValue AtomicVal = MakeAddrLValue(Ptr, AtomicTy);
1148 AtomicInfo Atomics(*this, AtomicVal);
1149
1150 Address OriginalVal1 = Val1;
1151 if (ShouldCastToIntPtrTy) {
1152 Ptr = Atomics.castToAtomicIntPointer(Ptr);
1153 if (Val1.isValid())
1154 Val1 = Atomics.convertToAtomicIntPointer(Val1);
1155 if (Val2.isValid())
1156 Val2 = Atomics.convertToAtomicIntPointer(Val2);
1157 }
1158 if (Dest.isValid()) {
1159 if (ShouldCastToIntPtrTy)
1160 Dest = Atomics.castToAtomicIntPointer(Dest);
1161 } else if (E->isCmpXChg())
1162 Dest = CreateMemTempWithoutCast(RValTy, "cmpxchg.bool");
1163 else if (!RValTy->isVoidType()) {
1164 Dest = Atomics.CreateTempAlloca();
1165 if (ShouldCastToIntPtrTy)
1166 Dest = Atomics.castToAtomicIntPointer(Dest);
1167 }
1168
1169 bool PowerOf2Size = (Size & (Size - 1)) == 0;
1170 bool UseLibcall = !PowerOf2Size || (Size > 16);
1171
1172 // For atomics larger than 16 bytes, emit a libcall from the frontend. This
1173 // avoids the overhead of dealing with excessively-large value types in IR.
1174 // Non-power-of-2 values also lower to libcall here, as they are not currently
1175 // permitted in IR instructions (although that constraint could be relaxed in
1176 // the future). For other cases where a libcall is required on a given
1177 // platform, we let the backend handle it (this includes handling for all of
1178 // the size-optimized libcall variants, which are only valid up to 16 bytes.)
1179 //
1180 // See: https://llvm.org/docs/Atomics.html#libcalls-atomic
1181 if (UseLibcall) {
1182 CallArgList Args;
1183 // For non-optimized library calls, the size is the first parameter.
1184 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
1185 getContext().getSizeType());
1186
1187 // The atomic address is the second parameter.
1188 // The OpenCL atomic library functions only accept pointer arguments to
1189 // generic address space.
1190 auto CastToGenericAddrSpace = [&](llvm::Value *V, QualType PT) {
1191 if (!E->isOpenCL())
1192 return V;
1193 auto AS = PT->castAs<PointerType>()->getPointeeType().getAddressSpace();
1194 if (AS == LangAS::opencl_generic)
1195 return V;
1196 auto DestAS = getContext().getTargetAddressSpace(LangAS::opencl_generic);
1197 auto *DestType = llvm::PointerType::get(getLLVMContext(), DestAS);
1198
1199 return performAddrSpaceCast(V, DestType);
1200 };
1201
1202 Args.add(RValue::get(CastToGenericAddrSpace(Ptr.emitRawPointer(*this),
1203 E->getPtr()->getType())),
1205
1206 // The next 1-3 parameters are op-dependent.
1207 std::string LibCallName;
1208 QualType RetTy;
1209 bool HaveRetTy = false;
1210 switch (E->getOp()) {
1211 case AtomicExpr::AO__c11_atomic_init:
1212 case AtomicExpr::AO__opencl_atomic_init:
1213 llvm_unreachable("Already handled!");
1214
1215 // There is only one libcall for compare an exchange, because there is no
1216 // optimisation benefit possible from a libcall version of a weak compare
1217 // and exchange.
1218 // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
1219 // void *desired, int success, int failure)
1220 case AtomicExpr::AO__atomic_compare_exchange:
1221 case AtomicExpr::AO__atomic_compare_exchange_n:
1222 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1223 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1224 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
1225 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
1226 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1227 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
1228 case AtomicExpr::AO__scoped_atomic_compare_exchange:
1229 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
1230 LibCallName = "__atomic_compare_exchange";
1231 RetTy = getContext().BoolTy;
1232 HaveRetTy = true;
1233 Args.add(RValue::get(CastToGenericAddrSpace(Val1.emitRawPointer(*this),
1234 E->getVal1()->getType())),
1236 Args.add(RValue::get(CastToGenericAddrSpace(Val2.emitRawPointer(*this),
1237 E->getVal2()->getType())),
1239 Args.add(RValue::get(Order), getContext().IntTy);
1240 Order = OrderFail;
1241 break;
1242 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
1243 // int order)
1244 case AtomicExpr::AO__atomic_exchange:
1245 case AtomicExpr::AO__atomic_exchange_n:
1246 case AtomicExpr::AO__c11_atomic_exchange:
1247 case AtomicExpr::AO__hip_atomic_exchange:
1248 case AtomicExpr::AO__opencl_atomic_exchange:
1249 case AtomicExpr::AO__scoped_atomic_exchange:
1250 case AtomicExpr::AO__scoped_atomic_exchange_n:
1251 LibCallName = "__atomic_exchange";
1252 Args.add(RValue::get(CastToGenericAddrSpace(Val1.emitRawPointer(*this),
1253 E->getVal1()->getType())),
1255 break;
1256 // void __atomic_store(size_t size, void *mem, void *val, int order)
1257 case AtomicExpr::AO__atomic_store:
1258 case AtomicExpr::AO__atomic_store_n:
1259 case AtomicExpr::AO__c11_atomic_store:
1260 case AtomicExpr::AO__hip_atomic_store:
1261 case AtomicExpr::AO__opencl_atomic_store:
1262 case AtomicExpr::AO__scoped_atomic_store:
1263 case AtomicExpr::AO__scoped_atomic_store_n:
1264 LibCallName = "__atomic_store";
1265 RetTy = getContext().VoidTy;
1266 HaveRetTy = true;
1267 Args.add(RValue::get(CastToGenericAddrSpace(Val1.emitRawPointer(*this),
1268 E->getVal1()->getType())),
1270 break;
1271 // void __atomic_load(size_t size, void *mem, void *return, int order)
1272 case AtomicExpr::AO__atomic_load:
1273 case AtomicExpr::AO__atomic_load_n:
1274 case AtomicExpr::AO__c11_atomic_load:
1275 case AtomicExpr::AO__hip_atomic_load:
1276 case AtomicExpr::AO__opencl_atomic_load:
1277 case AtomicExpr::AO__scoped_atomic_load:
1278 case AtomicExpr::AO__scoped_atomic_load_n:
1279 LibCallName = "__atomic_load";
1280 break;
1281 case AtomicExpr::AO__atomic_add_fetch:
1282 case AtomicExpr::AO__scoped_atomic_add_fetch:
1283 case AtomicExpr::AO__atomic_fetch_add:
1284 case AtomicExpr::AO__c11_atomic_fetch_add:
1285 case AtomicExpr::AO__hip_atomic_fetch_add:
1286 case AtomicExpr::AO__opencl_atomic_fetch_add:
1287 case AtomicExpr::AO__scoped_atomic_fetch_add:
1288 case AtomicExpr::AO__atomic_and_fetch:
1289 case AtomicExpr::AO__scoped_atomic_and_fetch:
1290 case AtomicExpr::AO__atomic_fetch_and:
1291 case AtomicExpr::AO__c11_atomic_fetch_and:
1292 case AtomicExpr::AO__hip_atomic_fetch_and:
1293 case AtomicExpr::AO__opencl_atomic_fetch_and:
1294 case AtomicExpr::AO__scoped_atomic_fetch_and:
1295 case AtomicExpr::AO__atomic_or_fetch:
1296 case AtomicExpr::AO__scoped_atomic_or_fetch:
1297 case AtomicExpr::AO__atomic_fetch_or:
1298 case AtomicExpr::AO__c11_atomic_fetch_or:
1299 case AtomicExpr::AO__hip_atomic_fetch_or:
1300 case AtomicExpr::AO__opencl_atomic_fetch_or:
1301 case AtomicExpr::AO__scoped_atomic_fetch_or:
1302 case AtomicExpr::AO__atomic_sub_fetch:
1303 case AtomicExpr::AO__scoped_atomic_sub_fetch:
1304 case AtomicExpr::AO__atomic_fetch_sub:
1305 case AtomicExpr::AO__c11_atomic_fetch_sub:
1306 case AtomicExpr::AO__hip_atomic_fetch_sub:
1307 case AtomicExpr::AO__opencl_atomic_fetch_sub:
1308 case AtomicExpr::AO__scoped_atomic_fetch_sub:
1309 case AtomicExpr::AO__atomic_xor_fetch:
1310 case AtomicExpr::AO__scoped_atomic_xor_fetch:
1311 case AtomicExpr::AO__atomic_fetch_xor:
1312 case AtomicExpr::AO__c11_atomic_fetch_xor:
1313 case AtomicExpr::AO__hip_atomic_fetch_xor:
1314 case AtomicExpr::AO__opencl_atomic_fetch_xor:
1315 case AtomicExpr::AO__scoped_atomic_fetch_xor:
1316 case AtomicExpr::AO__atomic_nand_fetch:
1317 case AtomicExpr::AO__atomic_fetch_nand:
1318 case AtomicExpr::AO__c11_atomic_fetch_nand:
1319 case AtomicExpr::AO__scoped_atomic_fetch_nand:
1320 case AtomicExpr::AO__scoped_atomic_nand_fetch:
1321 case AtomicExpr::AO__atomic_min_fetch:
1322 case AtomicExpr::AO__atomic_fetch_min:
1323 case AtomicExpr::AO__c11_atomic_fetch_min:
1324 case AtomicExpr::AO__hip_atomic_fetch_min:
1325 case AtomicExpr::AO__opencl_atomic_fetch_min:
1326 case AtomicExpr::AO__scoped_atomic_fetch_min:
1327 case AtomicExpr::AO__scoped_atomic_min_fetch:
1328 case AtomicExpr::AO__atomic_max_fetch:
1329 case AtomicExpr::AO__atomic_fetch_max:
1330 case AtomicExpr::AO__c11_atomic_fetch_max:
1331 case AtomicExpr::AO__hip_atomic_fetch_max:
1332 case AtomicExpr::AO__opencl_atomic_fetch_max:
1333 case AtomicExpr::AO__scoped_atomic_fetch_max:
1334 case AtomicExpr::AO__scoped_atomic_max_fetch:
1335 case AtomicExpr::AO__atomic_fetch_fminimum:
1336 case AtomicExpr::AO__atomic_fetch_fmaximum:
1337 case AtomicExpr::AO__atomic_fetch_fminimum_num:
1338 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
1339 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
1340 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
1341 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
1342 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
1343 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
1344 case AtomicExpr::AO__scoped_atomic_fetch_udec:
1345 case AtomicExpr::AO__atomic_test_and_set:
1346 case AtomicExpr::AO__atomic_clear:
1347 case AtomicExpr::AO__atomic_fetch_uinc:
1348 case AtomicExpr::AO__atomic_fetch_udec:
1349 llvm_unreachable("Integral atomic operations always become atomicrmw!");
1350 }
1351
1352 if (E->isOpenCL()) {
1353 LibCallName =
1354 std::string("__opencl") + StringRef(LibCallName).drop_front(1).str();
1355 }
1356 // By default, assume we return a value of the atomic type.
1357 if (!HaveRetTy) {
1358 // Value is returned through parameter before the order.
1359 RetTy = getContext().VoidTy;
1360 Args.add(RValue::get(
1361 CastToGenericAddrSpace(Dest.emitRawPointer(*this), RetTy)),
1363 }
1364 // Order is always the last parameter.
1365 Args.add(RValue::get(Order),
1366 getContext().IntTy);
1367 if (E->isOpenCL())
1369
1370 RValue Res = emitAtomicLibcall(*this, LibCallName, RetTy, Args);
1371 // The value is returned directly from the libcall.
1372 if (E->isCmpXChg())
1373 return Res;
1374
1375 if (RValTy->isVoidType())
1376 return RValue::get(nullptr);
1377
1379 RValTy, E->getExprLoc());
1380 }
1381
1382 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
1383 E->getOp() == AtomicExpr::AO__opencl_atomic_store ||
1384 E->getOp() == AtomicExpr::AO__hip_atomic_store ||
1385 E->getOp() == AtomicExpr::AO__atomic_store ||
1386 E->getOp() == AtomicExpr::AO__atomic_store_n ||
1387 E->getOp() == AtomicExpr::AO__scoped_atomic_store ||
1388 E->getOp() == AtomicExpr::AO__scoped_atomic_store_n ||
1389 E->getOp() == AtomicExpr::AO__atomic_clear;
1390 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
1391 E->getOp() == AtomicExpr::AO__opencl_atomic_load ||
1392 E->getOp() == AtomicExpr::AO__hip_atomic_load ||
1393 E->getOp() == AtomicExpr::AO__atomic_load ||
1394 E->getOp() == AtomicExpr::AO__atomic_load_n ||
1395 E->getOp() == AtomicExpr::AO__scoped_atomic_load ||
1396 E->getOp() == AtomicExpr::AO__scoped_atomic_load_n;
1397
1398 if (isa<llvm::ConstantInt>(Order)) {
1399 auto ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
1400 // We should not ever get to a case where the ordering isn't a valid C ABI
1401 // value, but it's hard to enforce that in general.
1402 if (llvm::isValidAtomicOrderingCABI(ord))
1403 switch ((llvm::AtomicOrderingCABI)ord) {
1404 case llvm::AtomicOrderingCABI::relaxed:
1405 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1406 OrderFail, Size, llvm::AtomicOrdering::Monotonic, Scope);
1407 break;
1408 case llvm::AtomicOrderingCABI::consume:
1409 case llvm::AtomicOrderingCABI::acquire:
1410 if (IsStore)
1411 break; // Avoid crashing on code with undefined behavior
1412 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1413 OrderFail, Size, llvm::AtomicOrdering::Acquire, Scope);
1414 break;
1415 case llvm::AtomicOrderingCABI::release:
1416 if (IsLoad)
1417 break; // Avoid crashing on code with undefined behavior
1418 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1419 OrderFail, Size, llvm::AtomicOrdering::Release, Scope);
1420 break;
1421 case llvm::AtomicOrderingCABI::acq_rel:
1422 if (IsLoad || IsStore)
1423 break; // Avoid crashing on code with undefined behavior
1424 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1425 OrderFail, Size, llvm::AtomicOrdering::AcquireRelease,
1426 Scope);
1427 break;
1428 case llvm::AtomicOrderingCABI::seq_cst:
1429 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1430 OrderFail, Size,
1431 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
1432 break;
1433 }
1434 if (RValTy->isVoidType())
1435 return RValue::get(nullptr);
1436
1438 RValTy, E->getExprLoc());
1439 }
1440
1441 // Long case, when Order isn't obviously constant.
1442
1443 // Create all the relevant BB's
1444 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
1445 *ReleaseBB = nullptr, *AcqRelBB = nullptr,
1446 *SeqCstBB = nullptr;
1447 MonotonicBB = createBasicBlock("monotonic", CurFn);
1448 if (!IsStore)
1449 AcquireBB = createBasicBlock("acquire", CurFn);
1450 if (!IsLoad)
1451 ReleaseBB = createBasicBlock("release", CurFn);
1452 if (!IsLoad && !IsStore)
1453 AcqRelBB = createBasicBlock("acqrel", CurFn);
1454 SeqCstBB = createBasicBlock("seqcst", CurFn);
1455 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
1456
1457 // Create the switch for the split
1458 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
1459 // doesn't matter unless someone is crazy enough to use something that
1460 // doesn't fold to a constant for the ordering.
1461 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
1462 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
1463
1464 // Emit all the different atomics
1465 Builder.SetInsertPoint(MonotonicBB);
1466 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak, OrderFail,
1467 Size, llvm::AtomicOrdering::Monotonic, Scope);
1468 Builder.CreateBr(ContBB);
1469 if (!IsStore) {
1470 Builder.SetInsertPoint(AcquireBB);
1471 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1472 OrderFail, Size, llvm::AtomicOrdering::Acquire, Scope);
1473 Builder.CreateBr(ContBB);
1474 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
1475 AcquireBB);
1476 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
1477 AcquireBB);
1478 }
1479 if (!IsLoad) {
1480 Builder.SetInsertPoint(ReleaseBB);
1481 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1482 OrderFail, Size, llvm::AtomicOrdering::Release, Scope);
1483 Builder.CreateBr(ContBB);
1484 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::release),
1485 ReleaseBB);
1486 }
1487 if (!IsLoad && !IsStore) {
1488 Builder.SetInsertPoint(AcqRelBB);
1489 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1490 OrderFail, Size, llvm::AtomicOrdering::AcquireRelease, Scope);
1491 Builder.CreateBr(ContBB);
1492 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acq_rel),
1493 AcqRelBB);
1494 }
1495 Builder.SetInsertPoint(SeqCstBB);
1496 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak, OrderFail,
1497 Size, llvm::AtomicOrdering::SequentiallyConsistent, Scope);
1498 Builder.CreateBr(ContBB);
1499 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
1500 SeqCstBB);
1501
1502 // Cleanup and return
1503 Builder.SetInsertPoint(ContBB);
1504 if (RValTy->isVoidType())
1505 return RValue::get(nullptr);
1506
1507 assert(Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits());
1509 RValTy, E->getExprLoc());
1510}
1511
1512Address AtomicInfo::castToAtomicIntPointer(Address addr) const {
1513 llvm::IntegerType *ty =
1514 llvm::IntegerType::get(CGF.getLLVMContext(), AtomicSizeInBits);
1515 return addr.withElementType(ty);
1516}
1517
1518Address AtomicInfo::convertToAtomicIntPointer(Address Addr) const {
1519 llvm::Type *Ty = Addr.getElementType();
1520 uint64_t SourceSizeInBits = CGF.CGM.getDataLayout().getTypeSizeInBits(Ty);
1521 if (SourceSizeInBits != AtomicSizeInBits) {
1522 Address Tmp = CreateTempAlloca();
1524 Tmp.emitRawPointer(CGF), llvm::ConstantInt::get(CGF.Int8Ty, 0),
1525 CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits).getQuantity(),
1526 Tmp.getAlignment().getAsAlign());
1527
1528 CGF.Builder.CreateMemCpy(Tmp, Addr,
1529 std::min(AtomicSizeInBits, SourceSizeInBits) / 8);
1530 Addr = Tmp;
1531 }
1532
1533 return castToAtomicIntPointer(Addr);
1534}
1535
1536RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
1537 AggValueSlot resultSlot,
1538 SourceLocation loc,
1539 bool asValue) const {
1540 if (LVal.isSimple()) {
1541 if (EvaluationKind == TEK_Aggregate)
1542 return resultSlot.asRValue();
1543
1544 // Drill into the padding structure if we have one.
1545 if (hasPadding())
1546 addr = CGF.Builder.CreateStructGEP(addr, 0);
1547
1548 // Otherwise, just convert the temporary to an r-value using the
1549 // normal conversion routine.
1550 return CGF.convertTempToRValue(addr, getValueType(), loc);
1551 }
1552 if (!asValue)
1553 // Get RValue from temp memory as atomic for non-simple lvalues
1554 return RValue::get(CGF.Builder.CreateLoad(addr));
1555 if (LVal.isBitField())
1556 return CGF.EmitLoadOfBitfieldLValue(
1557 LValue::MakeBitfield(addr, LVal.getBitFieldInfo(), LVal.getType(),
1558 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
1559 if (LVal.isVectorElt())
1560 return CGF.EmitLoadOfLValue(
1561 LValue::MakeVectorElt(addr, LVal.getVectorIdx(), LVal.getType(),
1562 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
1563 assert(LVal.isExtVectorElt());
1564 return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
1565 addr, LVal.getExtVectorElts(), LVal.getType(),
1566 LVal.getBaseInfo(), TBAAAccessInfo()));
1567}
1568
1569RValue AtomicInfo::ConvertToValueOrAtomic(llvm::Value *Val,
1570 AggValueSlot ResultSlot,
1571 SourceLocation Loc, bool AsValue,
1572 bool CmpXchg) const {
1573 // Try not to in some easy cases.
1574 assert((Val->getType()->isIntegerTy() || Val->getType()->isPointerTy() ||
1575 Val->getType()->isIEEELikeFPTy()) &&
1576 "Expected integer, pointer or floating point value when converting "
1577 "result.");
1578 if (getEvaluationKind() == TEK_Scalar &&
1579 (((!LVal.isBitField() ||
1580 LVal.getBitFieldInfo().Size == ValueSizeInBits) &&
1581 !hasPadding()) ||
1582 !AsValue)) {
1583 auto *ValTy = AsValue
1584 ? CGF.ConvertTypeForMem(ValueTy)
1585 : getAtomicAddress().getElementType();
1586 if (!shouldCastToInt(ValTy, CmpXchg)) {
1587 assert((!ValTy->isIntegerTy() || Val->getType() == ValTy) &&
1588 "Different integer types.");
1589 return RValue::get(CGF.EmitFromMemory(Val, ValueTy));
1590 }
1591 if (llvm::CastInst::isBitCastable(Val->getType(), ValTy))
1592 return RValue::get(CGF.Builder.CreateBitCast(Val, ValTy));
1593 }
1594
1595 // Create a temporary. This needs to be big enough to hold the
1596 // atomic integer.
1597 Address Temp = Address::invalid();
1598 bool TempIsVolatile = false;
1599 if (AsValue && getEvaluationKind() == TEK_Aggregate) {
1600 assert(!ResultSlot.isIgnored());
1601 Temp = ResultSlot.getAddress();
1602 TempIsVolatile = ResultSlot.isVolatile();
1603 } else {
1604 Temp = CreateTempAlloca();
1605 }
1606
1607 // Slam the integer into the temporary.
1608 Address CastTemp = castToAtomicIntPointer(Temp);
1609 CGF.Builder.CreateStore(Val, CastTemp)->setVolatile(TempIsVolatile);
1610
1611 return convertAtomicTempToRValue(Temp, ResultSlot, Loc, AsValue);
1612}
1613
1614void AtomicInfo::EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
1615 llvm::AtomicOrdering AO, bool) {
1616 // void __atomic_load(size_t size, void *mem, void *return, int order);
1617 CallArgList Args;
1618 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
1619 Args.add(RValue::get(getAtomicPointer()), CGF.getContext().VoidPtrTy);
1620 Args.add(RValue::get(AddForLoaded), CGF.getContext().VoidPtrTy);
1621 Args.add(
1622 RValue::get(llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(AO))),
1623 CGF.getContext().IntTy);
1624 emitAtomicLibcall(CGF, "__atomic_load", CGF.getContext().VoidTy, Args);
1625}
1626
1627llvm::Value *AtomicInfo::EmitAtomicLoadOp(llvm::AtomicOrdering AO,
1628 bool IsVolatile, bool CmpXchg) {
1629 // Okay, we're doing this natively.
1630 Address Addr = getAtomicAddress();
1631 if (shouldCastToInt(Addr.getElementType(), CmpXchg))
1632 Addr = castToAtomicIntPointer(Addr);
1633 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Addr, "atomic-load");
1634 Load->setAtomic(AO);
1635 CGF.getTargetHooks().setTargetAtomicMetadata(CGF, *Load);
1636
1637 // Other decoration.
1638 if (IsVolatile)
1639 Load->setVolatile(true);
1640 CGF.CGM.DecorateInstructionWithTBAA(Load, LVal.getTBAAInfo());
1641 return Load;
1642}
1643
1644/// An LValue is a candidate for having its loads and stores be made atomic if
1645/// we are operating under /volatile:ms *and* the LValue itself is volatile and
1646/// performing such an operation can be performed without a libcall.
1648 if (!CGM.getLangOpts().MSVolatile) return false;
1649 AtomicInfo AI(*this, LV);
1650 bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
1651 // An atomic is inline if we don't need to use a libcall.
1652 bool AtomicIsInline = !AI.shouldUseLibcall();
1653 // MSVC doesn't seem to do this for types wider than a pointer.
1654 if (getContext().getTypeSize(LV.getType()) >
1655 getContext().getTypeSize(getContext().getIntPtrType()))
1656 return false;
1657 return IsVolatile && AtomicIsInline;
1658}
1659
1661 AggValueSlot Slot) {
1662 llvm::AtomicOrdering AO;
1663 bool IsVolatile = LV.isVolatileQualified();
1664 if (LV.getType()->isAtomicType()) {
1665 AO = llvm::AtomicOrdering::SequentiallyConsistent;
1666 } else {
1667 AO = llvm::AtomicOrdering::Acquire;
1668 IsVolatile = true;
1669 }
1670 return EmitAtomicLoad(LV, SL, AO, IsVolatile, Slot);
1671}
1672
1673RValue AtomicInfo::EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
1674 bool AsValue, llvm::AtomicOrdering AO,
1675 bool IsVolatile) {
1676 // Check whether we should use a library call.
1677 if (shouldUseLibcall()) {
1678 Address TempAddr = Address::invalid();
1679 if (LVal.isSimple() && !ResultSlot.isIgnored()) {
1680 assert(getEvaluationKind() == TEK_Aggregate);
1681 TempAddr = ResultSlot.getAddress();
1682 } else
1683 TempAddr = CreateTempAlloca();
1684
1685 EmitAtomicLoadLibcall(TempAddr.emitRawPointer(CGF), AO, IsVolatile);
1686
1687 // Okay, turn that back into the original value or whole atomic (for
1688 // non-simple lvalues) type.
1689 return convertAtomicTempToRValue(TempAddr, ResultSlot, Loc, AsValue);
1690 }
1691
1692 // Okay, we're doing this natively.
1693 auto *Load = EmitAtomicLoadOp(AO, IsVolatile);
1694
1695 // If we're ignoring an aggregate return, don't do anything.
1696 if (getEvaluationKind() == TEK_Aggregate && ResultSlot.isIgnored())
1697 return RValue::getAggregate(Address::invalid(), false);
1698
1699 // Okay, turn that back into the original value or atomic (for non-simple
1700 // lvalues) type.
1701 return ConvertToValueOrAtomic(Load, ResultSlot, Loc, AsValue);
1702}
1703
1704/// Emit a load from an l-value of atomic type. Note that the r-value
1705/// we produce is an r-value of the atomic *value* type.
1707 llvm::AtomicOrdering AO, bool IsVolatile,
1708 AggValueSlot resultSlot) {
1709 AtomicInfo Atomics(*this, src);
1710 return Atomics.EmitAtomicLoad(resultSlot, loc, /*AsValue=*/true, AO,
1711 IsVolatile);
1712}
1713
1714/// Copy an r-value into memory as part of storing to an atomic type.
1715/// This needs to create a bit-pattern suitable for atomic operations.
1716void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
1717 assert(LVal.isSimple());
1718 // If we have an r-value, the rvalue should be of the atomic type,
1719 // which means that the caller is responsible for having zeroed
1720 // any padding. Just do an aggregate copy of that type.
1721 if (rvalue.isAggregate()) {
1722 LValue Dest = CGF.MakeAddrLValue(getAtomicAddress(), getAtomicType());
1723 LValue Src = CGF.MakeAddrLValue(rvalue.getAggregateAddress(),
1724 getAtomicType());
1725 bool IsVolatile = rvalue.isVolatileQualified() ||
1726 LVal.isVolatileQualified();
1727 CGF.EmitAggregateCopy(Dest, Src, getAtomicType(),
1728 AggValueSlot::DoesNotOverlap, IsVolatile);
1729 return;
1730 }
1731
1732 // Okay, otherwise we're copying stuff.
1733
1734 // Zero out the buffer if necessary.
1735 emitMemSetZeroIfNecessary();
1736
1737 // Drill past the padding if present.
1738 LValue TempLVal = projectValue();
1739
1740 // Okay, store the rvalue in.
1741 if (rvalue.isScalar()) {
1742 CGF.EmitStoreOfScalar(rvalue.getScalarVal(), TempLVal, /*init*/ true);
1743 } else {
1744 CGF.EmitStoreOfComplex(rvalue.getComplexVal(), TempLVal, /*init*/ true);
1745 }
1746}
1747
1748
1749/// Materialize an r-value into memory for the purposes of storing it
1750/// to an atomic type.
1751Address AtomicInfo::materializeRValue(RValue rvalue) const {
1752 // Aggregate r-values are already in memory, and EmitAtomicStore
1753 // requires them to be values of the atomic type.
1754 if (rvalue.isAggregate())
1755 return rvalue.getAggregateAddress();
1756
1757 // Otherwise, make a temporary and materialize into it.
1758 LValue TempLV = CGF.MakeAddrLValue(CreateTempAlloca(), getAtomicType());
1759 AtomicInfo Atomics(CGF, TempLV);
1760 Atomics.emitCopyIntoMemory(rvalue);
1761 return TempLV.getAddress();
1762}
1763
1764llvm::Value *AtomicInfo::getScalarRValValueOrNull(RValue RVal) const {
1765 if (RVal.isScalar() && (!hasPadding() || !LVal.isSimple()))
1766 return RVal.getScalarVal();
1767 return nullptr;
1768}
1769
1770llvm::Value *AtomicInfo::convertRValueToInt(RValue RVal, bool CmpXchg) const {
1771 // If we've got a scalar value of the right size, try to avoid going
1772 // through memory. Floats get casted if needed by AtomicExpandPass.
1773 if (llvm::Value *Value = getScalarRValValueOrNull(RVal)) {
1774 if (!shouldCastToInt(Value->getType(), CmpXchg))
1775 return CGF.EmitToMemory(Value, ValueTy);
1776 else {
1777 llvm::IntegerType *InputIntTy = llvm::IntegerType::get(
1778 CGF.getLLVMContext(),
1779 LVal.isSimple() ? getValueSizeInBits() : getAtomicSizeInBits());
1780 if (llvm::BitCastInst::isBitCastable(Value->getType(), InputIntTy))
1781 return CGF.Builder.CreateBitCast(Value, InputIntTy);
1782 }
1783 }
1784 // Otherwise, we need to go through memory.
1785 // Put the r-value in memory.
1786 Address Addr = materializeRValue(RVal);
1787
1788 // Cast the temporary to the atomic int type and pull a value out.
1789 Addr = castToAtomicIntPointer(Addr);
1790 return CGF.Builder.CreateLoad(Addr);
1791}
1792
1793std::pair<llvm::Value *, llvm::Value *> AtomicInfo::EmitAtomicCompareExchangeOp(
1794 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
1795 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak) {
1796 // Do the atomic store.
1797 Address Addr = getAtomicAddressAsAtomicIntPointer();
1798 auto *Inst = CGF.Builder.CreateAtomicCmpXchg(Addr, ExpectedVal, DesiredVal,
1799 Success, Failure);
1800 // Other decoration.
1801 Inst->setVolatile(LVal.isVolatileQualified());
1802 Inst->setWeak(IsWeak);
1803 CGF.getTargetHooks().setTargetAtomicMetadata(CGF, *Inst);
1804
1805 // Okay, turn that back into the original value type.
1806 auto *PreviousVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/0);
1807 auto *SuccessFailureVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/1);
1808 return std::make_pair(PreviousVal, SuccessFailureVal);
1809}
1810
1811llvm::Value *
1812AtomicInfo::EmitAtomicCompareExchangeLibcall(llvm::Value *ExpectedAddr,
1813 llvm::Value *DesiredAddr,
1814 llvm::AtomicOrdering Success,
1815 llvm::AtomicOrdering Failure) {
1816 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
1817 // void *desired, int success, int failure);
1818 CallArgList Args;
1819 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
1820 Args.add(RValue::get(getAtomicPointer()), CGF.getContext().VoidPtrTy);
1821 Args.add(RValue::get(ExpectedAddr), CGF.getContext().VoidPtrTy);
1822 Args.add(RValue::get(DesiredAddr), CGF.getContext().VoidPtrTy);
1823 Args.add(RValue::get(
1824 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Success))),
1825 CGF.getContext().IntTy);
1826 Args.add(RValue::get(
1827 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Failure))),
1828 CGF.getContext().IntTy);
1829 auto SuccessFailureRVal = emitAtomicLibcall(CGF, "__atomic_compare_exchange",
1830 CGF.getContext().BoolTy, Args);
1831
1832 return SuccessFailureRVal.getScalarVal();
1833}
1834
1835std::pair<RValue, llvm::Value *> AtomicInfo::EmitAtomicCompareExchange(
1836 RValue Expected, RValue Desired, llvm::AtomicOrdering Success,
1837 llvm::AtomicOrdering Failure, bool IsWeak) {
1838 // Check whether we should use a library call.
1839 if (shouldUseLibcall()) {
1840 // Produce a source address.
1841 Address ExpectedAddr = materializeRValue(Expected);
1842 llvm::Value *ExpectedPtr = ExpectedAddr.emitRawPointer(CGF);
1843 llvm::Value *DesiredPtr = materializeRValue(Desired).emitRawPointer(CGF);
1844 auto *Res = EmitAtomicCompareExchangeLibcall(ExpectedPtr, DesiredPtr,
1845 Success, Failure);
1846 return std::make_pair(
1847 convertAtomicTempToRValue(ExpectedAddr, AggValueSlot::ignored(),
1848 SourceLocation(), /*AsValue=*/false),
1849 Res);
1850 }
1851
1852 // If we've got a scalar value of the right size, try to avoid going
1853 // through memory.
1854 auto *ExpectedVal = convertRValueToInt(Expected, /*CmpXchg=*/true);
1855 auto *DesiredVal = convertRValueToInt(Desired, /*CmpXchg=*/true);
1856 auto Res = EmitAtomicCompareExchangeOp(ExpectedVal, DesiredVal, Success,
1857 Failure, IsWeak);
1858 return std::make_pair(
1859 ConvertToValueOrAtomic(Res.first, AggValueSlot::ignored(),
1860 SourceLocation(), /*AsValue=*/false,
1861 /*CmpXchg=*/true),
1862 Res.second);
1863}
1864
1865static void
1866EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal,
1867 const llvm::function_ref<RValue(RValue)> &UpdateOp,
1868 Address DesiredAddr) {
1869 RValue UpRVal;
1870 LValue AtomicLVal = Atomics.getAtomicLValue();
1871 LValue DesiredLVal;
1872 if (AtomicLVal.isSimple()) {
1873 UpRVal = OldRVal;
1874 DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
1875 } else {
1876 // Build new lvalue for temp address.
1877 Address Ptr = Atomics.materializeRValue(OldRVal);
1878 LValue UpdateLVal;
1879 if (AtomicLVal.isBitField()) {
1880 UpdateLVal =
1881 LValue::MakeBitfield(Ptr, AtomicLVal.getBitFieldInfo(),
1882 AtomicLVal.getType(),
1883 AtomicLVal.getBaseInfo(),
1884 AtomicLVal.getTBAAInfo());
1885 DesiredLVal =
1886 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
1887 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1888 AtomicLVal.getTBAAInfo());
1889 } else if (AtomicLVal.isVectorElt()) {
1890 UpdateLVal = LValue::MakeVectorElt(Ptr, AtomicLVal.getVectorIdx(),
1891 AtomicLVal.getType(),
1892 AtomicLVal.getBaseInfo(),
1893 AtomicLVal.getTBAAInfo());
1894 DesiredLVal = LValue::MakeVectorElt(
1895 DesiredAddr, AtomicLVal.getVectorIdx(), AtomicLVal.getType(),
1896 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1897 } else {
1898 assert(AtomicLVal.isExtVectorElt());
1899 UpdateLVal = LValue::MakeExtVectorElt(Ptr, AtomicLVal.getExtVectorElts(),
1900 AtomicLVal.getType(),
1901 AtomicLVal.getBaseInfo(),
1902 AtomicLVal.getTBAAInfo());
1903 DesiredLVal = LValue::MakeExtVectorElt(
1904 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
1905 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1906 }
1907 UpRVal = CGF.EmitLoadOfLValue(UpdateLVal, SourceLocation());
1908 }
1909 // Store new value in the corresponding memory area.
1910 RValue NewRVal = UpdateOp(UpRVal);
1911 if (NewRVal.isScalar()) {
1912 CGF.EmitStoreThroughLValue(NewRVal, DesiredLVal);
1913 } else {
1914 assert(NewRVal.isComplex());
1915 CGF.EmitStoreOfComplex(NewRVal.getComplexVal(), DesiredLVal,
1916 /*isInit=*/false);
1917 }
1918}
1919
1920void AtomicInfo::EmitAtomicUpdateLibcall(
1921 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1922 bool IsVolatile) {
1923 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1924
1925 Address ExpectedAddr = CreateTempAlloca();
1926
1927 EmitAtomicLoadLibcall(ExpectedAddr.emitRawPointer(CGF), AO, IsVolatile);
1928 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1929 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1930 CGF.EmitBlock(ContBB);
1931 Address DesiredAddr = CreateTempAlloca();
1932 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1933 requiresMemSetZero(getAtomicAddress().getElementType())) {
1934 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1935 CGF.Builder.CreateStore(OldVal, DesiredAddr);
1936 }
1937 auto OldRVal = convertAtomicTempToRValue(ExpectedAddr,
1939 SourceLocation(), /*AsValue=*/false);
1940 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, DesiredAddr);
1941 llvm::Value *ExpectedPtr = ExpectedAddr.emitRawPointer(CGF);
1942 llvm::Value *DesiredPtr = DesiredAddr.emitRawPointer(CGF);
1943 auto *Res =
1944 EmitAtomicCompareExchangeLibcall(ExpectedPtr, DesiredPtr, AO, Failure);
1945 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1946 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1947}
1948
1949void AtomicInfo::EmitAtomicUpdateOp(
1950 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1951 bool IsVolatile) {
1952 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1953
1954 // Do the atomic load.
1955 auto *OldVal = EmitAtomicLoadOp(Failure, IsVolatile, /*CmpXchg=*/true);
1956 // For non-simple lvalues perform compare-and-swap procedure.
1957 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1958 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1959 auto *CurBB = CGF.Builder.GetInsertBlock();
1960 CGF.EmitBlock(ContBB);
1961 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1962 /*NumReservedValues=*/2);
1963 PHI->addIncoming(OldVal, CurBB);
1964 Address NewAtomicAddr = CreateTempAlloca();
1965 Address NewAtomicIntAddr =
1966 shouldCastToInt(NewAtomicAddr.getElementType(), /*CmpXchg=*/true)
1967 ? castToAtomicIntPointer(NewAtomicAddr)
1968 : NewAtomicAddr;
1969
1970 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1971 requiresMemSetZero(getAtomicAddress().getElementType())) {
1972 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
1973 }
1974 auto OldRVal = ConvertToValueOrAtomic(PHI, AggValueSlot::ignored(),
1975 SourceLocation(), /*AsValue=*/false,
1976 /*CmpXchg=*/true);
1977 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, NewAtomicAddr);
1978 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
1979 // Try to write new value using cmpxchg operation.
1980 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1981 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1982 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1983 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1984}
1985
1986static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics,
1987 RValue UpdateRVal, Address DesiredAddr) {
1988 LValue AtomicLVal = Atomics.getAtomicLValue();
1989 LValue DesiredLVal;
1990 // Build new lvalue for temp address.
1991 if (AtomicLVal.isBitField()) {
1992 DesiredLVal =
1993 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
1994 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1995 AtomicLVal.getTBAAInfo());
1996 } else if (AtomicLVal.isVectorElt()) {
1997 DesiredLVal =
1998 LValue::MakeVectorElt(DesiredAddr, AtomicLVal.getVectorIdx(),
1999 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
2000 AtomicLVal.getTBAAInfo());
2001 } else {
2002 assert(AtomicLVal.isExtVectorElt());
2003 DesiredLVal = LValue::MakeExtVectorElt(
2004 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
2005 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
2006 }
2007 // Store new value in the corresponding memory area.
2008 assert(UpdateRVal.isScalar());
2009 CGF.EmitStoreThroughLValue(UpdateRVal, DesiredLVal);
2010}
2011
2012void AtomicInfo::EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
2013 RValue UpdateRVal, bool IsVolatile) {
2014 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
2015
2016 Address ExpectedAddr = CreateTempAlloca();
2017
2018 EmitAtomicLoadLibcall(ExpectedAddr.emitRawPointer(CGF), AO, IsVolatile);
2019 auto *ContBB = CGF.createBasicBlock("atomic_cont");
2020 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
2021 CGF.EmitBlock(ContBB);
2022 Address DesiredAddr = CreateTempAlloca();
2023 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
2024 requiresMemSetZero(getAtomicAddress().getElementType())) {
2025 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
2026 CGF.Builder.CreateStore(OldVal, DesiredAddr);
2027 }
2028 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, DesiredAddr);
2029 llvm::Value *ExpectedPtr = ExpectedAddr.emitRawPointer(CGF);
2030 llvm::Value *DesiredPtr = DesiredAddr.emitRawPointer(CGF);
2031 auto *Res =
2032 EmitAtomicCompareExchangeLibcall(ExpectedPtr, DesiredPtr, AO, Failure);
2033 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
2034 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2035}
2036
2037void AtomicInfo::EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRVal,
2038 bool IsVolatile) {
2039 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
2040
2041 // Do the atomic load.
2042 auto *OldVal = EmitAtomicLoadOp(Failure, IsVolatile, /*CmpXchg=*/true);
2043 // For non-simple lvalues perform compare-and-swap procedure.
2044 auto *ContBB = CGF.createBasicBlock("atomic_cont");
2045 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
2046 auto *CurBB = CGF.Builder.GetInsertBlock();
2047 CGF.EmitBlock(ContBB);
2048 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
2049 /*NumReservedValues=*/2);
2050 PHI->addIncoming(OldVal, CurBB);
2051 Address NewAtomicAddr = CreateTempAlloca();
2052 Address NewAtomicIntAddr = castToAtomicIntPointer(NewAtomicAddr);
2053 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
2054 requiresMemSetZero(getAtomicAddress().getElementType())) {
2055 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
2056 }
2057 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, NewAtomicAddr);
2058 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
2059 // Try to write new value using cmpxchg operation.
2060 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
2061 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
2062 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
2063 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2064}
2065
2066void AtomicInfo::EmitAtomicUpdate(
2067 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
2068 bool IsVolatile) {
2069 if (shouldUseLibcall()) {
2070 EmitAtomicUpdateLibcall(AO, UpdateOp, IsVolatile);
2071 } else {
2072 EmitAtomicUpdateOp(AO, UpdateOp, IsVolatile);
2073 }
2074}
2075
2076void AtomicInfo::EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
2077 bool IsVolatile) {
2078 if (shouldUseLibcall()) {
2079 EmitAtomicUpdateLibcall(AO, UpdateRVal, IsVolatile);
2080 } else {
2081 EmitAtomicUpdateOp(AO, UpdateRVal, IsVolatile);
2082 }
2083}
2084
2086 bool isInit) {
2087 bool IsVolatile = lvalue.isVolatileQualified();
2088 llvm::AtomicOrdering AO;
2089 if (lvalue.getType()->isAtomicType()) {
2090 AO = llvm::AtomicOrdering::SequentiallyConsistent;
2091 } else {
2092 AO = llvm::AtomicOrdering::Release;
2093 IsVolatile = true;
2094 }
2095 return EmitAtomicStore(rvalue, lvalue, AO, IsVolatile, isInit);
2096}
2097
2098/// Emit a store to an l-value of atomic type.
2099///
2100/// Note that the r-value is expected to be an r-value *of the atomic
2101/// type*; this means that for aggregate r-values, it should include
2102/// storage for any padding that was necessary.
2104 llvm::AtomicOrdering AO, bool IsVolatile,
2105 bool isInit) {
2106 // If this is an aggregate r-value, it should agree in type except
2107 // maybe for address-space qualification.
2108 assert(!rvalue.isAggregate() ||
2110 dest.getAddress().getElementType());
2111
2112 AtomicInfo atomics(*this, dest);
2113 LValue LVal = atomics.getAtomicLValue();
2114
2115 // If this is an initialization, just put the value there normally.
2116 if (LVal.isSimple()) {
2117 if (isInit) {
2118 atomics.emitCopyIntoMemory(rvalue);
2119 return;
2120 }
2121
2122 // Check whether we should use a library call.
2123 if (atomics.shouldUseLibcall()) {
2124 // Produce a source address.
2125 Address srcAddr = atomics.materializeRValue(rvalue);
2126
2127 // void __atomic_store(size_t size, void *mem, void *val, int order)
2128 CallArgList args;
2129 args.add(RValue::get(atomics.getAtomicSizeValue()),
2130 getContext().getSizeType());
2131 args.add(RValue::get(atomics.getAtomicPointer()), getContext().VoidPtrTy);
2132 args.add(RValue::get(srcAddr.emitRawPointer(*this)),
2134 args.add(
2135 RValue::get(llvm::ConstantInt::get(IntTy, (int)llvm::toCABI(AO))),
2136 getContext().IntTy);
2137 emitAtomicLibcall(*this, "__atomic_store", getContext().VoidTy, args);
2138 return;
2139 }
2140
2141 // Okay, we're doing this natively.
2142 llvm::Value *ValToStore = atomics.convertRValueToInt(rvalue);
2143
2144 // Do the atomic store.
2145 Address Addr = atomics.getAtomicAddress();
2146 if (llvm::Value *Value = atomics.getScalarRValValueOrNull(rvalue))
2147 if (shouldCastToInt(Value->getType(), /*CmpXchg=*/false)) {
2148 Addr = atomics.castToAtomicIntPointer(Addr);
2149 ValToStore = Builder.CreateIntCast(ValToStore, Addr.getElementType(),
2150 /*isSigned=*/false);
2151 }
2152 llvm::StoreInst *store = Builder.CreateStore(ValToStore, Addr);
2153
2154 if (AO == llvm::AtomicOrdering::Acquire)
2155 AO = llvm::AtomicOrdering::Monotonic;
2156 else if (AO == llvm::AtomicOrdering::AcquireRelease)
2157 AO = llvm::AtomicOrdering::Release;
2158 // Initializations don't need to be atomic.
2159 if (!isInit) {
2160 store->setAtomic(AO);
2161 getTargetHooks().setTargetAtomicMetadata(*this, *store);
2162 }
2163
2164 // Other decoration.
2165 if (IsVolatile)
2166 store->setVolatile(true);
2167 CGM.DecorateInstructionWithTBAA(store, dest.getTBAAInfo());
2168 return;
2169 }
2170
2171 // Emit simple atomic update operation.
2172 atomics.EmitAtomicUpdate(AO, rvalue, IsVolatile);
2173}
2174
2175/// Emit a compare-and-exchange op for atomic type.
2176///
2177std::pair<RValue, llvm::Value *> CodeGenFunction::EmitAtomicCompareExchange(
2178 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2179 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak,
2180 AggValueSlot Slot) {
2181 // If this is an aggregate r-value, it should agree in type except
2182 // maybe for address-space qualification.
2183 assert(!Expected.isAggregate() ||
2184 Expected.getAggregateAddress().getElementType() ==
2185 Obj.getAddress().getElementType());
2186 assert(!Desired.isAggregate() ||
2187 Desired.getAggregateAddress().getElementType() ==
2188 Obj.getAddress().getElementType());
2189 AtomicInfo Atomics(*this, Obj);
2190
2191 return Atomics.EmitAtomicCompareExchange(Expected, Desired, Success, Failure,
2192 IsWeak);
2193}
2194
2195llvm::AtomicRMWInst *
2196CodeGenFunction::emitAtomicRMWInst(llvm::AtomicRMWInst::BinOp Op, Address Addr,
2197 llvm::Value *Val, llvm::AtomicOrdering Order,
2198 llvm::SyncScope::ID SSID,
2199 const AtomicExpr *AE) {
2200 llvm::AtomicRMWInst *RMW =
2201 Builder.CreateAtomicRMW(Op, Addr, Val, Order, SSID);
2202 getTargetHooks().setTargetAtomicMetadata(*this, *RMW, AE);
2203 return RMW;
2204}
2205
2206llvm::FenceInst *CodeGenFunction::emitAtomicFence(llvm::AtomicOrdering Order,
2207 llvm::SyncScope::ID SSID) {
2208 llvm::FenceInst *Fence = Builder.CreateFence(Order, SSID);
2209 getTargetHooks().setTargetAtomicMetadata(*this, *Fence);
2210 return Fence;
2211}
2212
2214 LValue LVal, llvm::AtomicOrdering AO,
2215 const llvm::function_ref<RValue(RValue)> &UpdateOp, bool IsVolatile) {
2216 AtomicInfo Atomics(*this, LVal);
2217 Atomics.EmitAtomicUpdate(AO, UpdateOp, IsVolatile);
2218}
2219
2221 AtomicInfo atomics(*this, dest);
2222
2223 switch (atomics.getEvaluationKind()) {
2224 case TEK_Scalar: {
2225 llvm::Value *value = EmitScalarExpr(init);
2226 atomics.emitCopyIntoMemory(RValue::get(value));
2227 return;
2228 }
2229
2230 case TEK_Complex: {
2231 ComplexPairTy value = EmitComplexExpr(init);
2232 atomics.emitCopyIntoMemory(RValue::getComplex(value));
2233 return;
2234 }
2235
2236 case TEK_Aggregate: {
2237 // Fix up the destination if the initializer isn't an expression
2238 // of atomic type.
2239 bool Zeroed = false;
2240 if (!init->getType()->isAtomicType()) {
2241 Zeroed = atomics.emitMemSetZeroIfNecessary();
2242 dest = atomics.projectValue();
2243 }
2244
2245 // Evaluate the expression directly into the destination.
2251
2252 EmitAggExpr(init, slot);
2253 return;
2254 }
2255 }
2256 llvm_unreachable("bad evaluation kind");
2257}
Defines the clang::ASTContext interface.
#define V(N, I)
static llvm::Value * EmitPostAtomicMinMax(CGBuilderTy &Builder, AtomicExpr::AtomicOp Op, bool IsSigned, llvm::Value *OldVal, llvm::Value *RHS)
Duplicate the atomic min/max operation in conventional IR for the builtin variants that return the ne...
Definition CGAtomic.cpp:527
static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal, const llvm::function_ref< RValue(RValue)> &UpdateOp, Address DesiredAddr)
static Address EmitValToTemp(CodeGenFunction &CGF, Expr *E)
Definition CGAtomic.cpp:858
static RValue emitAtomicLibcall(CodeGenFunction &CGF, StringRef fnName, QualType resultType, CallArgList &args)
Definition CGAtomic.cpp:316
static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest, Address Ptr, Address Val1, Address Val2, Address ExpectedResult, llvm::Value *IsWeak, llvm::Value *FailureOrder, uint64_t Size, llvm::AtomicOrdering Order, llvm::SyncScope::ID Scope)
Definition CGAtomic.cpp:560
static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo, KnownNonNull_t IsKnownNonNull, CodeGenFunction &CGF)
Definition CGExpr.cpp:1482
static bool shouldCastToInt(mlir::Type valueTy, bool cmpxchg)
Return true if.
static void emitAtomicCmpXchg(CIRGenFunction &cgf, AtomicExpr *e, bool isWeak, Address dest, Address ptr, Address val1, Address val2, uint64_t size, cir::MemOrder successOrder, cir::MemOrder failureOrder, cir::SyncScopeKind scope)
static bool isFullSizeType(CIRGenModule &cgm, mlir::Type ty, uint64_t expectedSize)
Does a store of the given IR type modify the full expected width?
static void emitAtomicCmpXchgFailureSet(CIRGenFunction &cgf, AtomicExpr *e, bool isWeak, Address dest, Address ptr, Address val1, Address val2, Expr *failureOrderExpr, uint64_t size, cir::MemOrder successOrder, cir::SyncScopeKind scope)
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
static QualType getPointeeType(const MemRegion *R)
CanQualType VoidPtrTy
CanQualType BoolTy
CanQualType IntTy
CanQualType VoidTy
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6940
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7089
Expr * getVal2() const
Definition Expr.h:6991
Expr * getOrder() const
Definition Expr.h:6974
QualType getValueType() const
Definition Expr.cpp:5399
Expr * getScope() const
Definition Expr.h:6977
bool isCmpXChg() const
Definition Expr.h:7024
AtomicOp getOp() const
Definition Expr.h:7003
bool isOpenCL() const
Definition Expr.h:7052
Expr * getVal1() const
Definition Expr.h:6981
Expr * getPtr() const
Definition Expr.h:6971
Expr * getWeak() const
Definition Expr.h:6997
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7071
Expr * getOrderFail() const
Definition Expr.h:6987
bool isVolatile() const
Definition Expr.h:7020
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
bool isMultipleOf(CharUnits N) const
Test whether this is a multiple of the other value.
Definition CharUnits.h:143
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
static Address invalid()
Definition Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
bool isValid() const
Definition Address.h:177
An aggregate value slot.
Definition CGValue.h:551
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition CGValue.h:619
Address getAddress() const
Definition CGValue.h:691
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
Definition CGValue.h:649
RValue asRValue() const
Definition CGValue.h:713
A scoped helper to set the current source atom group for CGDebugInfo::addInstToCurrentSourceAtom.
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:146
Address CreatePointerBitCastOrAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition CGBuilder.h:213
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Definition CGBuilder.h:430
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition CGBuilder.h:229
llvm::AtomicCmpXchgInst * CreateAtomicCmpXchg(Address Addr, llvm::Value *Cmp, llvm::Value *New, llvm::AtomicOrdering SuccessOrdering, llvm::AtomicOrdering FailureOrdering, llvm::SyncScope::ID SSID=llvm::SyncScope::System)
Definition CGBuilder.h:179
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:118
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition CGBuilder.h:397
Address CreateAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition CGBuilder.h:199
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:139
CGFunctionInfo - Class to encapsulate the information about a function definition.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition CGCall.h:276
void add(RValue rvalue, QualType type)
Definition CGCall.h:304
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
void EmitAtomicInit(Expr *E, LValue lvalue)
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Given the address of a temporary variable, produce an r-value of its type.
Definition CGExpr.cpp:7242
bool hasVolatileMember(QualType T)
hasVolatileMember - returns true if aggregate type has a volatile member.
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
See CGDebugInfo::addInstToCurrentSourceAtom.
const LangOptions & getLangOpts() const
void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO, const llvm::function_ref< RValue(RValue)> &UpdateOp, bool IsVolatile)
std::pair< RValue, llvm::Value * > EmitAtomicCompareExchange(LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc, llvm::AtomicOrdering Success=llvm::AtomicOrdering::SequentiallyConsistent, llvm::AtomicOrdering Failure=llvm::AtomicOrdering::SequentiallyConsistent, bool IsWeak=false, AggValueSlot Slot=AggValueSlot::ignored())
Emit a compare-and-exchange op for atomic type.
void maybeAttachRangeForLoad(llvm::LoadInst *Load, QualType Ty, SourceLocation Loc)
Definition CGExpr.cpp:2125
void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, AggValueSlot::Overlap_t MayOverlap, bool isVolatile=false)
EmitAggregateCopy - Emit an aggregate copy.
const TargetInfo & getTarget() const
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2542
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
llvm::Value * EmitToMemory(llvm::Value *Value, QualType Ty)
EmitToMemory - Change a scalar value from its value representation to its in-memory representation.
Definition CGExpr.cpp:2267
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition CGExpr.cpp:160
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5640
const TargetCodeGenInfo & getTargetHooks() const
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:232
llvm::FenceInst * emitAtomicFence(llvm::AtomicOrdering Order, llvm::SyncScope::ID SSID=llvm::SyncScope::System)
Emit a fence instruction, applying relevant target-specific metadata when applicable.
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition CGExpr.cpp:2793
llvm::AtomicRMWInst * emitAtomicRMWInst(llvm::AtomicRMWInst::BinOp Op, Address Addr, llvm::Value *Val, llvm::AtomicOrdering Order=llvm::AtomicOrdering::SequentiallyConsistent, llvm::SyncScope::ID SSID=llvm::SyncScope::System, const AtomicExpr *AE=nullptr)
Emit an atomicrmw instruction, and applying relevant metadata when applicable.
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
Definition CGExpr.cpp:310
llvm::Type * ConvertTypeForMem(QualType T)
RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc)
Definition CGExpr.cpp:2656
RValue EmitAtomicExpr(AtomicExpr *E)
Definition CGAtomic.cpp:944
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
bool LValueIsSuitableForInlineAtomic(LValue Src)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
RValue EmitLoadOfExtVectorElementLValue(LValue V)
Definition CGExpr.cpp:2693
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
Definition CGExpr.cpp:2301
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
llvm::LLVMContext & getLLVMContext()
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:651
This class organizes the cross-function state that is used while generating LLVM code.
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
const LangOptions & getLangOpts() const
const llvm::DataLayout & getDataLayout() const
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
llvm::LLVMContext & getLLVMContext()
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:2046
const CGFunctionInfo & arrangeBuiltinFunctionCall(QualType resultType, const CallArgList &args)
Definition CGCall.cpp:764
LValue - This represents an lvalue references.
Definition CGValue.h:183
bool isSimple() const
Definition CGValue.h:286
bool isVolatileQualified() const
Definition CGValue.h:297
bool isVolatile() const
Definition CGValue.h:340
Address getAddress() const
Definition CGValue.h:373
QualType getType() const
Definition CGValue.h:303
TBAAAccessInfo getTBAAInfo() const
Definition CGValue.h:347
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
bool isScalar() const
Definition CGValue.h:64
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition CGValue.h:126
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition CGValue.h:109
bool isAggregate() const
Definition CGValue.h:66
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition CGValue.h:84
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
bool isComplex() const
Definition CGValue.h:65
bool isVolatileQualified() const
Definition CGValue.h:69
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition CGValue.h:79
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition CGCall.h:383
llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, SyncScope Scope, llvm::AtomicOrdering Ordering, llvm::LLVMContext &Ctx) const
Get the syncscope used in LLVM IR as a SyncScope ID.
virtual void setTargetAtomicMetadata(CodeGenFunction &CGF, llvm::Instruction &AtomicInst, const AtomicExpr *Expr=nullptr) const
Allow the target to apply other metadata to an atomic instruction.
Definition TargetInfo.h:375
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
This represents one expression.
Definition Expr.h:112
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:144
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3405
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8627
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8541
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8595
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Encodes a location in the source.
bool isVoidType() const
Definition TypeBase.h:9110
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2270
bool isPointerType() const
Definition TypeBase.h:8738
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9404
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isAtomicType() const
Definition TypeBase.h:8930
bool isFloatingType() const
Definition Type.cpp:2393
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9337
QualType getType() const
Definition Value.cpp:238
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
bool Load(InterpState &S, CodePtr OpPC)
Definition Interp.h:2242
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Success
Annotation was successful.
Definition Parser.h:65
llvm::Expected< QualType > ExpectedType
llvm::StringRef getAsString(SyncScope S)
Definition SyncScope.h:63
U cast(CodeGen::Address addr)
Definition Address.h:327
unsigned long uint64_t
#define true
Definition stdbool.h:25
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Size
The total size of the bit-field, in bits.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64