clang 24.0.0git
CIRGenTBAA.cpp
Go to the documentation of this file.
1//===--- CIRGenTBAA.cpp - TBAA information for CIR CodeGen ----------------===//
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 is the code that manages TBAA information and defines the TBAA policy
10// for the optimizer to use. Relevant standards text includes:
11//
12// C99 6.5p7
13// C++ [basic.lval] (p10 in n3126, p15 in some earlier versions)
14//
15//===----------------------------------------------------------------------===//
16
17#include "CIRGenTBAA.h"
18#include "CIRGenCXXABI.h"
19
21#include "clang/AST/Mangle.h"
27#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/SmallString.h"
29
30using namespace clang;
31using namespace clang::CIRGen;
32
33CIRGenTBAA::CIRGenTBAA(mlir::MLIRContext &mlirContext, ASTContext &astContext,
34 CIRGenCXXABI &cxxABI, const CodeGenOptions &codeGenOpts,
35 const LangOptions &features)
36 : mlirContext(mlirContext), astContext(astContext), cxxABI(cxxABI),
37 codeGenOpts(codeGenOpts), features(features),
38 mangleCtx(ItaniumMangleContext::create(astContext,
39 astContext.getDiagnostics())) {}
40
41CIRGenTBAA::~CIRGenTBAA() = default;
42
43cir::TBAAScalarAttr
44CIRGenTBAA::createScalarTypeNode(StringRef name, cir::TBAAScalarAttr parent) {
45 // The new struct-path format would also record the size of the type.
47 return cir::TBAAScalarAttr::get(&mlirContext, name, parent);
48}
49
50cir::TBAAOmnipotentCharAttr CIRGenTBAA::getChar() {
51 return cir::TBAAOmnipotentCharAttr::get(&mlirContext);
52}
53
54cir::TBAAScalarAttr CIRGenTBAA::getAnyPtr(unsigned ptrDepth) {
55 assert(ptrDepth >= 1 && "Pointer must have some depth");
56
57 // Populate at least ptrDepth elements in anyPtrs. These are the type nodes
58 // for "any" pointers of increasing pointer depth, and are organized in the
59 // hierarchy: any pointer <- any p2 pointer <- any p3 pointer <- ...
60 if (anyPtrs.size() < ptrDepth) {
61 anyPtrs.reserve(ptrDepth);
62 if (anyPtrs.empty())
63 anyPtrs.push_back(createScalarTypeNode("any pointer", {}));
64 for (size_t idx = anyPtrs.size(); idx < ptrDepth; ++idx) {
65 std::string name = ("any p" + llvm::Twine(idx + 1) + " pointer").str();
66 anyPtrs.push_back(createScalarTypeNode(name, anyPtrs[idx - 1]));
67 }
68 }
69
70 return anyPtrs[ptrDepth - 1];
71}
72
73/// Returns the name of a scalar type descriptor.
75 if (auto scalar = mlir::dyn_cast<cir::TBAAScalarAttr>(typeDesc))
76 return scalar.getId();
77 assert(mlir::isa<cir::TBAAOmnipotentCharAttr>(typeDesc) &&
78 "expected a scalar type descriptor");
79 return "omnipotent char";
80}
81
82cir::TBAATypeDescriptorAttr
83CIRGenTBAA::getTypeInfoHelper(const clang::Type *ty) {
84 // Handle builtin types.
85 if (const auto *bty = dyn_cast<BuiltinType>(ty)) {
86 switch (bty->getKind()) {
87 // Character types are special and can alias anything.
88 // In C++, this technically only includes "char" and "unsigned char",
89 // and not "signed char". In C, it includes all three. For now,
90 // the risk of exploiting this detail in C++ seems likely to outweigh
91 // the benefit.
92 case BuiltinType::Char_U:
93 case BuiltinType::Char_S:
94 case BuiltinType::UChar:
95 case BuiltinType::SChar:
96 return getChar();
97
98 default:
99 break;
100 }
101
102 // Unsigned types can alias their corresponding signed types.
103 QualType signedTy = CodeGenUtils::getTBAASignedCounterpart(astContext, bty);
104 if (!signedTy.isNull())
105 return getTypeInfo(signedTy);
106
107 // Treat all other builtin types as distinct types. This includes
108 // treating wchar_t, char16_t, and char32_t as distinct from their
109 // "underlying types".
110 return createScalarTypeNode(bty->getName(features), {});
111 }
112
113 // C++1z [basic.lval]p10: "If a program attempts to access the stored value of
114 // an object through a glvalue of other than one of the following types the
115 // behavior is undefined: [...] a char, unsigned char, or std::byte type."
116 if (ty->isStdByteType())
117 return getChar();
118
119 // Handle pointers and references. See CodeGenTBAA::getTypeInfoHelper for the
120 // rationale: pointers are distinguished by their pointer depth and by their
121 // base pointee type, ignoring qualifiers and array types.
122 if (ty->isPointerType() || ty->isReferenceType()) {
123 if (!codeGenOpts.PointerTBAA)
124 return getAnyPtr();
125
126 unsigned ptrDepth = 0;
127 do {
128 ptrDepth++;
130 } while (ty->isPointerType());
131
132 // While there are no special rules in the standards regarding void pointers
133 // and strict aliasing, emitting distinct tags for void pointers break some
134 // common idioms and there is no good alternative to re-write the code
135 // without strict-aliasing violations.
136 if (ty->isVoidType())
137 return getAnyPtr(ptrDepth);
138
139 assert(!isa<VariableArrayType>(ty));
140 // When the underlying type is a builtin type, we compute the pointee type
141 // string recursively, which is implicitly more forgiving than the standards
142 // require.
143 SmallString<256> tyName;
144 if (isa<BuiltinType>(ty)) {
145 tyName = getTypeDescriptorName(getTypeInfoHelper(ty));
146 } else {
147 // Be conservative if the type isn't a RecordType. We are specifically
148 // required to do this for member pointers until we implement the
149 // similar-types rule.
150 const auto *rt = ty->getAsCanonical<RecordType>();
151 if (!rt)
152 return getAnyPtr(ptrDepth);
153
154 // For unnamed structs or unions C's compatible types rule applies. Two
155 // compatible types in different compilation units can have different
156 // mangled names, meaning the metadata emitted below would incorrectly
157 // mark them as no-alias. Use AnyPtr for such types in both C and C++, as
158 // C and C++ types may be visible when doing LTO.
159 if (!rt->getDecl()->getDeclName())
160 return getAnyPtr(ptrDepth);
161
162 // For non-builtin types use the mangled name of the canonical type.
163 llvm::raw_svector_ostream tyOut(tyName);
164 mangleCtx->mangleCanonicalTypeName(QualType(ty, 0), tyOut);
165 }
166
167 SmallString<256> outName("p");
168 outName += std::to_string(ptrDepth);
169 outName += " ";
170 outName += tyName;
171 return createScalarTypeNode(outName, getAnyPtr(ptrDepth));
172 }
173
174 // Accesses to matrix types are accesses to objects of their element types.
175 if (const auto *mty = dyn_cast<MatrixType>(ty)) {
176 assert(isa<ConstantMatrixType>(ty) &&
177 "only ConstantMatrixType should reach CodeGen");
178 return getTypeInfo(mty->getElementType());
179 }
180
181 // Accesses to complex types are accesses to objects of their element types.
182 if (const auto *cty = dyn_cast<ComplexType>(ty))
183 return getTypeInfo(cty->getElementType());
184
185 // Enum types are distinct types. In C++ they have "underlying types",
186 // however they aren't related for TBAA.
187 if (const auto *ety = dyn_cast<EnumType>(ty)) {
188 const EnumDecl *ed = ety->getDecl()->getDefinitionOrSelf();
189 if (!features.CPlusPlus)
190 return getTypeInfo(ed->getIntegerType());
191
192 // In C++ mode, types have linkage, so we can rely on the ODR and
193 // on their mangled names, if they're external.
194 if (!ed->isExternallyVisible())
195 return getChar();
196
197 SmallString<256> outName;
198 llvm::raw_svector_ostream out(outName);
199 cxxABI.getMangleContext().mangleCanonicalTypeName(QualType(ety, 0), out);
200 return createScalarTypeNode(outName, {});
201 }
202
203 if (const auto *eit = dyn_cast<BitIntType>(ty)) {
204 SmallString<256> outName;
205 llvm::raw_svector_ostream out(outName);
206 // Don't specify signed/unsigned since integer types can alias despite sign
207 // differences.
208 out << "_BitInt(" << eit->getNumBits() << ')';
209 return createScalarTypeNode(outName, {});
210 }
211
212 // For now, handle any other kind of type conservatively.
213 return getChar();
214}
215
217 // If the type has the may_alias attribute (even on a typedef), it is
218 // effectively in the general char alias class.
220 return getChar();
221
222 // We need this function to not fall back to returning the "omnipotent char"
223 // type node for aggregate and union types. Otherwise, any dereference of an
224 // aggregate will result into the may-alias access descriptor, meaning all
225 // subsequent accesses to direct and indirect members of that aggregate will
226 // be considered may-alias too.
228 return getValidBaseTypeInfo(qty);
229
230 const clang::Type *ty = astContext.getCanonicalType(qty).getTypePtr();
231 if (cir::TBAATypeDescriptorAttr typeDesc = metadataCache.lookup(ty))
232 return typeDesc;
233
234 // The helper may add new entries to the cache, so compute the type
235 // descriptor before inserting it.
236 cir::TBAATypeDescriptorAttr typeDesc = getTypeInfoHelper(ty);
237 return metadataCache[ty] = typeDesc;
238}
239
241 // Pointee values may have incomplete types, but they shall never be
242 // dereferenced.
243 if (accessType->isIncompleteType())
245
246 if (CodeGenUtils::typeHasMayAlias(accessType))
248
249 uint64_t size = astContext.getTypeSizeInChars(accessType).getQuantity();
250 return TBAAAccessInfo(getTypeInfo(accessType), size);
251}
252
254CIRGenTBAA::getBaseTypeInfoHelper(const clang::Type *ty) {
255 const auto *rt = dyn_cast<RecordType>(ty);
256 if (!rt)
257 return {};
258
259 const RecordDecl *rd = rt->getDecl()->getDefinition();
260 const ASTRecordLayout &layout = astContext.getASTRecordLayout(rd);
262 if (const auto *cxxrd = dyn_cast<CXXRecordDecl>(rd)) {
263 // Handle C++ base classes. Non-virtual bases can treated a kind of
264 // field. Virtual bases are more complex and omitted.
265 for (const CXXBaseSpecifier &base : cxxrd->bases()) {
266 if (base.isVirtual())
267 continue;
268 QualType baseQTy = base.getType();
269 const CXXRecordDecl *baseRD = baseQTy->getAsCXXRecordDecl();
270 if (baseRD->isEmpty())
271 continue;
274 ? getValidBaseTypeInfo(baseQTy)
275 : getTypeInfo(baseQTy);
276 if (!typeDesc)
277 return {};
278 uint64_t offset = layout.getBaseClassOffset(baseRD).getQuantity();
279 fields.push_back(
280 cir::TBAAMemberAttr::get(&mlirContext, typeDesc, offset));
281 }
282 // The order in which base class subobjects are allocated is unspecified,
283 // so may differ from declaration order. In particular, Itanium ABI will
284 // allocate a primary base first. Since we exclude empty subobjects, the
285 // objects are not overlapping and their offsets are unique.
286 llvm::sort(fields, [](cir::TBAAMemberAttr a, cir::TBAAMemberAttr b) {
287 return a.getOffset() < b.getOffset();
288 });
289 }
290
291 for (FieldDecl *field : rd->fields()) {
292 if (field->isZeroSize(astContext) || field->isUnnamedBitField())
293 continue;
294 QualType fieldQTy = field->getType();
295 cir::TBAATypeDescriptorAttr typeDesc =
297 ? getValidBaseTypeInfo(fieldQTy)
298 : getTypeInfo(fieldQTy);
299 if (!typeDesc)
300 return {};
301
302 uint64_t bitOffset = layout.getFieldOffset(field->getFieldIndex());
303 uint64_t offset = astContext.toCharUnitsFromBits(bitOffset).getQuantity();
304 fields.push_back(cir::TBAAMemberAttr::get(&mlirContext, typeDesc, offset));
305 }
306
307 SmallString<256> outName;
308 if (features.CPlusPlus) {
309 // Don't use the mangler for C code.
310 llvm::raw_svector_ostream out(outName);
311 cxxABI.getMangleContext().mangleCanonicalTypeName(QualType(ty, 0), out);
312 } else {
313 outName = rd->getName();
314 }
315
317 return cir::TBAAStructAttr::get(&mlirContext, outName, fields);
318}
319
320cir::TBAATypeDescriptorAttr CIRGenTBAA::getValidBaseTypeInfo(QualType qty) {
321 assert(CodeGenUtils::isValidTBAABaseType(qty) && "Must be a valid base type");
322
323 const clang::Type *ty = astContext.getCanonicalType(qty).getTypePtr();
324
325 // A null attribute is a valid value in the cache, so use find rather than
326 // lookup.
327 auto it = baseTypeMetadataCache.find(ty);
328 if (it != baseTypeMetadataCache.end())
329 return it->second;
330
331 // First calculate the type descriptor, before recomputing the insertion
332 // point, as the helper can recursively call us.
333 cir::TBAATypeDescriptorAttr typeDesc = getBaseTypeInfoHelper(ty);
334 [[maybe_unused]] auto inserted = baseTypeMetadataCache.insert({ty, typeDesc});
335 assert(inserted.second && "BaseType metadata was already inserted");
336
337 return typeDesc;
338}
339
344
346 assert(!info.isIncomplete() && "Access to an object of an incomplete type!");
347
348 if (info.isMayAlias())
349 info = TBAAAccessInfo(getChar(), info.size);
350
351 // Only scalar accesses carry access tags.
352 if (!info.accessType || mlir::isa<cir::TBAAStructAttr>(info.accessType))
353 return {};
354
355 if (!codeGenOpts.StructPathTBAA)
356 info = TBAAAccessInfo(info.accessType, info.size);
357
358 if (!info.baseType) {
359 info.baseType = info.accessType;
360 assert(!info.offset && "Nonzero offset for an access with no base type!");
361 }
362
364 return cir::TBAATagAttr::get(&mlirContext, info.baseType, info.accessType,
365 info.offset);
366}
367
369 TBAAAccessInfo targetInfo) {
370 if (sourceInfo.isMayAlias() || targetInfo.isMayAlias())
372 return targetInfo;
373}
374
377 TBAAAccessInfo infoB) {
378 if (infoA == infoB)
379 return infoA;
380
381 if (!infoA || !infoB)
382 return TBAAAccessInfo();
383
384 if (infoA.isMayAlias() || infoB.isMayAlias())
386
387 // TODO: Implement the rest of the logic here. For example, two accesses
388 // with same final access types result in an access to an object of that final
389 // access type regardless of their base types.
391}
Defines the clang::ASTContext interface.
static StringRef getTypeDescriptorName(cir::TBAATypeDescriptorAttr typeDesc)
Returns the name of a scalar type descriptor.
Base class of the TBAA type descriptor attributes.
Definition CIRAttrs.h:48
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:246
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Implements C++ ABI-specific code generation functions.
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo infoA, TBAAAccessInfo infoB)
Returns the merged TBAA information for the purpose of conditional operator.
cir::TBAATypeDescriptorAttr getTypeInfo(clang::QualType qty)
Returns the type descriptor used to describe accesses to objects of the given type.
cir::TBAATagAttr getAccessTagInfo(TBAAAccessInfo info)
Returns the access tag for the given memory access, or null if the access has no TBAA information.
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo sourceInfo, TBAAAccessInfo targetInfo)
Returns the merged TBAA information for the purpose of type casts.
TBAAAccessInfo getAccessInfo(clang::QualType accessType)
Returns the TBAA information that describes an access to an object of the given type.
CIRGenTBAA(mlir::MLIRContext &mlirContext, clang::ASTContext &astContext, CIRGenCXXABI &cxxABI, const clang::CodeGenOptions &codeGenOpts, const clang::LangOptions &features)
cir::TBAATypeDescriptorAttr getBaseTypeInfo(clang::QualType qty)
Returns the type descriptor that describes the given base access type, or null if the type is not sui...
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1196
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4365
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
bool isExternallyVisible() const
Definition Decl.h:435
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
Represents a struct/union/class.
Definition Decl.h:4506
field_range fields() const
Definition Decl.h:4709
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4690
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9306
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isPointerType() const
Definition TypeBase.h:8917
bool isReferenceType() const
Definition TypeBase.h:8941
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9490
bool isStdByteType() const
Definition Type.cpp:3472
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2678
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3003
Defines the clang::TargetInfo interface.
bool typeHasMayAlias(QualType QTy)
Returns true if accesses to objects of type QTy are in the general char alias class because of a may_...
Definition TBAAUtils.cpp:16
QualType getTBAASignedCounterpart(const ASTContext &Ctx, const BuiltinType *BTy)
Returns the signed type whose TBAA type node an access to the unsigned builtin type BTy uses,...
Definition TBAAUtils.cpp:55
bool isValidTBAABaseType(QualType QTy)
Returns true if QTy is a valid base type to be used in TBAA access tags.
Definition TBAAUtils.cpp:40
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
static bool tbaaNewStructPath()
Describes a memory access in terms of TBAA.
Definition CIRGenTBAA.h:44
static TBAAAccessInfo getIncompleteInfo()
Definition CIRGenTBAA.h:69
static TBAAAccessInfo getMayAliasInfo()
Definition CIRGenTBAA.h:62