1 //===--- CodeGenTypes.cpp - TBAA information for LLVM CodeGen -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the code that manages TBAA information and defines the TBAA policy
11 // for the optimizer to use. Relevant standards text includes:
14 // C++ [basic.lval] (p10 in n3126, p15 in some earlier versions)
16 //===----------------------------------------------------------------------===//
18 #include "CodeGenTBAA.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/Mangle.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/Frontend/CodeGenOptions.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Metadata.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Type.h"
30 using namespace clang;
31 using namespace CodeGen;
33 CodeGenTBAA::CodeGenTBAA(ASTContext &Ctx, llvm::Module &M,
34 const CodeGenOptions &CGO,
35 const LangOptions &Features, MangleContext &MContext)
36 : Context(Ctx), Module(M), CodeGenOpts(CGO),
37 Features(Features), MContext(MContext), MDHelper(M.getContext()),
38 Root(nullptr), Char(nullptr)
41 CodeGenTBAA::~CodeGenTBAA() {
44 llvm::MDNode *CodeGenTBAA::getRoot() {
45 // Define the root of the tree. This identifies the tree, so that
46 // if our LLVM IR is linked with LLVM IR from a different front-end
47 // (or a different version of this front-end), their TBAA trees will
48 // remain distinct, and the optimizer will treat them conservatively.
50 if (Features.CPlusPlus)
51 Root = MDHelper.createTBAARoot("Simple C++ TBAA");
53 Root = MDHelper.createTBAARoot("Simple C/C++ TBAA");
59 llvm::MDNode *CodeGenTBAA::createScalarTypeNode(StringRef Name,
62 if (CodeGenOpts.NewStructPathTBAA) {
63 llvm::Metadata *Id = MDHelper.createString(Name);
64 return MDHelper.createTBAATypeNode(Parent, Size, Id);
66 return MDHelper.createTBAAScalarTypeNode(Name, Parent);
69 llvm::MDNode *CodeGenTBAA::getChar() {
70 // Define the root of the tree for user-accessible memory. C and C++
71 // give special powers to char and certain similar types. However,
72 // these special powers only cover user-accessible memory, and doesn't
73 // include things like vtables.
75 Char = createScalarTypeNode("omnipotent char", getRoot(), /* Size= */ 1);
80 static bool TypeHasMayAlias(QualType QTy) {
81 // Tagged types have declarations, and therefore may have attributes.
82 if (const TagType *TTy = dyn_cast<TagType>(QTy))
83 return TTy->getDecl()->hasAttr<MayAliasAttr>();
85 // Typedef types have declarations, and therefore may have attributes.
86 if (const TypedefType *TTy = dyn_cast<TypedefType>(QTy)) {
87 if (TTy->getDecl()->hasAttr<MayAliasAttr>())
89 // Also, their underlying types may have relevant attributes.
90 return TypeHasMayAlias(TTy->desugar());
96 /// Check if the given type is a valid base type to be used in access tags.
97 static bool isValidBaseType(QualType QTy) {
98 if (QTy->isReferenceType())
100 if (const RecordType *TTy = QTy->getAs<RecordType>()) {
101 const RecordDecl *RD = TTy->getDecl()->getDefinition();
102 // Incomplete types are not valid base access types.
105 if (RD->hasFlexibleArrayMember())
107 // RD can be struct, union, class, interface or enum.
108 // For now, we only handle struct and class.
109 if (RD->isStruct() || RD->isClass())
115 llvm::MDNode *CodeGenTBAA::getTypeInfoHelper(const Type *Ty) {
116 uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity();
118 // Handle builtin types.
119 if (const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) {
120 switch (BTy->getKind()) {
121 // Character types are special and can alias anything.
122 // In C++, this technically only includes "char" and "unsigned char",
123 // and not "signed char". In C, it includes all three. For now,
124 // the risk of exploiting this detail in C++ seems likely to outweigh
126 case BuiltinType::Char_U:
127 case BuiltinType::Char_S:
128 case BuiltinType::UChar:
129 case BuiltinType::SChar:
132 // Unsigned types can alias their corresponding signed types.
133 case BuiltinType::UShort:
134 return getTypeInfo(Context.ShortTy);
135 case BuiltinType::UInt:
136 return getTypeInfo(Context.IntTy);
137 case BuiltinType::ULong:
138 return getTypeInfo(Context.LongTy);
139 case BuiltinType::ULongLong:
140 return getTypeInfo(Context.LongLongTy);
141 case BuiltinType::UInt128:
142 return getTypeInfo(Context.Int128Ty);
144 // Treat all other builtin types as distinct types. This includes
145 // treating wchar_t, char16_t, and char32_t as distinct from their
146 // "underlying types".
148 return createScalarTypeNode(BTy->getName(Features), getChar(), Size);
152 // C++1z [basic.lval]p10: "If a program attempts to access the stored value of
153 // an object through a glvalue of other than one of the following types the
154 // behavior is undefined: [...] a char, unsigned char, or std::byte type."
155 if (Ty->isStdByteType())
158 // Handle pointers and references.
159 // TODO: Implement C++'s type "similarity" and consider dis-"similar"
160 // pointers distinct.
161 if (Ty->isPointerType() || Ty->isReferenceType())
162 return createScalarTypeNode("any pointer", getChar(), Size);
164 // Accesses to arrays are accesses to objects of their element types.
165 if (CodeGenOpts.NewStructPathTBAA && Ty->isArrayType())
166 return getTypeInfo(cast<ArrayType>(Ty)->getElementType());
168 // Enum types are distinct types. In C++ they have "underlying types",
169 // however they aren't related for TBAA.
170 if (const EnumType *ETy = dyn_cast<EnumType>(Ty)) {
171 // In C++ mode, types have linkage, so we can rely on the ODR and
172 // on their mangled names, if they're external.
173 // TODO: Is there a way to get a program-wide unique name for a
174 // decl with local linkage or no linkage?
175 if (!Features.CPlusPlus || !ETy->getDecl()->isExternallyVisible())
178 SmallString<256> OutName;
179 llvm::raw_svector_ostream Out(OutName);
180 MContext.mangleTypeName(QualType(ETy, 0), Out);
181 return createScalarTypeNode(OutName, getChar(), Size);
184 // For now, handle any other kind of type conservatively.
188 llvm::MDNode *CodeGenTBAA::getTypeInfo(QualType QTy) {
189 // At -O0 or relaxed aliasing, TBAA is not emitted for regular types.
190 if (CodeGenOpts.OptimizationLevel == 0 || CodeGenOpts.RelaxedAliasing)
193 // If the type has the may_alias attribute (even on a typedef), it is
194 // effectively in the general char alias class.
195 if (TypeHasMayAlias(QTy))
198 // We need this function to not fall back to returning the "omnipotent char"
199 // type node for aggregate and union types. Otherwise, any dereference of an
200 // aggregate will result into the may-alias access descriptor, meaning all
201 // subsequent accesses to direct and indirect members of that aggregate will
202 // be considered may-alias too.
203 // TODO: Combine getTypeInfo() and getBaseTypeInfo() into a single function.
204 if (isValidBaseType(QTy))
205 return getBaseTypeInfo(QTy);
207 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
208 if (llvm::MDNode *N = MetadataCache[Ty])
211 // Note that the following helper call is allowed to add new nodes to the
212 // cache, which invalidates all its previously obtained iterators. So we
213 // first generate the node for the type and then add that node to the cache.
214 llvm::MDNode *TypeNode = getTypeInfoHelper(Ty);
215 return MetadataCache[Ty] = TypeNode;
218 TBAAAccessInfo CodeGenTBAA::getVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
219 llvm::DataLayout DL(&Module);
220 unsigned Size = DL.getPointerTypeSize(VTablePtrType);
221 return TBAAAccessInfo(createScalarTypeNode("vtable pointer", getRoot(), Size),
226 CodeGenTBAA::CollectFields(uint64_t BaseOffset,
228 SmallVectorImpl<llvm::MDBuilder::TBAAStructField> &
231 /* Things not handled yet include: C++ base classes, bitfields, */
233 if (const RecordType *TTy = QTy->getAs<RecordType>()) {
234 const RecordDecl *RD = TTy->getDecl()->getDefinition();
235 if (RD->hasFlexibleArrayMember())
238 // TODO: Handle C++ base classes.
239 if (const CXXRecordDecl *Decl = dyn_cast<CXXRecordDecl>(RD))
240 if (Decl->bases_begin() != Decl->bases_end())
243 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
246 for (RecordDecl::field_iterator i = RD->field_begin(),
247 e = RD->field_end(); i != e; ++i, ++idx) {
248 uint64_t Offset = BaseOffset +
249 Layout.getFieldOffset(idx) / Context.getCharWidth();
250 QualType FieldQTy = i->getType();
251 if (!CollectFields(Offset, FieldQTy, Fields,
252 MayAlias || TypeHasMayAlias(FieldQTy)))
258 /* Otherwise, treat whatever it is as a field. */
259 uint64_t Offset = BaseOffset;
260 uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity();
261 llvm::MDNode *TBAAType = MayAlias ? getChar() : getTypeInfo(QTy);
262 llvm::MDNode *TBAATag = getAccessTagInfo(TBAAAccessInfo(TBAAType, Size));
263 Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag));
268 CodeGenTBAA::getTBAAStructInfo(QualType QTy) {
269 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
271 if (llvm::MDNode *N = StructMetadataCache[Ty])
274 SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields;
275 if (CollectFields(0, QTy, Fields, TypeHasMayAlias(QTy)))
276 return MDHelper.createTBAAStructNode(Fields);
278 // For now, handle any other kind of type conservatively.
279 return StructMetadataCache[Ty] = nullptr;
282 llvm::MDNode *CodeGenTBAA::getBaseTypeInfoHelper(const Type *Ty) {
283 if (auto *TTy = dyn_cast<RecordType>(Ty)) {
284 const RecordDecl *RD = TTy->getDecl()->getDefinition();
285 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
286 SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields;
287 for (FieldDecl *Field : RD->fields()) {
288 QualType FieldQTy = Field->getType();
289 llvm::MDNode *TypeNode = isValidBaseType(FieldQTy) ?
290 getBaseTypeInfo(FieldQTy) : getTypeInfo(FieldQTy);
292 return BaseTypeMetadataCache[Ty] = nullptr;
294 uint64_t BitOffset = Layout.getFieldOffset(Field->getFieldIndex());
295 uint64_t Offset = Context.toCharUnitsFromBits(BitOffset).getQuantity();
296 uint64_t Size = Context.getTypeSizeInChars(FieldQTy).getQuantity();
297 Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size,
301 SmallString<256> OutName;
302 if (Features.CPlusPlus) {
303 // Don't use the mangler for C code.
304 llvm::raw_svector_ostream Out(OutName);
305 MContext.mangleTypeName(QualType(Ty, 0), Out);
307 OutName = RD->getName();
310 if (CodeGenOpts.NewStructPathTBAA) {
311 llvm::MDNode *Parent = getChar();
312 uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity();
313 llvm::Metadata *Id = MDHelper.createString(OutName);
314 return MDHelper.createTBAATypeNode(Parent, Size, Id, Fields);
317 // Create the struct type node with a vector of pairs (offset, type).
318 SmallVector<std::pair<llvm::MDNode*, uint64_t>, 4> OffsetsAndTypes;
319 for (const auto &Field : Fields)
320 OffsetsAndTypes.push_back(std::make_pair(Field.Type, Field.Offset));
321 return MDHelper.createTBAAStructTypeNode(OutName, OffsetsAndTypes);
327 llvm::MDNode *CodeGenTBAA::getBaseTypeInfo(QualType QTy) {
328 if (!isValidBaseType(QTy))
331 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
332 if (llvm::MDNode *N = BaseTypeMetadataCache[Ty])
335 // Note that the following helper call is allowed to add new nodes to the
336 // cache, which invalidates all its previously obtained iterators. So we
337 // first generate the node for the type and then add that node to the cache.
338 llvm::MDNode *TypeNode = getBaseTypeInfoHelper(Ty);
339 return BaseTypeMetadataCache[Ty] = TypeNode;
342 llvm::MDNode *CodeGenTBAA::getAccessTagInfo(TBAAAccessInfo Info) {
343 assert(!Info.isIncomplete() && "Access to an object of an incomplete type!");
345 if (Info.isMayAlias())
346 Info = TBAAAccessInfo(getChar(), Info.Size);
348 if (!Info.AccessType)
351 if (!CodeGenOpts.StructPathTBAA)
352 Info = TBAAAccessInfo(Info.AccessType, Info.Size);
354 llvm::MDNode *&N = AccessTagMetadataCache[Info];
358 if (!Info.BaseType) {
359 Info.BaseType = Info.AccessType;
360 assert(!Info.Offset && "Nonzero offset for an access with no base type!");
362 if (CodeGenOpts.NewStructPathTBAA) {
363 return N = MDHelper.createTBAAAccessTag(Info.BaseType, Info.AccessType,
364 Info.Offset, Info.Size);
366 return N = MDHelper.createTBAAStructTagNode(Info.BaseType, Info.AccessType,
370 TBAAAccessInfo CodeGenTBAA::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
371 TBAAAccessInfo TargetInfo) {
372 if (SourceInfo.isMayAlias() || TargetInfo.isMayAlias())
373 return TBAAAccessInfo::getMayAliasInfo();
378 CodeGenTBAA::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
379 TBAAAccessInfo InfoB) {
383 if (!InfoA || !InfoB)
384 return TBAAAccessInfo();
386 if (InfoA.isMayAlias() || InfoB.isMayAlias())
387 return TBAAAccessInfo::getMayAliasInfo();
389 // TODO: Implement the rest of the logic here. For example, two accesses
390 // with same final access types result in an access to an object of that final
391 // access type regardless of their base types.
392 return TBAAAccessInfo::getMayAliasInfo();