clang 23.0.0git
CIRGenAtomic.cpp
Go to the documentation of this file.
1//===--- CIRGenAtomic.cpp - Emit CIR 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 "CIRGenFunction.h"
15
16using namespace clang;
17using namespace clang::CIRGen;
18using namespace cir;
19
20namespace {
21class AtomicInfo {
22 CIRGenFunction &cgf;
23 QualType atomicTy;
24 QualType valueTy;
25 uint64_t atomicSizeInBits = 0;
26 uint64_t valueSizeInBits = 0;
27 CharUnits atomicAlign;
28 CharUnits valueAlign;
29 TypeEvaluationKind evaluationKind = cir::TEK_Scalar;
30 bool useLibCall = true;
31 LValue lvalue;
32 mlir::Location loc;
33
34public:
35 AtomicInfo(CIRGenFunction &cgf, LValue &lvalue, mlir::Location loc)
36 : cgf(cgf), loc(loc) {
37 assert(!lvalue.isGlobalReg());
38 ASTContext &ctx = cgf.getContext();
39 if (lvalue.isSimple()) {
40 atomicTy = lvalue.getType();
41 if (auto *ty = atomicTy->getAs<AtomicType>())
42 valueTy = ty->getValueType();
43 else
44 valueTy = atomicTy;
45 evaluationKind = cgf.getEvaluationKind(valueTy);
46
47 TypeInfo valueTypeInfo = ctx.getTypeInfo(valueTy);
48 TypeInfo atomicTypeInfo = ctx.getTypeInfo(atomicTy);
49 uint64_t valueAlignInBits = valueTypeInfo.Align;
50 uint64_t atomicAlignInBits = atomicTypeInfo.Align;
51 valueSizeInBits = valueTypeInfo.Width;
52 atomicSizeInBits = atomicTypeInfo.Width;
53 assert(valueSizeInBits <= atomicSizeInBits);
54 assert(valueAlignInBits <= atomicAlignInBits);
55
56 atomicAlign = ctx.toCharUnitsFromBits(atomicAlignInBits);
57 valueAlign = ctx.toCharUnitsFromBits(valueAlignInBits);
58 if (lvalue.getAlignment().isZero())
59 lvalue.setAlignment(atomicAlign);
60
61 this->lvalue = lvalue;
62 } else {
64 cgf.cgm.errorNYI(loc, "AtomicInfo: non-simple lvalue");
65 }
66 useLibCall = !ctx.getTargetInfo().hasBuiltinAtomic(
67 atomicSizeInBits, ctx.toBits(lvalue.getAlignment()));
68 }
69
70 QualType getValueType() const { return valueTy; }
71 CharUnits getAtomicAlignment() const { return atomicAlign; }
72 TypeEvaluationKind getEvaluationKind() const { return evaluationKind; }
73 mlir::Value getAtomicPointer() const {
74 if (lvalue.isSimple())
75 return lvalue.getPointer();
77 return nullptr;
78 }
79 bool shouldUseLibCall() const { return useLibCall; }
80 const LValue &getAtomicLValue() const { return lvalue; }
81 Address getAtomicAddress() const {
82 mlir::Type elemTy;
83 if (lvalue.isSimple()) {
84 elemTy = lvalue.getAddress().getElementType();
85 } else {
87 cgf.cgm.errorNYI(loc, "AtomicInfo::getAtomicAddress: non-simple lvalue");
88 }
89 return Address(getAtomicPointer(), elemTy, getAtomicAlignment());
90 }
91
92 /// Is the atomic size larger than the underlying value type?
93 ///
94 /// Note that the absence of padding does not mean that atomic
95 /// objects are completely interchangeable with non-atomic
96 /// objects: we might have promoted the alignment of a type
97 /// without making it bigger.
98 bool hasPadding() const { return (valueSizeInBits != atomicSizeInBits); }
99
100 bool emitMemSetZeroIfNecessary() const;
101
102 mlir::Value getScalarRValValueOrNull(RValue rvalue) const;
103
104 /// Cast the given pointer to an integer pointer suitable for atomic
105 /// operations on the source.
106 Address castToAtomicIntPointer(Address addr) const;
107
108 /// If addr is compatible with the iN that will be used for an atomic
109 /// operation, bitcast it. Otherwise, create a temporary that is suitable and
110 /// copy the value across.
111 Address convertToAtomicIntPointer(Address addr) const;
112
113 /// Converts a rvalue to integer value.
114 mlir::Value convertRValueToInt(RValue rvalue, bool cmpxchg = false) const;
115
116 /// Copy an atomic r-value into atomic-layout memory.
117 void emitCopyIntoMemory(RValue rvalue) const;
118
119 /// Project an l-value down to the value field.
120 LValue projectValue() const {
121 assert(lvalue.isSimple());
122 Address addr = getAtomicAddress();
123 if (hasPadding()) {
124 cgf.cgm.errorNYI(loc, "AtomicInfo::projectValue: padding");
125 }
126
128 return LValue::makeAddr(addr, getValueType(), lvalue.getBaseInfo());
129 }
130
131 /// Creates temp alloca for intermediate operations on atomic value.
132 Address createTempAlloca() const;
133
134private:
135 bool requiresMemSetZero(mlir::Type ty) const;
136};
137} // namespace
138
139// This function emits any expression (scalar, complex, or aggregate)
140// into a temporary alloca.
142 Address declPtr = cgf.createMemTemp(
143 e->getType(), cgf.getLoc(e->getSourceRange()), ".atomictmp");
144 cgf.emitAnyExprToMem(e, declPtr, e->getType().getQualifiers(),
145 /*Init*/ true);
146 return declPtr;
147}
148
149/// Does a store of the given IR type modify the full expected width?
150static bool isFullSizeType(CIRGenModule &cgm, mlir::Type ty,
151 uint64_t expectedSize) {
152 return cgm.getDataLayout().getTypeStoreSize(ty) * 8 == expectedSize;
153}
154
155/// Does the atomic type require memsetting to zero before initialization?
156///
157/// The IR type is provided as a way of making certain queries faster.
158bool AtomicInfo::requiresMemSetZero(mlir::Type ty) const {
159 // If the atomic type has size padding, we definitely need a memset.
160 if (hasPadding())
161 return true;
162
163 // Otherwise, do some simple heuristics to try to avoid it:
164 switch (getEvaluationKind()) {
165 // For scalars and complexes, check whether the store size of the
166 // type uses the full size.
167 case cir::TEK_Scalar:
168 return !isFullSizeType(cgf.cgm, ty, atomicSizeInBits);
169 case cir::TEK_Complex:
170 return !isFullSizeType(cgf.cgm,
171 mlir::cast<cir::ComplexType>(ty).getElementType(),
172 atomicSizeInBits / 2);
173 // Padding in structs has an undefined bit pattern. User beware.
175 return false;
176 }
177 llvm_unreachable("bad evaluation kind");
178}
179
180Address AtomicInfo::convertToAtomicIntPointer(Address addr) const {
181 mlir::Type ty = addr.getElementType();
182 uint64_t sourceSizeInBits = cgf.cgm.getDataLayout().getTypeSizeInBits(ty);
183 if (sourceSizeInBits != atomicSizeInBits) {
184 cgf.cgm.errorNYI(
185 loc,
186 "AtomicInfo::convertToAtomicIntPointer: convert through temp alloca");
187 }
188
189 return castToAtomicIntPointer(addr);
190}
191
192Address AtomicInfo::createTempAlloca() const {
193 Address tempAlloca = cgf.createMemTemp(
194 (lvalue.isBitField() && valueSizeInBits > atomicSizeInBits) ? valueTy
195 : atomicTy,
196 getAtomicAlignment(), loc, "atomic-temp");
197
198 // Cast to pointer to value type for bitfields.
199 if (lvalue.isBitField()) {
200 cgf.cgm.errorNYI(loc, "AtomicInfo::createTempAlloca: bitfield lvalue");
201 }
202
203 return tempAlloca;
204}
205
206mlir::Value AtomicInfo::getScalarRValValueOrNull(RValue rvalue) const {
207 if (rvalue.isScalar() && (!hasPadding() || !lvalue.isSimple()))
208 return rvalue.getValue();
209 return nullptr;
210}
211
212Address AtomicInfo::castToAtomicIntPointer(Address addr) const {
213 auto intTy = mlir::dyn_cast<cir::IntType>(addr.getElementType());
214 // Don't bother with int casts if the integer size is the same.
215 if (intTy && intTy.getWidth() == atomicSizeInBits)
216 return addr;
217 auto ty = cgf.getBuilder().getUIntNTy(atomicSizeInBits);
218 return addr.withElementType(cgf.getBuilder(), ty);
219}
220
221bool AtomicInfo::emitMemSetZeroIfNecessary() const {
222 assert(lvalue.isSimple());
223 Address addr = lvalue.getAddress();
224 if (!requiresMemSetZero(addr.getElementType()))
225 return false;
226
227 cgf.cgm.errorNYI(loc,
228 "AtomicInfo::emitMemSetZeroIfNecaessary: emit memset zero");
229 return false;
230}
231
232/// Return true if \param valueTy is a type that should be casted to integer
233/// around the atomic memory operation. If \param cmpxchg is true, then the
234/// cast of a floating point type is made as that instruction can not have
235/// floating point operands. TODO: Allow compare-and-exchange and FP - see
236/// comment in CIRGenAtomicExpandPass.cpp.
237static bool shouldCastToInt(mlir::Type valueTy, bool cmpxchg) {
238 if (cir::isAnyFloatingPointType(valueTy))
239 return isa<cir::FP80Type>(valueTy) || cmpxchg;
240 return !isa<cir::IntType>(valueTy) && !isa<cir::PointerType>(valueTy);
241}
242
243mlir::Value AtomicInfo::convertRValueToInt(RValue rvalue, bool cmpxchg) const {
244 // If we've got a scalar value of the right size, try to avoid going
245 // through memory. Floats get casted if needed by AtomicExpandPass.
246 if (mlir::Value value = getScalarRValValueOrNull(rvalue)) {
247 if (!shouldCastToInt(value.getType(), cmpxchg))
248 return cgf.emitToMemory(value, valueTy);
249
250 cgf.cgm.errorNYI(
251 loc, "AtomicInfo::convertRValueToInt: cast scalar rvalue to int");
252 return nullptr;
253 }
254
255 cgf.cgm.errorNYI(
256 loc, "AtomicInfo::convertRValueToInt: cast non-scalar rvalue to int");
257 return nullptr;
258}
259
260/// Copy an r-value into memory as part of storing to an atomic type.
261/// This needs to create a bit-pattern suitable for atomic operations.
262void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
263 assert(lvalue.isSimple());
264
265 // If we have an r-value, the rvalue should be of the atomic type,
266 // which means that the caller is responsible for having zeroed
267 // any padding. Just do an aggregate copy of that type.
268 if (rvalue.isAggregate()) {
269 cgf.cgm.errorNYI("copying aggregate into atomic lvalue");
270 return;
271 }
272
273 // Okay, otherwise we're copying stuff.
274
275 // Zero out the buffer if necessary.
276 emitMemSetZeroIfNecessary();
277
278 // Drill past the padding if present.
279 LValue tempLValue = projectValue();
280
281 // Okay, store the rvalue in.
282 if (rvalue.isScalar()) {
283 cgf.emitStoreOfScalar(rvalue.getValue(), tempLValue, /*isInit=*/true);
284 } else {
285 cgf.cgm.errorNYI("copying complex into atomic lvalue");
286 }
287}
288
290 mlir::Location loc) {
291 mlir::ArrayAttr ordersAttr = builder.getArrayAttr({});
292 mlir::OpBuilder::InsertPoint insertPoint;
293 cir::CaseOp::create(builder, loc, ordersAttr, cir::CaseOpKind::Default,
294 insertPoint);
295 builder.restoreInsertionPoint(insertPoint);
296}
297
298// Create a "case" operation with the given list of orders as its values. Also
299// create the region that will hold the body of the switch-case label.
300static void emitMemOrderCaseLabel(CIRGenBuilderTy &builder, mlir::Location loc,
301 mlir::Type orderType,
304 for (cir::MemOrder order : orders)
305 orderAttrs.push_back(cir::IntAttr::get(orderType, static_cast<int>(order)));
306 mlir::ArrayAttr ordersAttr = builder.getArrayAttr(orderAttrs);
307
308 mlir::OpBuilder::InsertPoint insertPoint;
309 cir::CaseOp::create(builder, loc, ordersAttr, cir::CaseOpKind::Anyof,
310 insertPoint);
311 builder.restoreInsertionPoint(insertPoint);
312}
313
314static void emitAtomicCmpXchg(CIRGenFunction &cgf, AtomicExpr *e, bool isWeak,
315 Address dest, Address ptr, Address val1,
316 Address val2, uint64_t size,
317 cir::MemOrder successOrder,
318 cir::MemOrder failureOrder,
319 cir::SyncScopeKind scope) {
320 mlir::Location loc = cgf.getLoc(e->getSourceRange());
321
322 CIRGenBuilderTy &builder = cgf.getBuilder();
323 mlir::Value expected = builder.createLoad(loc, val1);
324 mlir::Value desired = builder.createLoad(loc, val2);
325
326 auto cmpxchg = cir::AtomicCmpXchgOp::create(
327 builder, loc, expected.getType(), builder.getBoolTy(), ptr.getPointer(),
328 expected, desired,
329 cir::MemOrderAttr::get(&cgf.getMLIRContext(), successOrder),
330 cir::MemOrderAttr::get(&cgf.getMLIRContext(), failureOrder),
331 cir::SyncScopeKindAttr::get(&cgf.getMLIRContext(), scope),
332 builder.getI64IntegerAttr(ptr.getAlignment().getAsAlign().value()));
333
334 cmpxchg.setIsVolatile(e->isVolatile());
335 cmpxchg.setWeak(isWeak);
336
337 mlir::Value failed = builder.createNot(cmpxchg.getSuccess());
338 cir::IfOp::create(builder, loc, failed, /*withElseRegion=*/false,
339 [&](mlir::OpBuilder &, mlir::Location) {
340 auto ptrTy = mlir::cast<cir::PointerType>(
341 val1.getPointer().getType());
342 if (val1.getElementType() != ptrTy.getPointee()) {
343 val1 = val1.withPointer(builder.createPtrBitcast(
344 val1.getPointer(), val1.getElementType()));
345 }
346 builder.createStore(loc, cmpxchg.getOld(), val1);
347 builder.createYield(loc);
348 });
349
350 // Update the memory at Dest with Success's value.
351 cgf.emitStoreOfScalar(cmpxchg.getSuccess(),
352 cgf.makeAddrLValue(dest, e->getType()),
353 /*isInit=*/false);
354}
355
357 bool isWeak, Address dest, Address ptr,
358 Address val1, Address val2,
359 Expr *failureOrderExpr, uint64_t size,
360 cir::MemOrder successOrder,
361 cir::SyncScopeKind scope) {
362 Expr::EvalResult failureOrderEval;
363 if (failureOrderExpr->EvaluateAsInt(failureOrderEval, cgf.getContext())) {
364 uint64_t failureOrderInt = failureOrderEval.Val.getInt().getZExtValue();
365
366 cir::MemOrder failureOrder;
367 if (!cir::isValidCIRAtomicOrderingCABI(failureOrderInt)) {
368 failureOrder = cir::MemOrder::Relaxed;
369 } else {
370 switch ((cir::MemOrder)failureOrderInt) {
371 case cir::MemOrder::Relaxed:
372 // 31.7.2.18: "The failure argument shall not be memory_order_release
373 // nor memory_order_acq_rel". Fallback to monotonic.
374 case cir::MemOrder::Release:
375 case cir::MemOrder::AcquireRelease:
376 failureOrder = cir::MemOrder::Relaxed;
377 break;
378 case cir::MemOrder::Consume:
379 case cir::MemOrder::Acquire:
380 failureOrder = cir::MemOrder::Acquire;
381 break;
382 case cir::MemOrder::SequentiallyConsistent:
383 failureOrder = cir::MemOrder::SequentiallyConsistent;
384 break;
385 }
386 }
387
388 // Prior to c++17, "the failure argument shall be no stronger than the
389 // success argument". This condition has been lifted and the only
390 // precondition is 31.7.2.18. Effectively treat this as a DR and skip
391 // language version checks.
392 emitAtomicCmpXchg(cgf, e, isWeak, dest, ptr, val1, val2, size, successOrder,
393 failureOrder, scope);
394 return;
395 }
396
397 // The failure memory order is not a compile time constant. The CIR atomic ops
398 // require a constant value, so that memory order is known at compile time. In
399 // this case, we can switch based on the memory order and call each variant
400 // individually.
401 mlir::Value failureOrderVal = cgf.emitScalarExpr(failureOrderExpr);
402 mlir::Location atomicLoc = cgf.getLoc(e->getSourceRange());
403 cir::SwitchOp::create(
404 cgf.getBuilder(), atomicLoc, failureOrderVal,
405 [&](mlir::OpBuilder &b, mlir::Location loc, mlir::OperationState &os) {
406 mlir::Block *switchBlock = cgf.getBuilder().getBlock();
407
408 // case cir::MemOrder::Relaxed:
409 // // 31.7.2.18: "The failure argument shall not be
410 // memory_order_release
411 // // nor memory_order_acq_rel". Fallback to monotonic.
412 // case cir::MemOrder::Release:
413 // case cir::MemOrder::AcquireRelease:
414 // Note: Since there are 3 options, this makes sense to just emit as a
415 // 'default', which prevents user code from 'falling off' of this,
416 // which seems reasonable. Also, 'relaxed' being the default behavior
417 // is also probably the least harmful.
418 emitMemOrderDefaultCaseLabel(cgf.getBuilder(), atomicLoc);
419 emitAtomicCmpXchg(cgf, e, isWeak, dest, ptr, val1, val2, size,
420 successOrder, cir::MemOrder::Relaxed, scope);
421 cgf.getBuilder().createBreak(atomicLoc);
422 cgf.getBuilder().setInsertionPointToEnd(switchBlock);
423
424 // case cir::MemOrder::Consume:
425 // case cir::MemOrder::Acquire:
426 emitMemOrderCaseLabel(cgf.getBuilder(), loc, failureOrderVal.getType(),
427 {cir::MemOrder::Consume, cir::MemOrder::Acquire});
428 emitAtomicCmpXchg(cgf, e, isWeak, dest, ptr, val1, val2, size,
429 successOrder, cir::MemOrder::Acquire, scope);
430 cgf.getBuilder().createBreak(atomicLoc);
431 cgf.getBuilder().setInsertionPointToEnd(switchBlock);
432
433 // case cir::MemOrder::SequentiallyConsistent:
434 emitMemOrderCaseLabel(cgf.getBuilder(), loc, failureOrderVal.getType(),
435 {cir::MemOrder::SequentiallyConsistent});
436 emitAtomicCmpXchg(cgf, e, isWeak, dest, ptr, val1, val2, size,
437 successOrder, cir::MemOrder::SequentiallyConsistent,
438 scope);
439 cgf.getBuilder().createBreak(atomicLoc);
440 cgf.getBuilder().setInsertionPointToEnd(switchBlock);
441
442 cgf.getBuilder().createYield(atomicLoc);
443 });
444}
445
447 Address ptr, Address val1, Address val2,
448 Expr *isWeakExpr, Expr *failureOrderExpr, int64_t size,
449 cir::MemOrder order, cir::SyncScopeKind scope) {
451 llvm::StringRef opName;
452
453 CIRGenBuilderTy &builder = cgf.getBuilder();
454 mlir::Location loc = cgf.getLoc(expr->getSourceRange());
455 auto orderAttr = cir::MemOrderAttr::get(builder.getContext(), order);
456 auto scopeAttr = cir::SyncScopeKindAttr::get(builder.getContext(), scope);
457 cir::AtomicFetchKindAttr fetchAttr;
458 bool fetchFirst = true;
459
460 switch (expr->getOp()) {
461 case AtomicExpr::AO__c11_atomic_init:
462 llvm_unreachable("already handled!");
463
464 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
465 emitAtomicCmpXchgFailureSet(cgf, expr, /*isWeak=*/false, dest, ptr, val1,
466 val2, failureOrderExpr, size, order, scope);
467 return;
468
469 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
470 emitAtomicCmpXchgFailureSet(cgf, expr, /*isWeak=*/true, dest, ptr, val1,
471 val2, failureOrderExpr, size, order, scope);
472 return;
473
474 case AtomicExpr::AO__atomic_compare_exchange:
475 case AtomicExpr::AO__atomic_compare_exchange_n:
476 case AtomicExpr::AO__scoped_atomic_compare_exchange:
477 case AtomicExpr::AO__scoped_atomic_compare_exchange_n: {
478 bool isWeak = false;
479 if (isWeakExpr->EvaluateAsBooleanCondition(isWeak, cgf.getContext())) {
480 emitAtomicCmpXchgFailureSet(cgf, expr, isWeak, dest, ptr, val1, val2,
481 failureOrderExpr, size, order, scope);
482 } else {
484 cgf.cgm.errorNYI(expr->getSourceRange(),
485 "emitAtomicOp: non-constant isWeak");
486 }
487 return;
488 }
489
490 case AtomicExpr::AO__c11_atomic_load:
491 case AtomicExpr::AO__atomic_load_n:
492 case AtomicExpr::AO__atomic_load:
493 case AtomicExpr::AO__scoped_atomic_load_n:
494 case AtomicExpr::AO__scoped_atomic_load: {
495 cir::LoadOp load =
496 builder.createLoad(loc, ptr, /*isVolatile=*/expr->isVolatile());
497
498 load->setAttr("mem_order", orderAttr);
499 load->setAttr("sync_scope", scopeAttr);
500
501 builder.createStore(loc, load->getResult(0), dest);
502 return;
503 }
504
505 case AtomicExpr::AO__c11_atomic_store:
506 case AtomicExpr::AO__atomic_store_n:
507 case AtomicExpr::AO__atomic_store:
508 case AtomicExpr::AO__scoped_atomic_store:
509 case AtomicExpr::AO__scoped_atomic_store_n: {
510 cir::LoadOp loadVal1 = builder.createLoad(loc, val1);
511
513
514 builder.createStore(loc, loadVal1, ptr, expr->isVolatile(),
515 /*align=*/mlir::IntegerAttr{}, scopeAttr, orderAttr);
516 return;
517 }
518
519 case AtomicExpr::AO__c11_atomic_exchange:
520 case AtomicExpr::AO__atomic_exchange_n:
521 case AtomicExpr::AO__atomic_exchange:
522 case AtomicExpr::AO__scoped_atomic_exchange_n:
523 case AtomicExpr::AO__scoped_atomic_exchange:
524 opName = cir::AtomicXchgOp::getOperationName();
525 break;
526
527 case AtomicExpr::AO__atomic_add_fetch:
528 case AtomicExpr::AO__scoped_atomic_add_fetch:
529 fetchFirst = false;
530 [[fallthrough]];
531 case AtomicExpr::AO__c11_atomic_fetch_add:
532 case AtomicExpr::AO__atomic_fetch_add:
533 case AtomicExpr::AO__scoped_atomic_fetch_add:
534 opName = cir::AtomicFetchOp::getOperationName();
535 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
536 cir::AtomicFetchKind::Add);
537 break;
538
539 case AtomicExpr::AO__atomic_sub_fetch:
540 case AtomicExpr::AO__scoped_atomic_sub_fetch:
541 fetchFirst = false;
542 [[fallthrough]];
543 case AtomicExpr::AO__c11_atomic_fetch_sub:
544 case AtomicExpr::AO__atomic_fetch_sub:
545 case AtomicExpr::AO__scoped_atomic_fetch_sub:
546 opName = cir::AtomicFetchOp::getOperationName();
547 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
548 cir::AtomicFetchKind::Sub);
549 break;
550
551 case AtomicExpr::AO__atomic_min_fetch:
552 case AtomicExpr::AO__scoped_atomic_min_fetch:
553 fetchFirst = false;
554 [[fallthrough]];
555 case AtomicExpr::AO__c11_atomic_fetch_min:
556 case AtomicExpr::AO__atomic_fetch_min:
557 case AtomicExpr::AO__scoped_atomic_fetch_min:
558 opName = cir::AtomicFetchOp::getOperationName();
559 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
560 cir::AtomicFetchKind::Min);
561 break;
562
563 case AtomicExpr::AO__atomic_max_fetch:
564 case AtomicExpr::AO__scoped_atomic_max_fetch:
565 fetchFirst = false;
566 [[fallthrough]];
567 case AtomicExpr::AO__c11_atomic_fetch_max:
568 case AtomicExpr::AO__atomic_fetch_max:
569 case AtomicExpr::AO__scoped_atomic_fetch_max:
570 opName = cir::AtomicFetchOp::getOperationName();
571 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
572 cir::AtomicFetchKind::Max);
573 break;
574
575 case AtomicExpr::AO__atomic_and_fetch:
576 case AtomicExpr::AO__scoped_atomic_and_fetch:
577 fetchFirst = false;
578 [[fallthrough]];
579 case AtomicExpr::AO__c11_atomic_fetch_and:
580 case AtomicExpr::AO__atomic_fetch_and:
581 case AtomicExpr::AO__scoped_atomic_fetch_and:
582 opName = cir::AtomicFetchOp::getOperationName();
583 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
584 cir::AtomicFetchKind::And);
585 break;
586
587 case AtomicExpr::AO__atomic_or_fetch:
588 case AtomicExpr::AO__scoped_atomic_or_fetch:
589 fetchFirst = false;
590 [[fallthrough]];
591 case AtomicExpr::AO__c11_atomic_fetch_or:
592 case AtomicExpr::AO__atomic_fetch_or:
593 case AtomicExpr::AO__scoped_atomic_fetch_or:
594 opName = cir::AtomicFetchOp::getOperationName();
595 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
596 cir::AtomicFetchKind::Or);
597 break;
598
599 case AtomicExpr::AO__atomic_xor_fetch:
600 case AtomicExpr::AO__scoped_atomic_xor_fetch:
601 fetchFirst = false;
602 [[fallthrough]];
603 case AtomicExpr::AO__c11_atomic_fetch_xor:
604 case AtomicExpr::AO__atomic_fetch_xor:
605 case AtomicExpr::AO__scoped_atomic_fetch_xor:
606 opName = cir::AtomicFetchOp::getOperationName();
607 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
608 cir::AtomicFetchKind::Xor);
609 break;
610
611 case AtomicExpr::AO__atomic_nand_fetch:
612 case AtomicExpr::AO__scoped_atomic_nand_fetch:
613 fetchFirst = false;
614 [[fallthrough]];
615 case AtomicExpr::AO__c11_atomic_fetch_nand:
616 case AtomicExpr::AO__atomic_fetch_nand:
617 case AtomicExpr::AO__scoped_atomic_fetch_nand:
618 opName = cir::AtomicFetchOp::getOperationName();
619 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
620 cir::AtomicFetchKind::Nand);
621 break;
622
623 case AtomicExpr::AO__atomic_test_and_set: {
624 auto op = cir::AtomicTestAndSetOp::create(
625 builder, loc, ptr.getPointer(), order,
626 builder.getI64IntegerAttr(ptr.getAlignment().getQuantity()),
627 expr->isVolatile());
628 builder.createStore(loc, op, dest);
629 return;
630 }
631
632 case AtomicExpr::AO__atomic_clear: {
633 cir::AtomicClearOp::create(
634 builder, loc, ptr.getPointer(), order,
635 builder.getI64IntegerAttr(ptr.getAlignment().getQuantity()),
636 expr->isVolatile());
637 return;
638 }
639
640 case AtomicExpr::AO__atomic_fetch_uinc:
641 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
642 opName = cir::AtomicFetchOp::getOperationName();
643 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
644 cir::AtomicFetchKind::UIncWrap);
645 break;
646
647 case AtomicExpr::AO__atomic_fetch_udec:
648 case AtomicExpr::AO__scoped_atomic_fetch_udec:
649 opName = cir::AtomicFetchOp::getOperationName();
650 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
651 cir::AtomicFetchKind::UDecWrap);
652 break;
653
654 case AtomicExpr::AO__opencl_atomic_init:
655
656 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
657 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
658
659 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
660 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
661
662 case AtomicExpr::AO__opencl_atomic_load:
663 case AtomicExpr::AO__hip_atomic_load:
664
665 case AtomicExpr::AO__opencl_atomic_store:
666 case AtomicExpr::AO__hip_atomic_store:
667
668 case AtomicExpr::AO__hip_atomic_exchange:
669 case AtomicExpr::AO__opencl_atomic_exchange:
670
671 case AtomicExpr::AO__hip_atomic_fetch_add:
672 case AtomicExpr::AO__opencl_atomic_fetch_add:
673
674 case AtomicExpr::AO__hip_atomic_fetch_sub:
675 case AtomicExpr::AO__opencl_atomic_fetch_sub:
676
677 case AtomicExpr::AO__hip_atomic_fetch_min:
678 case AtomicExpr::AO__opencl_atomic_fetch_min:
679
680 case AtomicExpr::AO__hip_atomic_fetch_max:
681 case AtomicExpr::AO__opencl_atomic_fetch_max:
682
683 case AtomicExpr::AO__hip_atomic_fetch_and:
684 case AtomicExpr::AO__opencl_atomic_fetch_and:
685
686 case AtomicExpr::AO__hip_atomic_fetch_or:
687 case AtomicExpr::AO__opencl_atomic_fetch_or:
688
689 case AtomicExpr::AO__hip_atomic_fetch_xor:
690 case AtomicExpr::AO__opencl_atomic_fetch_xor:
691 cgf.cgm.errorNYI(expr->getSourceRange(), "emitAtomicOp: expr op NYI");
692 return;
693 }
694
695 assert(!opName.empty() && "expected operation name to build");
696 mlir::Value loadVal1 = builder.createLoad(loc, val1);
697
698 SmallVector<mlir::Value> atomicOperands = {ptr.getPointer(), loadVal1};
699 SmallVector<mlir::Type> atomicResTys = {loadVal1.getType()};
700 mlir::Operation *rmwOp = builder.create(loc, builder.getStringAttr(opName),
701 atomicOperands, atomicResTys);
702
703 if (fetchAttr)
704 rmwOp->setAttr("binop", fetchAttr);
705 rmwOp->setAttr("mem_order", orderAttr);
706 rmwOp->setAttr("sync_scope", scopeAttr);
707 if (expr->isVolatile())
708 rmwOp->setAttr("is_volatile", builder.getUnitAttr());
709 if (fetchFirst && opName == cir::AtomicFetchOp::getOperationName())
710 rmwOp->setAttr("fetch_first", builder.getUnitAttr());
711
712 mlir::Value result = rmwOp->getResult(0);
713 builder.createStore(loc, result, dest);
714}
715
716// Map clang sync scope to CIR sync scope.
717static cir::SyncScopeKind convertSyncScopeToCIR(CIRGenFunction &cgf,
718 SourceRange range,
719 clang::SyncScope scope) {
720 switch (scope) {
721 default: {
723 cgf.cgm.errorNYI(range, "convertSyncScopeToCIR: unhandled sync scope");
724 return cir::SyncScopeKind::System;
725 }
726
728 return cir::SyncScopeKind::SingleThread;
730 return cir::SyncScopeKind::System;
731 }
732}
733
735 Address ptr, Address val1, Address val2,
736 Expr *isWeakExpr, Expr *failureOrderExpr, int64_t size,
737 cir::MemOrder order,
738 const std::optional<Expr::EvalResult> &scopeConst,
739 mlir::Value scopeValue) {
740 std::unique_ptr<AtomicScopeModel> scopeModel = expr->getScopeModel();
741
742 if (!scopeModel) {
743 emitAtomicOp(cgf, expr, dest, ptr, val1, val2, isWeakExpr, failureOrderExpr,
744 size, order, cir::SyncScopeKind::System);
745 return;
746 }
747
748 if (scopeConst.has_value()) {
749 cir::SyncScopeKind mappedScope = convertSyncScopeToCIR(
750 cgf, expr->getScope()->getSourceRange(),
751 scopeModel->map(scopeConst->Val.getInt().getZExtValue()));
752 emitAtomicOp(cgf, expr, dest, ptr, val1, val2, isWeakExpr, failureOrderExpr,
753 size, order, mappedScope);
754 return;
755 }
756
758 cgf.cgm.errorNYI(expr->getSourceRange(), "emitAtomicOp: dynamic sync scope");
759}
760
761static std::optional<cir::MemOrder>
762getEffectiveAtomicMemOrder(cir::MemOrder oriOrder, bool isStore, bool isLoad,
763 bool isFence) {
764 // Some memory orders are not supported by partial atomic operation:
765 // {memory_order_releaxed} is not valid for fence operations.
766 // {memory_order_consume, memory_order_acquire} are not valid for write-only
767 // operations.
768 // {memory_order_release} is not valid for read-only operations.
769 // {memory_order_acq_rel} is only valid for read-write operations.
770 if (isStore) {
771 if (oriOrder == cir::MemOrder::Consume ||
772 oriOrder == cir::MemOrder::Acquire ||
773 oriOrder == cir::MemOrder::AcquireRelease)
774 return std::nullopt;
775 } else if (isLoad) {
776 if (oriOrder == cir::MemOrder::Release ||
777 oriOrder == cir::MemOrder::AcquireRelease)
778 return std::nullopt;
779 } else if (isFence) {
780 if (oriOrder == cir::MemOrder::Relaxed)
781 return std::nullopt;
782 }
783 // memory_order_consume is not implemented, it is always treated like
784 // memory_order_acquire
785 if (oriOrder == cir::MemOrder::Consume)
786 return cir::MemOrder::Acquire;
787 return oriOrder;
788}
789
791 CIRGenFunction &cgf, mlir::Value order, bool isStore, bool isLoad,
792 bool isFence, llvm::function_ref<void(cir::MemOrder)> emitAtomicOpFn) {
793 if (!order)
794 return;
795 // The memory order is not known at compile-time. The atomic operations
796 // can't handle runtime memory orders; the memory order must be hard coded.
797 // Generate a "switch" statement that converts a runtime value into a
798 // compile-time value.
799 CIRGenBuilderTy &builder = cgf.getBuilder();
800 cir::SwitchOp::create(
801 builder, order.getLoc(), order,
802 [&](mlir::OpBuilder &, mlir::Location loc, mlir::OperationState &) {
803 mlir::Block *switchBlock = builder.getBlock();
804
805 auto emitMemOrderCase = [&](llvm::ArrayRef<cir::MemOrder> caseOrders) {
806 // Checking there are same effective memory order for each case.
807 for (int i = 1, e = caseOrders.size(); i < e; i++)
808 assert((getEffectiveAtomicMemOrder(caseOrders[i - 1], isStore,
809 isLoad, isFence) ==
810 getEffectiveAtomicMemOrder(caseOrders[i], isStore, isLoad,
811 isFence)) &&
812 "Effective memory order must be same!");
813 // Emit case label and atomic opeartion if neccessary.
814 if (caseOrders.empty()) {
815 emitMemOrderDefaultCaseLabel(builder, loc);
816 // There is no good way to report an unsupported memory order at
817 // runtime, hence the fallback to memory_order_relaxed.
818 if (!isFence)
819 emitAtomicOpFn(cir::MemOrder::Relaxed);
820 } else if (std::optional<cir::MemOrder> actualOrder =
821 getEffectiveAtomicMemOrder(caseOrders[0], isStore,
822 isLoad, isFence)) {
823 // Included in default case.
824 if (!isFence && actualOrder == cir::MemOrder::Relaxed)
825 return;
826 // Creating case operation for effective memory order. If there are
827 // multiple cases in `caseOrders`, the actual order of each case
828 // must be same, this needs to be guaranteed by the caller.
829 emitMemOrderCaseLabel(builder, loc, order.getType(), caseOrders);
830 emitAtomicOpFn(actualOrder.value());
831 } else {
832 // Do nothing if (!caseOrders.empty() && !actualOrder)
833 return;
834 }
835 builder.createBreak(loc);
836 builder.setInsertionPointToEnd(switchBlock);
837 };
838
839 emitMemOrderCase(/*default:*/ {});
840 emitMemOrderCase({cir::MemOrder::Relaxed});
841 emitMemOrderCase({cir::MemOrder::Consume, cir::MemOrder::Acquire});
842 emitMemOrderCase({cir::MemOrder::Release});
843 emitMemOrderCase({cir::MemOrder::AcquireRelease});
844 emitMemOrderCase({cir::MemOrder::SequentiallyConsistent});
845
846 builder.createYield(loc);
847 });
848}
849
851 const Expr *memOrder, bool isStore, bool isLoad, bool isFence,
852 llvm::function_ref<void(cir::MemOrder)> emitAtomicOpFn) {
853 // Emit the memory order operand, and try to evaluate it as a constant.
854 Expr::EvalResult eval;
855 if (memOrder->EvaluateAsInt(eval, getContext())) {
856 uint64_t constOrder = eval.Val.getInt().getZExtValue();
857 // We should not ever get to a case where the ordering isn't a valid CABI
858 // value, but it's hard to enforce that in general.
859 if (!cir::isValidCIRAtomicOrderingCABI(constOrder))
860 return;
861 cir::MemOrder oriOrder = static_cast<cir::MemOrder>(constOrder);
862 if (std::optional<cir::MemOrder> actualOrder =
863 getEffectiveAtomicMemOrder(oriOrder, isStore, isLoad, isFence))
864 emitAtomicOpFn(actualOrder.value());
865 return;
866 }
867
868 // Otherwise, handle variable memory ordering. Emit `SwitchOp` to convert
869 // dynamic value to static value.
870 mlir::Value dynOrder = emitScalarExpr(memOrder);
871 emitAtomicExprWithDynamicMemOrder(*this, dynOrder, isStore, isLoad, isFence,
872 emitAtomicOpFn);
873}
874
876 QualType atomicTy = e->getPtr()->getType()->getPointeeType();
877 QualType memTy = atomicTy;
878 if (const auto *ty = atomicTy->getAs<AtomicType>())
879 memTy = ty->getValueType();
880
881 Expr *isWeakExpr = nullptr;
882 Expr *orderFailExpr = nullptr;
883
884 Address val1 = Address::invalid();
885 Address val2 = Address::invalid();
886 Address dest = Address::invalid();
888
890 if (e->getOp() == AtomicExpr::AO__c11_atomic_init) {
891 LValue lvalue = makeAddrLValue(ptr, atomicTy);
892 emitAtomicInit(e->getVal1(), lvalue);
893 return RValue::get(nullptr);
894 }
895
896 TypeInfoChars typeInfo = getContext().getTypeInfoInChars(atomicTy);
897 uint64_t size = typeInfo.Width.getQuantity();
898
899 // Emit the sync scope operand, and try to evaluate it as a constant.
900 mlir::Value scope =
901 e->getScopeModel() ? emitScalarExpr(e->getScope()) : nullptr;
902 std::optional<Expr::EvalResult> scopeConst;
903 if (Expr::EvalResult eval;
904 e->getScopeModel() && e->getScope()->EvaluateAsInt(eval, getContext()))
905 scopeConst.emplace(std::move(eval));
906
907 switch (e->getOp()) {
908 default:
909 cgm.errorNYI(e->getSourceRange(), "atomic op NYI");
910 return RValue::get(nullptr);
911
912 case AtomicExpr::AO__c11_atomic_init:
913 llvm_unreachable("already handled above with emitAtomicInit");
914
915 case AtomicExpr::AO__atomic_load_n:
916 case AtomicExpr::AO__scoped_atomic_load_n:
917 case AtomicExpr::AO__c11_atomic_load:
918 case AtomicExpr::AO__atomic_test_and_set:
919 case AtomicExpr::AO__atomic_clear:
920 break;
921
922 case AtomicExpr::AO__atomic_load:
923 case AtomicExpr::AO__scoped_atomic_load:
925 break;
926
927 case AtomicExpr::AO__atomic_store:
928 case AtomicExpr::AO__scoped_atomic_store:
930 break;
931
932 case AtomicExpr::AO__atomic_exchange:
933 case AtomicExpr::AO__scoped_atomic_exchange:
936 break;
937
938 case AtomicExpr::AO__atomic_compare_exchange:
939 case AtomicExpr::AO__atomic_compare_exchange_n:
940 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
941 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
942 case AtomicExpr::AO__scoped_atomic_compare_exchange:
943 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
945 if (e->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
946 e->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange)
948 else
949 val2 = emitValToTemp(*this, e->getVal2());
950 orderFailExpr = e->getOrderFail();
951 if (e->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
952 e->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
953 e->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange_n ||
954 e->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange)
955 isWeakExpr = e->getWeak();
956 break;
957
958 case AtomicExpr::AO__c11_atomic_fetch_add:
959 case AtomicExpr::AO__c11_atomic_fetch_sub:
960 if (memTy->isPointerType()) {
961 cgm.errorNYI(e->getSourceRange(),
962 "atomic fetch-and-add and fetch-and-sub for pointers");
963 return RValue::get(nullptr);
964 }
965 [[fallthrough]];
966 case AtomicExpr::AO__atomic_fetch_add:
967 case AtomicExpr::AO__atomic_fetch_max:
968 case AtomicExpr::AO__atomic_fetch_min:
969 case AtomicExpr::AO__atomic_fetch_sub:
970 case AtomicExpr::AO__atomic_add_fetch:
971 case AtomicExpr::AO__atomic_max_fetch:
972 case AtomicExpr::AO__atomic_min_fetch:
973 case AtomicExpr::AO__atomic_sub_fetch:
974 case AtomicExpr::AO__c11_atomic_fetch_max:
975 case AtomicExpr::AO__c11_atomic_fetch_min:
976 case AtomicExpr::AO__scoped_atomic_fetch_add:
977 case AtomicExpr::AO__scoped_atomic_fetch_max:
978 case AtomicExpr::AO__scoped_atomic_fetch_min:
979 case AtomicExpr::AO__scoped_atomic_fetch_sub:
980 case AtomicExpr::AO__scoped_atomic_add_fetch:
981 case AtomicExpr::AO__scoped_atomic_max_fetch:
982 case AtomicExpr::AO__scoped_atomic_min_fetch:
983 case AtomicExpr::AO__scoped_atomic_sub_fetch:
984 [[fallthrough]];
985
986 case AtomicExpr::AO__atomic_fetch_and:
987 case AtomicExpr::AO__atomic_fetch_nand:
988 case AtomicExpr::AO__atomic_fetch_or:
989 case AtomicExpr::AO__atomic_fetch_xor:
990 case AtomicExpr::AO__atomic_and_fetch:
991 case AtomicExpr::AO__atomic_nand_fetch:
992 case AtomicExpr::AO__atomic_or_fetch:
993 case AtomicExpr::AO__atomic_xor_fetch:
994 case AtomicExpr::AO__atomic_exchange_n:
995 case AtomicExpr::AO__atomic_store_n:
996 case AtomicExpr::AO__c11_atomic_fetch_and:
997 case AtomicExpr::AO__c11_atomic_fetch_nand:
998 case AtomicExpr::AO__c11_atomic_fetch_or:
999 case AtomicExpr::AO__c11_atomic_fetch_xor:
1000 case AtomicExpr::AO__c11_atomic_exchange:
1001 case AtomicExpr::AO__c11_atomic_store:
1002 case AtomicExpr::AO__scoped_atomic_fetch_and:
1003 case AtomicExpr::AO__scoped_atomic_fetch_nand:
1004 case AtomicExpr::AO__scoped_atomic_fetch_or:
1005 case AtomicExpr::AO__scoped_atomic_fetch_xor:
1006 case AtomicExpr::AO__scoped_atomic_and_fetch:
1007 case AtomicExpr::AO__scoped_atomic_nand_fetch:
1008 case AtomicExpr::AO__scoped_atomic_or_fetch:
1009 case AtomicExpr::AO__scoped_atomic_xor_fetch:
1010 case AtomicExpr::AO__scoped_atomic_store_n:
1011 case AtomicExpr::AO__scoped_atomic_exchange_n:
1012 case AtomicExpr::AO__atomic_fetch_uinc:
1013 case AtomicExpr::AO__atomic_fetch_udec:
1014 val1 = emitValToTemp(*this, e->getVal1());
1015 break;
1016 }
1017
1018 QualType resultTy = e->getType().getUnqualifiedType();
1019
1020 bool shouldCastToIntPtrTy =
1022
1023 // The inlined atomics only function on iN types, where N is a power of 2. We
1024 // need to make sure (via temporaries if necessary) that all incoming values
1025 // are compatible.
1026 LValue atomicValue = makeAddrLValue(ptr, atomicTy);
1027 AtomicInfo atomics(*this, atomicValue, getLoc(e->getSourceRange()));
1028
1029 if (shouldCastToIntPtrTy) {
1030 ptr = atomics.castToAtomicIntPointer(ptr);
1031 if (val1.isValid())
1032 val1 = atomics.convertToAtomicIntPointer(val1);
1033 }
1034 if (dest.isValid()) {
1035 if (shouldCastToIntPtrTy)
1036 dest = atomics.castToAtomicIntPointer(dest);
1037 } else if (e->isCmpXChg()) {
1038 dest = createMemTemp(resultTy, getLoc(e->getSourceRange()), "cmpxchg.bool");
1039 } else if (e->getOp() == AtomicExpr::AO__atomic_test_and_set) {
1040 dest = createMemTemp(resultTy, getLoc(e->getSourceRange()),
1041 "test_and_set.bool");
1042 } else if (!resultTy->isVoidType()) {
1043 dest = atomics.createTempAlloca();
1044 if (shouldCastToIntPtrTy)
1045 dest = atomics.castToAtomicIntPointer(dest);
1046 }
1047
1048 bool powerOf2Size = (size & (size - 1)) == 0;
1049 bool useLibCall = !powerOf2Size || (size > 16);
1050
1051 // For atomics larger than 16 bytes, emit a libcall from the frontend. This
1052 // avoids the overhead of dealing with excessively-large value types in IR.
1053 // Non-power-of-2 values also lower to libcall here, as they are not currently
1054 // permitted in IR instructions (although that constraint could be relaxed in
1055 // the future). For other cases where a libcall is required on a given
1056 // platform, we let the backend handle it (this includes handling for all of
1057 // the size-optimized libcall variants, which are only valid up to 16 bytes.)
1058 //
1059 // See: https://llvm.org/docs/Atomics.html#libcalls-atomic
1060 if (useLibCall) {
1062 cgm.errorNYI(e->getSourceRange(), "emitAtomicExpr: emit atomic lib call");
1063 return RValue::get(nullptr);
1064 }
1065
1066 bool isStore = e->getOp() == AtomicExpr::AO__c11_atomic_store ||
1067 e->getOp() == AtomicExpr::AO__opencl_atomic_store ||
1068 e->getOp() == AtomicExpr::AO__hip_atomic_store ||
1069 e->getOp() == AtomicExpr::AO__atomic_store ||
1070 e->getOp() == AtomicExpr::AO__atomic_store_n ||
1071 e->getOp() == AtomicExpr::AO__scoped_atomic_store ||
1072 e->getOp() == AtomicExpr::AO__scoped_atomic_store_n ||
1073 e->getOp() == AtomicExpr::AO__atomic_clear;
1074 bool isLoad = e->getOp() == AtomicExpr::AO__c11_atomic_load ||
1075 e->getOp() == AtomicExpr::AO__opencl_atomic_load ||
1076 e->getOp() == AtomicExpr::AO__hip_atomic_load ||
1077 e->getOp() == AtomicExpr::AO__atomic_load ||
1078 e->getOp() == AtomicExpr::AO__atomic_load_n ||
1079 e->getOp() == AtomicExpr::AO__scoped_atomic_load ||
1080 e->getOp() == AtomicExpr::AO__scoped_atomic_load_n;
1081
1082 auto emitAtomicOpCallBackFn = [&](cir::MemOrder memOrder) {
1083 emitAtomicOp(*this, e, dest, ptr, val1, val2, isWeakExpr, orderFailExpr,
1084 size, memOrder, scopeConst, scope);
1085 };
1086 emitAtomicExprWithMemOrder(e->getOrder(), isStore, isLoad, /*isFence*/ false,
1087 emitAtomicOpCallBackFn);
1088
1089 if (resultTy->isVoidType())
1090 return RValue::get(nullptr);
1091
1092 return convertTempToRValue(
1093 dest.withElementType(builder, convertTypeForMem(resultTy)), resultTy,
1094 e->getExprLoc());
1095}
1096
1097void CIRGenFunction::emitAtomicStore(RValue rvalue, LValue dest, bool isInit) {
1098 bool isVolatile = dest.isVolatileQualified();
1099 auto order = cir::MemOrder::SequentiallyConsistent;
1100 if (!dest.getType()->isAtomicType()) {
1102 }
1103 return emitAtomicStore(rvalue, dest, order, isVolatile, isInit);
1104}
1105
1106/// Emit a store to an l-value of atomic type.
1107///
1108/// Note that the r-value is expected to be an r-value of the atomic type; this
1109/// means that for aggregate r-values, it should include storage for any padding
1110/// that was necessary.
1112 cir::MemOrder order, bool isVolatile,
1113 bool isInit) {
1114 // If this is an aggregate r-value, it should agree in type except
1115 // maybe for address-space qualification.
1116 mlir::Location loc = dest.getPointer().getLoc();
1117 assert(!rvalue.isAggregate() ||
1119 dest.getAddress().getElementType());
1120
1121 AtomicInfo atomics(*this, dest, loc);
1122 LValue lvalue = atomics.getAtomicLValue();
1123
1124 if (lvalue.isSimple()) {
1125 // If this is an initialization, just put the value there normally.
1126 if (isInit) {
1127 atomics.emitCopyIntoMemory(rvalue);
1128 return;
1129 }
1130
1131 // Check whether we should use a library call.
1132 if (atomics.shouldUseLibCall()) {
1134 cgm.errorNYI(loc, "emitAtomicStore: atomic store with library call");
1135 return;
1136 }
1137
1138 // Okay, we're doing this natively.
1139 mlir::Value valueToStore = atomics.convertRValueToInt(rvalue);
1140
1141 // Do the atomic store.
1142 Address addr = atomics.getAtomicAddress();
1143 if (mlir::Value value = atomics.getScalarRValValueOrNull(rvalue)) {
1144 if (shouldCastToInt(value.getType(), /*CmpXchg=*/false)) {
1145 addr = atomics.castToAtomicIntPointer(addr);
1146 valueToStore =
1147 builder.createIntCast(valueToStore, addr.getElementType());
1148 }
1149 }
1150 cir::StoreOp store = builder.createStore(loc, valueToStore, addr);
1151
1152 // Initializations don't need to be atomic.
1153 if (!isInit) {
1155 store.setMemOrder(order);
1156 }
1157
1158 // Other decoration.
1159 if (isVolatile)
1160 store.setIsVolatile(true);
1161
1163 return;
1164 }
1165
1166 cgm.errorNYI(loc, "emitAtomicStore: non-simple atomic lvalue");
1168}
1169
1171 AtomicInfo atomics(*this, dest, getLoc(init->getSourceRange()));
1172
1173 switch (atomics.getEvaluationKind()) {
1174 case cir::TEK_Scalar: {
1175 mlir::Value value = emitScalarExpr(init);
1176 atomics.emitCopyIntoMemory(RValue::get(value));
1177 return;
1178 }
1179
1180 case cir::TEK_Complex: {
1181 mlir::Value value = emitComplexExpr(init);
1182 atomics.emitCopyIntoMemory(RValue::get(value));
1183 return;
1184 }
1185
1186 case cir::TEK_Aggregate: {
1187 // Fix up the destination if the initializer isn't an expression
1188 // of atomic type.
1189 bool zeroed = false;
1190 if (!init->getType()->isAtomicType()) {
1191 zeroed = atomics.emitMemSetZeroIfNecessary();
1192 dest = atomics.projectValue();
1193 }
1194
1195 // Evaluate the expression directly into the destination.
1201
1202 emitAggExpr(init, slot);
1203 return;
1204 }
1205 }
1206
1207 llvm_unreachable("bad evaluation kind");
1208}
static bool shouldCastToInt(mlir::Type valueTy, bool cmpxchg)
Return true if.
static Address emitValToTemp(CIRGenFunction &cgf, Expr *e)
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 void emitMemOrderCaseLabel(CIRGenBuilderTy &builder, mlir::Location loc, mlir::Type orderType, llvm::ArrayRef< cir::MemOrder > orders)
static cir::SyncScopeKind convertSyncScopeToCIR(CIRGenFunction &cgf, SourceRange range, clang::SyncScope scope)
static void emitAtomicExprWithDynamicMemOrder(CIRGenFunction &cgf, mlir::Value order, bool isStore, bool isLoad, bool isFence, llvm::function_ref< void(cir::MemOrder)> emitAtomicOpFn)
static void emitAtomicOp(CIRGenFunction &cgf, AtomicExpr *expr, Address dest, Address ptr, Address val1, Address val2, Expr *isWeakExpr, Expr *failureOrderExpr, int64_t size, cir::MemOrder order, 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 emitMemOrderDefaultCaseLabel(CIRGenBuilderTy &builder, mlir::Location loc)
static std::optional< cir::MemOrder > getEffectiveAtomicMemOrder(cir::MemOrder oriOrder, bool isStore, bool isLoad, bool isFence)
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)
__device__ __2f16 b
cir::BreakOp createBreak(mlir::Location loc)
Create a break operation.
mlir::Value createPtrBitcast(mlir::Value src, mlir::Type newPointeeTy)
mlir::Value createNot(mlir::Location loc, mlir::Value value)
cir::YieldOp createYield(mlir::Location loc, mlir::ValueRange value={})
Create a yield operation.
cir::BoolType getBoolTy()
llvm::TypeSize getTypeSizeInBits(mlir::Type ty) const
llvm::TypeSize getTypeStoreSize(mlir::Type ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
APSInt & getInt()
Definition APValue.h:508
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:917
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:6927
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7076
Expr * getVal2() const
Definition Expr.h:6978
Expr * getOrder() const
Definition Expr.h:6961
Expr * getScope() const
Definition Expr.h:6964
bool isCmpXChg() const
Definition Expr.h:7011
AtomicOp getOp() const
Definition Expr.h:6990
Expr * getVal1() const
Definition Expr.h:6968
Expr * getPtr() const
Definition Expr.h:6958
Expr * getWeak() const
Definition Expr.h:6984
Expr * getOrderFail() const
Definition Expr.h:6974
bool isVolatile() const
Definition Expr.h:7007
Address withPointer(mlir::Value newPtr) const
Return address with different pointer, but same element type and alignment.
Definition Address.h:81
mlir::Value getPointer() const
Definition Address.h:96
mlir::Type getElementType() const
Definition Address.h:123
static Address invalid()
Definition Address.h:74
Address withElementType(CIRGenBuilderTy &builder, mlir::Type ElemTy) const
Return address with different element type, a bitcast pointer, and the same alignment.
clang::CharUnits getAlignment() const
Definition Address.h:136
bool isValid() const
Definition Address.h:75
An aggregate value slot.
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed)
cir::StoreOp createStore(mlir::Location loc, mlir::Value val, Address dst, bool isVolatile=false, mlir::IntegerAttr align={}, cir::SyncScopeKindAttr scope={}, cir::MemOrderAttr order={})
cir::LoadOp createLoad(mlir::Location loc, Address addr, bool isVolatile=false)
cir::IntType getUIntNTy(int n)
RValue convertTempToRValue(Address addr, clang::QualType type, clang::SourceLocation loc)
Given the address of a temporary variable, produce an r-value of its type.
Address emitPointerWithAlignment(const clang::Expr *expr, LValueBaseInfo *baseInfo=nullptr)
Given an expression with a pointer type, emit the value and compute our best estimate of the alignmen...
mlir::Value emitComplexExpr(const Expr *e)
Emit the computation of the specified expression of complex type, returning the result.
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
void emitAnyExprToMem(const Expr *e, Address location, Qualifiers quals, bool isInitializer)
Emits the code necessary to evaluate an arbitrary expression into the given memory location.
RValue emitAtomicExpr(AtomicExpr *e)
mlir::Type convertTypeForMem(QualType t)
void emitStoreOfScalar(mlir::Value value, Address addr, bool isVolatile, clang::QualType ty, LValueBaseInfo baseInfo, bool isInit=false, bool isNontemporal=false)
void emitAtomicExprWithMemOrder(const Expr *memOrder, bool isStore, bool isLoad, bool isFence, llvm::function_ref< void(cir::MemOrder)> emitAtomicOp)
mlir::Value emitToMemory(mlir::Value value, clang::QualType ty)
Given a value and its clang type, returns the value casted to its memory representation.
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
CIRGenBuilderTy & getBuilder()
mlir::MLIRContext & getMLIRContext()
void emitAtomicInit(Expr *init, LValue dest)
LValue makeAddrLValue(Address addr, QualType ty, AlignmentSource source=AlignmentSource::Type)
void emitAtomicStore(RValue rvalue, LValue dest, bool isInit)
clang::ASTContext & getContext() const
Address createMemTemp(QualType t, mlir::Location loc, const Twine &name="tmp", Address *alloca=nullptr, mlir::OpBuilder::InsertPoint ip={})
Create a temporary memory object of the given type, with appropriate alignmen and cast it to the defa...
void emitAggExpr(const clang::Expr *e, AggValueSlot slot)
This class organizes the cross-function state that is used while generating CIR code.
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
const cir::CIRDataLayout getDataLayout() const
Address getAddress() const
clang::QualType getType() const
mlir::Value getPointer() const
bool isVolatileQualified() const
bool isSimple() const
This trivial value class is used to represent the result of an expression that is evaluated.
Definition CIRGenValue.h:33
Address getAggregateAddress() const
Return the value of the address of the aggregate.
Definition CIRGenValue.h:69
bool isAggregate() const
Definition CIRGenValue.h:51
static RValue get(mlir::Value v)
Definition CIRGenValue.h:83
mlir::Value getValue() const
Return the value of this scalar value.
Definition CIRGenValue.h:57
bool isScalar() const
Definition CIRGenValue.h:49
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
This represents one expression.
Definition Expr.h:112
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
QualType getType() const
Definition Expr.h:144
A (possibly-)qualified type.
Definition TypeBase.h:937
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8471
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
A trivial tuple used to represent a source range.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
virtual bool hasBuiltinAtomic(uint64_t AtomicSizeInBits, uint64_t AlignmentInBits) const
Returns true if the given target supports lock-free atomic operations at the specified width and alig...
Definition TargetInfo.h:865
bool isVoidType() const
Definition TypeBase.h:9034
bool isPointerType() const
Definition TypeBase.h:8668
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
bool isAtomicType() const
Definition TypeBase.h:8860
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
bool isValidCIRAtomicOrderingCABI(Int value)
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
SyncScope
Defines sync scope values used internally by clang.
Definition SyncScope.h:42
unsigned long uint64_t
static bool atomicInfoGetAtomicPointer()
static bool aggValueSlotGC()
static bool opLoadStoreAtomic()
static bool opLoadStoreTbaa()
static bool atomicUseLibCall()
static bool atomicOpenMP()
static bool atomicMicrosoftVolatile()
static bool atomicSyncScopeID()
static bool atomicInfoGetAtomicAddress()
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650