1 //===--- CodeGenTypes.cpp - TBAA information for LLVM CodeGen -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the code that manages TBAA information and defines the TBAA policy
11 // for the optimizer to use. Relevant standards text includes:
12 //
13 //   C99 6.5p7
14 //   C++ [basic.lval] (p10 in n3126, p15 in some earlier versions)
15 //
16 //===----------------------------------------------------------------------===//
17 
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/Type.h"
29 using namespace clang;
30 using namespace CodeGen;
31 
32 CodeGenTBAA::CodeGenTBAA(ASTContext &Ctx, llvm::LLVMContext& VMContext,
33                          const CodeGenOptions &CGO,
34                          const LangOptions &Features, MangleContext &MContext)
35   : Context(Ctx), CodeGenOpts(CGO), Features(Features), MContext(MContext),
36     MDHelper(VMContext), Root(nullptr), Char(nullptr) {
37 }
38 
39 CodeGenTBAA::~CodeGenTBAA() {
40 }
41 
42 llvm::MDNode *CodeGenTBAA::getRoot() {
43   // Define the root of the tree. This identifies the tree, so that
44   // if our LLVM IR is linked with LLVM IR from a different front-end
45   // (or a different version of this front-end), their TBAA trees will
46   // remain distinct, and the optimizer will treat them conservatively.
47   if (!Root) {
48     if (Features.CPlusPlus)
49       Root = MDHelper.createTBAARoot("Simple C++ TBAA");
50     else
51       Root = MDHelper.createTBAARoot("Simple C/C++ TBAA");
52   }
53 
54   return Root;
55 }
56 
57 // For both scalar TBAA and struct-path aware TBAA, the scalar type has the
58 // same format: name, parent node, and offset.
59 llvm::MDNode *CodeGenTBAA::createTBAAScalarType(StringRef Name,
60                                                 llvm::MDNode *Parent) {
61   return MDHelper.createTBAAScalarTypeNode(Name, Parent);
62 }
63 
64 llvm::MDNode *CodeGenTBAA::getChar() {
65   // Define the root of the tree for user-accessible memory. C and C++
66   // give special powers to char and certain similar types. However,
67   // these special powers only cover user-accessible memory, and doesn't
68   // include things like vtables.
69   if (!Char)
70     Char = createTBAAScalarType("omnipotent char", getRoot());
71 
72   return Char;
73 }
74 
75 static bool TypeHasMayAlias(QualType QTy) {
76   // Tagged types have declarations, and therefore may have attributes.
77   if (const TagType *TTy = dyn_cast<TagType>(QTy))
78     return TTy->getDecl()->hasAttr<MayAliasAttr>();
79 
80   // Typedef types have declarations, and therefore may have attributes.
81   if (const TypedefType *TTy = dyn_cast<TypedefType>(QTy)) {
82     if (TTy->getDecl()->hasAttr<MayAliasAttr>())
83       return true;
84     // Also, their underlying types may have relevant attributes.
85     return TypeHasMayAlias(TTy->desugar());
86   }
87 
88   return false;
89 }
90 
91 /// Check if the given type is a valid base type to be used in access tags.
92 static bool isValidBaseType(QualType QTy) {
93   if (QTy->isReferenceType())
94     return false;
95   if (const RecordType *TTy = QTy->getAs<RecordType>()) {
96     const RecordDecl *RD = TTy->getDecl()->getDefinition();
97     // Incomplete types are not valid base access types.
98     if (!RD)
99       return false;
100     if (RD->hasFlexibleArrayMember())
101       return false;
102     // RD can be struct, union, class, interface or enum.
103     // For now, we only handle struct and class.
104     if (RD->isStruct() || RD->isClass())
105       return true;
106   }
107   return false;
108 }
109 
110 llvm::MDNode *CodeGenTBAA::getTypeInfo(QualType QTy) {
111   // At -O0 or relaxed aliasing, TBAA is not emitted for regular types.
112   if (CodeGenOpts.OptimizationLevel == 0 || CodeGenOpts.RelaxedAliasing)
113     return nullptr;
114 
115   // If the type has the may_alias attribute (even on a typedef), it is
116   // effectively in the general char alias class.
117   if (TypeHasMayAlias(QTy))
118     return getChar();
119 
120   // We need this function to not fall back to returning the "omnipotent char"
121   // type node for aggregate and union types. Otherwise, any dereference of an
122   // aggregate will result into the may-alias access descriptor, meaning all
123   // subsequent accesses to direct and indirect members of that aggregate will
124   // be considered may-alias too.
125   // TODO: Combine getTypeInfo() and getBaseTypeInfo() into a single function.
126   if (isValidBaseType(QTy))
127     return getBaseTypeInfo(QTy);
128 
129   const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
130   if (llvm::MDNode *N = MetadataCache[Ty])
131     return N;
132 
133   // Handle builtin types.
134   if (const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) {
135     switch (BTy->getKind()) {
136     // Character types are special and can alias anything.
137     // In C++, this technically only includes "char" and "unsigned char",
138     // and not "signed char". In C, it includes all three. For now,
139     // the risk of exploiting this detail in C++ seems likely to outweigh
140     // the benefit.
141     case BuiltinType::Char_U:
142     case BuiltinType::Char_S:
143     case BuiltinType::UChar:
144     case BuiltinType::SChar:
145       return getChar();
146 
147     // Unsigned types can alias their corresponding signed types.
148     case BuiltinType::UShort:
149       return getTypeInfo(Context.ShortTy);
150     case BuiltinType::UInt:
151       return getTypeInfo(Context.IntTy);
152     case BuiltinType::ULong:
153       return getTypeInfo(Context.LongTy);
154     case BuiltinType::ULongLong:
155       return getTypeInfo(Context.LongLongTy);
156     case BuiltinType::UInt128:
157       return getTypeInfo(Context.Int128Ty);
158 
159     // Treat all other builtin types as distinct types. This includes
160     // treating wchar_t, char16_t, and char32_t as distinct from their
161     // "underlying types".
162     default:
163       return MetadataCache[Ty] =
164         createTBAAScalarType(BTy->getName(Features), getChar());
165     }
166   }
167 
168   // C++1z [basic.lval]p10: "If a program attempts to access the stored value of
169   // an object through a glvalue of other than one of the following types the
170   // behavior is undefined: [...] a char, unsigned char, or std::byte type."
171   if (Ty->isStdByteType())
172     return MetadataCache[Ty] = getChar();
173 
174   // Handle pointers and references.
175   // TODO: Implement C++'s type "similarity" and consider dis-"similar"
176   // pointers distinct.
177   if (Ty->isPointerType() || Ty->isReferenceType())
178     return MetadataCache[Ty] = createTBAAScalarType("any pointer",
179                                                     getChar());
180 
181   // Enum types are distinct types. In C++ they have "underlying types",
182   // however they aren't related for TBAA.
183   if (const EnumType *ETy = dyn_cast<EnumType>(Ty)) {
184     // In C++ mode, types have linkage, so we can rely on the ODR and
185     // on their mangled names, if they're external.
186     // TODO: Is there a way to get a program-wide unique name for a
187     // decl with local linkage or no linkage?
188     if (!Features.CPlusPlus || !ETy->getDecl()->isExternallyVisible())
189       return MetadataCache[Ty] = getChar();
190 
191     SmallString<256> OutName;
192     llvm::raw_svector_ostream Out(OutName);
193     MContext.mangleTypeName(QualType(ETy, 0), Out);
194     return MetadataCache[Ty] = createTBAAScalarType(OutName, getChar());
195   }
196 
197   // For now, handle any other kind of type conservatively.
198   return MetadataCache[Ty] = getChar();
199 }
200 
201 TBAAAccessInfo CodeGenTBAA::getVTablePtrAccessInfo() {
202   return TBAAAccessInfo(createTBAAScalarType("vtable pointer", getRoot()));
203 }
204 
205 bool
206 CodeGenTBAA::CollectFields(uint64_t BaseOffset,
207                            QualType QTy,
208                            SmallVectorImpl<llvm::MDBuilder::TBAAStructField> &
209                              Fields,
210                            bool MayAlias) {
211   /* Things not handled yet include: C++ base classes, bitfields, */
212 
213   if (const RecordType *TTy = QTy->getAs<RecordType>()) {
214     const RecordDecl *RD = TTy->getDecl()->getDefinition();
215     if (RD->hasFlexibleArrayMember())
216       return false;
217 
218     // TODO: Handle C++ base classes.
219     if (const CXXRecordDecl *Decl = dyn_cast<CXXRecordDecl>(RD))
220       if (Decl->bases_begin() != Decl->bases_end())
221         return false;
222 
223     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
224 
225     unsigned idx = 0;
226     for (RecordDecl::field_iterator i = RD->field_begin(),
227          e = RD->field_end(); i != e; ++i, ++idx) {
228       uint64_t Offset = BaseOffset +
229                         Layout.getFieldOffset(idx) / Context.getCharWidth();
230       QualType FieldQTy = i->getType();
231       if (!CollectFields(Offset, FieldQTy, Fields,
232                          MayAlias || TypeHasMayAlias(FieldQTy)))
233         return false;
234     }
235     return true;
236   }
237 
238   /* Otherwise, treat whatever it is as a field. */
239   uint64_t Offset = BaseOffset;
240   uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity();
241   llvm::MDNode *TBAAType = MayAlias ? getChar() : getTypeInfo(QTy);
242   llvm::MDNode *TBAATag = getAccessTagInfo(TBAAAccessInfo(TBAAType));
243   Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag));
244   return true;
245 }
246 
247 llvm::MDNode *
248 CodeGenTBAA::getTBAAStructInfo(QualType QTy) {
249   const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
250 
251   if (llvm::MDNode *N = StructMetadataCache[Ty])
252     return N;
253 
254   SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields;
255   if (CollectFields(0, QTy, Fields, TypeHasMayAlias(QTy)))
256     return MDHelper.createTBAAStructNode(Fields);
257 
258   // For now, handle any other kind of type conservatively.
259   return StructMetadataCache[Ty] = nullptr;
260 }
261 
262 llvm::MDNode *CodeGenTBAA::getBaseTypeInfo(QualType QTy) {
263   if (!isValidBaseType(QTy))
264     return nullptr;
265 
266   const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
267   if (llvm::MDNode *N = BaseTypeMetadataCache[Ty])
268     return N;
269 
270   if (const RecordType *TTy = QTy->getAs<RecordType>()) {
271     const RecordDecl *RD = TTy->getDecl()->getDefinition();
272 
273     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
274     SmallVector <std::pair<llvm::MDNode*, uint64_t>, 4> Fields;
275     unsigned idx = 0;
276     for (RecordDecl::field_iterator i = RD->field_begin(),
277          e = RD->field_end(); i != e; ++i, ++idx) {
278       QualType FieldQTy = i->getType();
279       llvm::MDNode *FieldNode = isValidBaseType(FieldQTy) ?
280           getBaseTypeInfo(FieldQTy) : getTypeInfo(FieldQTy);
281       if (!FieldNode)
282         return BaseTypeMetadataCache[Ty] = nullptr;
283       Fields.push_back(std::make_pair(
284           FieldNode, Layout.getFieldOffset(idx) / Context.getCharWidth()));
285     }
286 
287     SmallString<256> OutName;
288     if (Features.CPlusPlus) {
289       // Don't use the mangler for C code.
290       llvm::raw_svector_ostream Out(OutName);
291       MContext.mangleTypeName(QualType(Ty, 0), Out);
292     } else {
293       OutName = RD->getName();
294     }
295     // Create the struct type node with a vector of pairs (offset, type).
296     return BaseTypeMetadataCache[Ty] =
297       MDHelper.createTBAAStructTypeNode(OutName, Fields);
298   }
299 
300   return BaseTypeMetadataCache[Ty] = nullptr;
301 }
302 
303 llvm::MDNode *CodeGenTBAA::getAccessTagInfo(TBAAAccessInfo Info) {
304   if (Info.isMayAlias())
305     Info = TBAAAccessInfo(getChar());
306 
307   if (!Info.AccessType)
308     return nullptr;
309 
310   if (!CodeGenOpts.StructPathTBAA)
311     Info = TBAAAccessInfo(Info.AccessType);
312 
313   llvm::MDNode *&N = AccessTagMetadataCache[Info];
314   if (N)
315     return N;
316 
317   if (!Info.BaseType) {
318     Info.BaseType = Info.AccessType;
319     assert(!Info.Offset && "Nonzero offset for an access with no base type!");
320   }
321   return N = MDHelper.createTBAAStructTagNode(Info.BaseType, Info.AccessType,
322                                               Info.Offset);
323 }
324 
325 TBAAAccessInfo CodeGenTBAA::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
326                                                  TBAAAccessInfo TargetInfo) {
327   if (SourceInfo.isMayAlias() || TargetInfo.isMayAlias())
328     return TBAAAccessInfo::getMayAliasInfo();
329   return TargetInfo;
330 }
331 
332 TBAAAccessInfo
333 CodeGenTBAA::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
334                                                  TBAAAccessInfo InfoB) {
335   if (InfoA == InfoB)
336     return InfoA;
337 
338   if (!InfoA || !InfoB)
339     return TBAAAccessInfo();
340 
341   if (InfoA.isMayAlias() || InfoB.isMayAlias())
342     return TBAAAccessInfo::getMayAliasInfo();
343 
344   // TODO: Implement the rest of the logic here. For example, two accesses
345   // with same final access types result in an access to an object of that final
346   // access type regardless of their base types.
347   return TBAAAccessInfo::getMayAliasInfo();
348 }
349