Skip to content

Commit 331a5db

Browse files
authored
[CIR] Add initial support for atomic types (#152923)
1 parent 7b8189a commit 331a5db

File tree

11 files changed

+351
-3
lines changed

11 files changed

+351
-3
lines changed

clang/include/clang/CIR/Dialect/IR/CIRDataLayout.h

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,21 @@ class CIRDataLayout {
3434
void reset(mlir::DataLayoutSpecInterface spec);
3535

3636
bool isBigEndian() const { return bigEndian; }
37+
38+
/// Returns the maximum number of bytes that may be overwritten by
39+
/// storing the specified type.
40+
///
41+
/// If Ty is a scalable vector type, the scalable property will be set and
42+
/// the runtime size will be a positive integer multiple of the base size.
43+
///
44+
/// For example, returns 5 for i36 and 10 for x86_fp80.
45+
llvm::TypeSize getTypeStoreSize(mlir::Type ty) const {
46+
llvm::TypeSize baseSize = getTypeSizeInBits(ty);
47+
return {llvm::divideCeil(baseSize.getKnownMinValue(), 8),
48+
baseSize.isScalable()};
49+
}
50+
51+
llvm::TypeSize getTypeSizeInBits(mlir::Type ty) const;
3752
};
3853

3954
} // namespace cir

clang/include/clang/CIR/MissingFeatures.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,13 @@ struct MissingFeatures {
161161
static bool addressIsKnownNonNull() { return false; }
162162
static bool addressPointerAuthInfo() { return false; }
163163

164+
// Atomic
165+
static bool atomicExpr() { return false; }
166+
static bool atomicInfo() { return false; }
167+
static bool atomicInfoGetAtomicPointer() { return false; }
168+
static bool atomicInfoGetAtomicAddress() { return false; }
169+
static bool atomicUseLibCall() { return false; }
170+
164171
// Misc
165172
static bool abiArgInfo() { return false; }
166173
static bool addHeapAllocSiteMetadata() { return false; }
@@ -196,7 +203,9 @@ struct MissingFeatures {
196203
static bool ctorMemcpyizer() { return false; }
197204
static bool cudaSupport() { return false; }
198205
static bool cxxRecordStaticMembers() { return false; }
206+
static bool dataLayoutTypeIsSized() { return false; }
199207
static bool dataLayoutTypeAllocSize() { return false; }
208+
static bool dataLayoutTypeStoreSize() { return false; }
200209
static bool deferredCXXGlobalInit() { return false; }
201210
static bool ehCleanupFlags() { return false; }
202211
static bool ehCleanupScope() { return false; }
@@ -237,6 +246,7 @@ struct MissingFeatures {
237246
static bool objCBlocks() { return false; }
238247
static bool objCGC() { return false; }
239248
static bool objCLifetime() { return false; }
249+
static bool openCL() { return false; }
240250
static bool openMP() { return false; }
241251
static bool opTBAA() { return false; }
242252
static bool peepholeProtection() { return false; }
Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
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"
14+
#include "clang/CIR/MissingFeatures.h"
15+
16+
using namespace clang;
17+
using namespace clang::CIRGen;
18+
using namespace cir;
19+
20+
namespace {
21+
class 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+
LValue lvalue;
31+
mlir::Location loc;
32+
33+
public:
34+
AtomicInfo(CIRGenFunction &cgf, LValue &lvalue, mlir::Location loc)
35+
: cgf(cgf), loc(loc) {
36+
assert(!lvalue.isGlobalReg());
37+
ASTContext &ctx = cgf.getContext();
38+
if (lvalue.isSimple()) {
39+
atomicTy = lvalue.getType();
40+
if (auto *ty = atomicTy->getAs<AtomicType>())
41+
valueTy = ty->getValueType();
42+
else
43+
valueTy = atomicTy;
44+
evaluationKind = cgf.getEvaluationKind(valueTy);
45+
46+
TypeInfo valueTypeInfo = ctx.getTypeInfo(valueTy);
47+
TypeInfo atomicTypeInfo = ctx.getTypeInfo(atomicTy);
48+
uint64_t valueAlignInBits = valueTypeInfo.Align;
49+
uint64_t atomicAlignInBits = atomicTypeInfo.Align;
50+
valueSizeInBits = valueTypeInfo.Width;
51+
atomicSizeInBits = atomicTypeInfo.Width;
52+
assert(valueSizeInBits <= atomicSizeInBits);
53+
assert(valueAlignInBits <= atomicAlignInBits);
54+
55+
atomicAlign = ctx.toCharUnitsFromBits(atomicAlignInBits);
56+
valueAlign = ctx.toCharUnitsFromBits(valueAlignInBits);
57+
if (lvalue.getAlignment().isZero())
58+
lvalue.setAlignment(atomicAlign);
59+
60+
this->lvalue = lvalue;
61+
} else {
62+
assert(!cir::MissingFeatures::atomicInfo());
63+
cgf.cgm.errorNYI(loc, "AtomicInfo: non-simple lvalue");
64+
}
65+
66+
assert(!cir::MissingFeatures::atomicUseLibCall());
67+
}
68+
69+
QualType getValueType() const { return valueTy; }
70+
CharUnits getAtomicAlignment() const { return atomicAlign; }
71+
TypeEvaluationKind getEvaluationKind() const { return evaluationKind; }
72+
mlir::Value getAtomicPointer() const {
73+
if (lvalue.isSimple())
74+
return lvalue.getPointer();
75+
assert(!cir::MissingFeatures::atomicInfoGetAtomicPointer());
76+
return nullptr;
77+
}
78+
Address getAtomicAddress() const {
79+
mlir::Type elemTy;
80+
if (lvalue.isSimple()) {
81+
elemTy = lvalue.getAddress().getElementType();
82+
} else {
83+
assert(!cir::MissingFeatures::atomicInfoGetAtomicAddress());
84+
cgf.cgm.errorNYI(loc, "AtomicInfo::getAtomicAddress: non-simple lvalue");
85+
}
86+
return Address(getAtomicPointer(), elemTy, getAtomicAlignment());
87+
}
88+
89+
/// Is the atomic size larger than the underlying value type?
90+
///
91+
/// Note that the absence of padding does not mean that atomic
92+
/// objects are completely interchangeable with non-atomic
93+
/// objects: we might have promoted the alignment of a type
94+
/// without making it bigger.
95+
bool hasPadding() const { return (valueSizeInBits != atomicSizeInBits); }
96+
97+
bool emitMemSetZeroIfNecessary() const;
98+
99+
/// Copy an atomic r-value into atomic-layout memory.
100+
void emitCopyIntoMemory(RValue rvalue) const;
101+
102+
/// Project an l-value down to the value field.
103+
LValue projectValue() const {
104+
assert(lvalue.isSimple());
105+
Address addr = getAtomicAddress();
106+
if (hasPadding()) {
107+
cgf.cgm.errorNYI(loc, "AtomicInfo::projectValue: padding");
108+
}
109+
110+
assert(!cir::MissingFeatures::opTBAA());
111+
return LValue::makeAddr(addr, getValueType(), lvalue.getBaseInfo());
112+
}
113+
114+
private:
115+
bool requiresMemSetZero(mlir::Type ty) const;
116+
};
117+
} // namespace
118+
119+
/// Does a store of the given IR type modify the full expected width?
120+
static bool isFullSizeType(CIRGenModule &cgm, mlir::Type ty,
121+
uint64_t expectedSize) {
122+
return cgm.getDataLayout().getTypeStoreSize(ty) * 8 == expectedSize;
123+
}
124+
125+
/// Does the atomic type require memsetting to zero before initialization?
126+
///
127+
/// The IR type is provided as a way of making certain queries faster.
128+
bool AtomicInfo::requiresMemSetZero(mlir::Type ty) const {
129+
// If the atomic type has size padding, we definitely need a memset.
130+
if (hasPadding())
131+
return true;
132+
133+
// Otherwise, do some simple heuristics to try to avoid it:
134+
switch (getEvaluationKind()) {
135+
// For scalars and complexes, check whether the store size of the
136+
// type uses the full size.
137+
case cir::TEK_Scalar:
138+
return !isFullSizeType(cgf.cgm, ty, atomicSizeInBits);
139+
case cir::TEK_Complex:
140+
cgf.cgm.errorNYI(loc, "AtomicInfo::requiresMemSetZero: complex type");
141+
return false;
142+
143+
// Padding in structs has an undefined bit pattern. User beware.
144+
case cir::TEK_Aggregate:
145+
return false;
146+
}
147+
llvm_unreachable("bad evaluation kind");
148+
}
149+
150+
bool AtomicInfo::emitMemSetZeroIfNecessary() const {
151+
assert(lvalue.isSimple());
152+
Address addr = lvalue.getAddress();
153+
if (!requiresMemSetZero(addr.getElementType()))
154+
return false;
155+
156+
cgf.cgm.errorNYI(loc,
157+
"AtomicInfo::emitMemSetZeroIfNecessary: emit memset zero");
158+
return false;
159+
}
160+
161+
/// Copy an r-value into memory as part of storing to an atomic type.
162+
/// This needs to create a bit-pattern suitable for atomic operations.
163+
void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
164+
assert(lvalue.isSimple());
165+
166+
// If we have an r-value, the rvalue should be of the atomic type,
167+
// which means that the caller is responsible for having zeroed
168+
// any padding. Just do an aggregate copy of that type.
169+
if (rvalue.isAggregate()) {
170+
cgf.cgm.errorNYI("copying aggregate into atomic lvalue");
171+
return;
172+
}
173+
174+
// Okay, otherwise we're copying stuff.
175+
176+
// Zero out the buffer if necessary.
177+
emitMemSetZeroIfNecessary();
178+
179+
// Drill past the padding if present.
180+
LValue tempLValue = projectValue();
181+
182+
// Okay, store the rvalue in.
183+
if (rvalue.isScalar()) {
184+
cgf.emitStoreOfScalar(rvalue.getValue(), tempLValue, /*isInit=*/true);
185+
} else {
186+
cgf.cgm.errorNYI("copying complex into atomic lvalue");
187+
}
188+
}
189+
190+
RValue CIRGenFunction::emitAtomicExpr(AtomicExpr *e) {
191+
QualType atomicTy = e->getPtr()->getType()->getPointeeType();
192+
QualType memTy = atomicTy;
193+
if (const auto *ty = atomicTy->getAs<AtomicType>())
194+
memTy = ty->getValueType();
195+
196+
Address ptr = emitPointerWithAlignment(e->getPtr());
197+
198+
assert(!cir::MissingFeatures::openCL());
199+
if (e->getOp() == AtomicExpr::AO__c11_atomic_init) {
200+
LValue lvalue = makeAddrLValue(ptr, atomicTy);
201+
emitAtomicInit(e->getVal1(), lvalue);
202+
return RValue::get(nullptr);
203+
}
204+
205+
assert(!cir::MissingFeatures::atomicExpr());
206+
cgm.errorNYI(e->getSourceRange(), "atomic expr is NYI");
207+
return RValue::get(nullptr);
208+
}
209+
210+
void CIRGenFunction::emitAtomicInit(Expr *init, LValue dest) {
211+
AtomicInfo atomics(*this, dest, getLoc(init->getSourceRange()));
212+
213+
switch (atomics.getEvaluationKind()) {
214+
case cir::TEK_Scalar: {
215+
mlir::Value value = emitScalarExpr(init);
216+
atomics.emitCopyIntoMemory(RValue::get(value));
217+
return;
218+
}
219+
220+
case cir::TEK_Complex:
221+
cgm.errorNYI(init->getSourceRange(), "emitAtomicInit: complex type");
222+
return;
223+
224+
case cir::TEK_Aggregate:
225+
cgm.errorNYI(init->getSourceRange(), "emitAtomicInit: aggregate type");
226+
return;
227+
}
228+
229+
llvm_unreachable("bad evaluation kind");
230+
}

clang/lib/CIR/CodeGen/CIRGenExpr.cpp

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,11 @@ Address CIRGenFunction::emitPointerWithAlignment(const Expr *expr,
184184
if (const UnaryOperator *uo = dyn_cast<UnaryOperator>(expr)) {
185185
// TODO(cir): maybe we should use cir.unary for pointers here instead.
186186
if (uo->getOpcode() == UO_AddrOf) {
187-
cgm.errorNYI(expr->getSourceRange(), "emitPointerWithAlignment: unary &");
188-
return Address::invalid();
187+
LValue lv = emitLValue(uo->getSubExpr());
188+
if (baseInfo)
189+
*baseInfo = lv.getBaseInfo();
190+
assert(!cir::MissingFeatures::opTBAA());
191+
return lv.getAddress();
189192
}
190193
}
191194

clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1060,6 +1060,10 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
10601060

10611061
return maybePromoteBoolResult(resOp.getResult(), resTy);
10621062
}
1063+
1064+
mlir::Value VisitAtomicExpr(AtomicExpr *e) {
1065+
return cgf.emitAtomicExpr(e).getValue();
1066+
}
10631067
};
10641068

10651069
LValue ScalarExprEmitter::emitCompoundAssignLValue(

clang/lib/CIR/CodeGen/CIRGenFunction.h

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -926,6 +926,9 @@ class CIRGenFunction : public CIRGenTypeCache {
926926

927927
Address emitArrayToPointerDecay(const Expr *array);
928928

929+
RValue emitAtomicExpr(AtomicExpr *e);
930+
void emitAtomicInit(Expr *init, LValue dest);
931+
929932
AutoVarEmission emitAutoVarAlloca(const clang::VarDecl &d,
930933
mlir::OpBuilder::InsertPoint ip = {});
931934

@@ -1234,7 +1237,7 @@ class CIRGenFunction : public CIRGenTypeCache {
12341237
/// reasonable to just ignore the returned alignment when it isn't from an
12351238
/// explicit source.
12361239
Address emitPointerWithAlignment(const clang::Expr *expr,
1237-
LValueBaseInfo *baseInfo);
1240+
LValueBaseInfo *baseInfo = nullptr);
12381241

12391242
/// Emits a reference binding to the passed in expression.
12401243
RValue emitReferenceBindingToExpr(const Expr *e);

clang/lib/CIR/CodeGen/CIRGenTypes.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,20 @@ mlir::Type CIRGenTypes::convertType(QualType type) {
493493
break;
494494
}
495495

496+
case Type::Atomic: {
497+
QualType valueType = cast<AtomicType>(ty)->getValueType();
498+
resultType = convertTypeForMem(valueType);
499+
500+
// Pad out to the inflated size if necessary.
501+
uint64_t valueSize = astContext.getTypeSize(valueType);
502+
uint64_t atomicSize = astContext.getTypeSize(ty);
503+
if (valueSize != atomicSize) {
504+
cgm.errorNYI("convertType: atomic type value size != atomic size");
505+
}
506+
507+
break;
508+
}
509+
496510
default:
497511
cgm.errorNYI(SourceLocation(), "processing of type",
498512
type->getTypeClassName());

clang/lib/CIR/CodeGen/CIRGenValue.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,7 @@ class LValue {
190190
bool isSimple() const { return lvType == Simple; }
191191
bool isVectorElt() const { return lvType == VectorElt; }
192192
bool isBitField() const { return lvType == BitField; }
193+
bool isGlobalReg() const { return lvType == GlobalReg; }
193194
bool isVolatile() const { return quals.hasVolatile(); }
194195

195196
bool isVolatileQualified() const { return quals.hasVolatile(); }

clang/lib/CIR/CodeGen/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ get_property(dialect_libs GLOBAL PROPERTY MLIR_DIALECT_LIBS)
88

99
add_clang_library(clangCIR
1010
CIRGenerator.cpp
11+
CIRGenAtomic.cpp
1112
CIRGenBuilder.cpp
1213
CIRGenCall.cpp
1314
CIRGenClass.cpp

clang/lib/CIR/Dialect/IR/CIRDataLayout.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
#include "clang/CIR/Dialect/IR/CIRDataLayout.h"
2+
#include "clang/CIR/Dialect/IR/CIRTypes.h"
3+
#include "clang/CIR/MissingFeatures.h"
24

35
using namespace cir;
46

@@ -20,3 +22,21 @@ void CIRDataLayout::reset(mlir::DataLayoutSpecInterface spec) {
2022
bigEndian = str == mlir::DLTIDialect::kDataLayoutEndiannessBig;
2123
}
2224
}
25+
26+
// The implementation of this method is provided inline as it is particularly
27+
// well suited to constant folding when called on a specific Type subclass.
28+
llvm::TypeSize CIRDataLayout::getTypeSizeInBits(mlir::Type ty) const {
29+
assert(!cir::MissingFeatures::dataLayoutTypeIsSized());
30+
31+
if (auto recordTy = llvm::dyn_cast<cir::RecordType>(ty)) {
32+
// FIXME(cir): CIR record's data layout implementation doesn't do a good job
33+
// of handling unions particularities. We should have a separate union type.
34+
return recordTy.getTypeSizeInBits(layout, {});
35+
}
36+
37+
// FIXME(cir): This does not account for different address spaces, and relies
38+
// on CIR's data layout to give the proper ABI-specific type width.
39+
assert(!cir::MissingFeatures::addressSpace());
40+
41+
return llvm::TypeSize::getFixed(layout.getTypeSizeInBits(ty));
42+
}

0 commit comments

Comments
 (0)