| 1 |
//===-- CodeGenTBAA.cpp - TBAA information for LLVM 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 "CodeGenTBAA.h" |
| 18 |
#include "ABIInfoImpl.h" |
| 19 |
#include "CGCXXABI.h" |
| 20 |
#include "CGRecordLayout.h" |
| 21 |
#include "CodeGenTypes.h" |
| 22 |
#include "clang/AST/ASTContext.h" |
| 23 |
#include "clang/AST/Attr.h" |
| 24 |
#include "clang/AST/Mangle.h" |
| 25 |
#include "clang/AST/RecordLayout.h" |
| 26 |
#include "clang/Basic/CodeGenOptions.h" |
| 27 |
#include "clang/Basic/TargetInfo.h" |
| 28 |
#include "llvm/IR/LLVMContext.h" |
| 29 |
#include "llvm/IR/Metadata.h" |
| 30 |
#include "llvm/IR/Module.h" |
| 31 |
#include "llvm/IR/Type.h" |
| 32 |
#include "llvm/Support/Debug.h" |
| 33 |
using namespace clang; |
| 34 |
using namespace CodeGen; |
| 35 |
|
| 36 |
CodeGenTBAA::CodeGenTBAA(ASTContext &Ctx, CodeGenTypes &CGTypes, |
| 37 |
llvm::Module &M, const CodeGenOptions &CGO, |
| 38 |
const LangOptions &Features) |
| 39 |
: Context(Ctx), CGTypes(CGTypes), Module(M), CodeGenOpts(CGO), |
| 40 |
Features(Features), |
| 41 |
MangleCtx(ItaniumMangleContext::create(Ctx, Ctx.getDiagnostics())), |
| 42 |
MDHelper(M.getContext()), Root(nullptr), Char(nullptr) {} |
| 43 |
|
| 44 |
CodeGenTBAA::~CodeGenTBAA() { |
| 45 |
} |
| 46 |
|
| 47 |
llvm::MDNode *CodeGenTBAA::getRoot() { |
| 48 |
// Define the root of the tree. This identifies the tree, so that |
| 49 |
// if our LLVM IR is linked with LLVM IR from a different front-end |
| 50 |
// (or a different version of this front-end), their TBAA trees will |
| 51 |
// remain distinct, and the optimizer will treat them conservatively. |
| 52 |
if (!Root) { |
| 53 |
if (Features.CPlusPlus) |
| 54 |
Root = MDHelper.createTBAARoot("Simple C++ TBAA"); |
| 55 |
else |
| 56 |
Root = MDHelper.createTBAARoot("Simple C/C++ TBAA"); |
| 57 |
} |
| 58 |
|
| 59 |
return Root; |
| 60 |
} |
| 61 |
|
| 62 |
llvm::MDNode *CodeGenTBAA::createScalarTypeNode(StringRef Name, |
| 63 |
llvm::MDNode *Parent, |
| 64 |
uint64_t Size) { |
| 65 |
if (CodeGenOpts.NewStructPathTBAA) { |
| 66 |
llvm::Metadata *Id = MDHelper.createString(Name); |
| 67 |
return MDHelper.createTBAATypeNode(Parent, Size, Id); |
| 68 |
} |
| 69 |
return MDHelper.createTBAAScalarTypeNode(Name, Parent); |
| 70 |
} |
| 71 |
|
| 72 |
llvm::MDNode *CodeGenTBAA::getChar() { |
| 73 |
// Define the root of the tree for user-accessible memory. C and C++ |
| 74 |
// give special powers to char and certain similar types. However, |
| 75 |
// these special powers only cover user-accessible memory, and doesn't |
| 76 |
// include things like vtables. |
| 77 |
if (!Char) |
| 78 |
Char = createScalarTypeNode("omnipotent char", getRoot(), /* Size= */ 1); |
| 79 |
|
| 80 |
return Char; |
| 81 |
} |
| 82 |
|
| 83 |
llvm::MDNode *CodeGenTBAA::getAnyPtr(unsigned PtrDepth) { |
| 84 |
assert(PtrDepth >= 1 && "Pointer must have some depth"); |
| 85 |
|
| 86 |
// Populate at least PtrDepth elements in AnyPtrs. These are the type nodes |
| 87 |
// for "any" pointers of increasing pointer depth, and are organized in the |
| 88 |
// hierarchy: any pointer <- any p2 pointer <- any p3 pointer <- ... |
| 89 |
// |
| 90 |
// Note that AnyPtrs[Idx] is actually the node for pointer depth (Idx+1), |
| 91 |
// since there is no node for pointer depth 0. |
| 92 |
// |
| 93 |
// These "any" pointer type nodes are used in pointer TBAA. The type node of |
| 94 |
// a concrete pointer type has the "any" pointer type node of appropriate |
| 95 |
// pointer depth as its parent. The "any" pointer type nodes are also used |
| 96 |
// directly for accesses to void pointers, or to specific pointers that we |
| 97 |
// conservatively do not distinguish in pointer TBAA (e.g. pointers to |
| 98 |
// members). Essentially, this establishes that e.g. void** can alias with |
| 99 |
// any type that can unify with T**, ignoring things like qualifiers. Here, T |
| 100 |
// is a variable that represents an arbitrary type, including pointer types. |
| 101 |
// As such, each depth is naturally a subtype of the previous depth, and thus |
| 102 |
// transitively of all previous depths. |
| 103 |
if (AnyPtrs.size() < PtrDepth) { |
| 104 |
AnyPtrs.reserve(PtrDepth); |
| 105 |
auto Size = Module.getDataLayout().getPointerSize(); |
| 106 |
// Populate first element. |
| 107 |
if (AnyPtrs.empty()) |
| 108 |
AnyPtrs.push_back(createScalarTypeNode("any pointer", getChar(), Size)); |
| 109 |
// Populate further elements. |
| 110 |
for (size_t Idx = AnyPtrs.size(); Idx < PtrDepth; ++Idx) { |
| 111 |
auto Name = ("any p" + llvm::Twine(Idx + 1) + " pointer").str(); |
| 112 |
AnyPtrs.push_back(createScalarTypeNode(Name, AnyPtrs[Idx - 1], Size)); |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
return AnyPtrs[PtrDepth - 1]; |
| 117 |
} |
| 118 |
|
| 119 |
static bool TypeHasMayAlias(QualType QTy) { |
| 120 |
// Tagged types have declarations, and therefore may have attributes. |
| 121 |
if (auto *TD = QTy->getAsTagDecl()) |
| 122 |
if (TD->hasAttr<MayAliasAttr>()) |
| 123 |
return true; |
| 124 |
|
| 125 |
// Also look for may_alias as a declaration attribute on a typedef. |
| 126 |
// FIXME: We should follow GCC and model may_alias as a type attribute |
| 127 |
// rather than as a declaration attribute. |
| 128 |
while (auto *TT = QTy->getAs<TypedefType>()) { |
| 129 |
if (TT->getDecl()->hasAttr<MayAliasAttr>()) |
| 130 |
return true; |
| 131 |
QTy = TT->desugar(); |
| 132 |
} |
| 133 |
|
| 134 |
// Also consider an array type as may_alias when its element type (at |
| 135 |
// any level) is marked as such. |
| 136 |
if (auto *ArrayTy = QTy->getAsArrayTypeUnsafe()) |
| 137 |
if (TypeHasMayAlias(ArrayTy->getElementType())) |
| 138 |
return true; |
| 139 |
|
| 140 |
return false; |
| 141 |
} |
| 142 |
|
| 143 |
/// Check if the given type is a valid base type to be used in access tags. |
| 144 |
static bool isValidBaseType(QualType QTy) { |
| 145 |
if (const auto *RD = QTy->getAsRecordDecl()) { |
| 146 |
// Incomplete types are not valid base access types. |
| 147 |
if (!RD->isCompleteDefinition()) |
| 148 |
return false; |
| 149 |
if (RD->hasFlexibleArrayMember()) |
| 150 |
return false; |
| 151 |
// RD can be struct, union, class, interface or enum. |
| 152 |
// For now, we only handle struct and class. |
| 153 |
if (RD->isStruct() || RD->isClass()) |
| 154 |
return true; |
| 155 |
} |
| 156 |
return false; |
| 157 |
} |
| 158 |
|
| 159 |
llvm::MDNode *CodeGenTBAA::getTypeInfoHelper(const Type *Ty) { |
| 160 |
uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity(); |
| 161 |
|
| 162 |
// Handle builtin types. |
| 163 |
if (const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) { |
| 164 |
switch (BTy->getKind()) { |
| 165 |
// Character types are special and can alias anything. |
| 166 |
// In C++, this technically only includes "char" and "unsigned char", |
| 167 |
// and not "signed char". In C, it includes all three. For now, |
| 168 |
// the risk of exploiting this detail in C++ seems likely to outweigh |
| 169 |
// the benefit. |
| 170 |
case BuiltinType::Char_U: |
| 171 |
case BuiltinType::Char_S: |
| 172 |
case BuiltinType::UChar: |
| 173 |
case BuiltinType::SChar: |
| 174 |
return getChar(); |
| 175 |
|
| 176 |
// Unsigned types can alias their corresponding signed types. |
| 177 |
case BuiltinType::UShort: |
| 178 |
return getTypeInfo(Context.ShortTy); |
| 179 |
case BuiltinType::UInt: |
| 180 |
return getTypeInfo(Context.IntTy); |
| 181 |
case BuiltinType::ULong: |
| 182 |
return getTypeInfo(Context.LongTy); |
| 183 |
case BuiltinType::ULongLong: |
| 184 |
return getTypeInfo(Context.LongLongTy); |
| 185 |
case BuiltinType::UInt128: |
| 186 |
return getTypeInfo(Context.Int128Ty); |
| 187 |
|
| 188 |
case BuiltinType::UShortFract: |
| 189 |
return getTypeInfo(Context.ShortFractTy); |
| 190 |
case BuiltinType::UFract: |
| 191 |
return getTypeInfo(Context.FractTy); |
| 192 |
case BuiltinType::ULongFract: |
| 193 |
return getTypeInfo(Context.LongFractTy); |
| 194 |
|
| 195 |
case BuiltinType::SatUShortFract: |
| 196 |
return getTypeInfo(Context.SatShortFractTy); |
| 197 |
case BuiltinType::SatUFract: |
| 198 |
return getTypeInfo(Context.SatFractTy); |
| 199 |
case BuiltinType::SatULongFract: |
| 200 |
return getTypeInfo(Context.SatLongFractTy); |
| 201 |
|
| 202 |
case BuiltinType::UShortAccum: |
| 203 |
return getTypeInfo(Context.ShortAccumTy); |
| 204 |
case BuiltinType::UAccum: |
| 205 |
return getTypeInfo(Context.AccumTy); |
| 206 |
case BuiltinType::ULongAccum: |
| 207 |
return getTypeInfo(Context.LongAccumTy); |
| 208 |
|
| 209 |
case BuiltinType::SatUShortAccum: |
| 210 |
return getTypeInfo(Context.SatShortAccumTy); |
| 211 |
case BuiltinType::SatUAccum: |
| 212 |
return getTypeInfo(Context.SatAccumTy); |
| 213 |
case BuiltinType::SatULongAccum: |
| 214 |
return getTypeInfo(Context.SatLongAccumTy); |
| 215 |
|
| 216 |
// Treat all other builtin types as distinct types. This includes |
| 217 |
// treating wchar_t, char16_t, and char32_t as distinct from their |
| 218 |
// "underlying types". |
| 219 |
default: |
| 220 |
return createScalarTypeNode(BTy->getName(Features), getChar(), Size); |
| 221 |
} |
| 222 |
} |
| 223 |
|
| 224 |
// C++1z [basic.lval]p10: "If a program attempts to access the stored value of |
| 225 |
// an object through a glvalue of other than one of the following types the |
| 226 |
// behavior is undefined: [...] a char, unsigned char, or std::byte type." |
| 227 |
if (Ty->isStdByteType()) |
| 228 |
return getChar(); |
| 229 |
|
| 230 |
// Handle pointers and references. |
| 231 |
// |
| 232 |
// C has a very strict rule for pointer aliasing. C23 6.7.6.1p2: |
| 233 |
// For two pointer types to be compatible, both shall be identically |
| 234 |
// qualified and both shall be pointers to compatible types. |
| 235 |
// |
| 236 |
// This rule is impractically strict; we want to at least ignore CVR |
| 237 |
// qualifiers. Distinguishing by CVR qualifiers would make it UB to |
| 238 |
// e.g. cast a `char **` to `const char * const *` and dereference it, |
| 239 |
// which is too common and useful to invalidate. C++'s similar types |
| 240 |
// rule permits qualifier differences in these nested positions; in fact, |
| 241 |
// C++ even allows that cast as an implicit conversion. |
| 242 |
// |
| 243 |
// Other qualifiers could theoretically be distinguished, especially if |
| 244 |
// they involve a significant representation difference. We don't |
| 245 |
// currently do so, however. |
| 246 |
if (Ty->isPointerType() || Ty->isReferenceType()) { |
| 247 |
if (!CodeGenOpts.PointerTBAA) |
| 248 |
return getAnyPtr(); |
| 249 |
// C++ [basic.lval]p11 permits objects to accessed through an l-value of |
| 250 |
// similar type. Two types are similar under C++ [conv.qual]p2 if the |
| 251 |
// decomposition of the types into pointers, member pointers, and arrays has |
| 252 |
// the same structure when ignoring cv-qualifiers at each level of the |
| 253 |
// decomposition. Meanwhile, C makes T(*)[] and T(*)[N] compatible, which |
| 254 |
// would really complicate any attempt to distinguish pointers to arrays by |
| 255 |
// their bounds. It's simpler, and much easier to explain to users, to |
| 256 |
// simply treat all pointers to arrays as pointers to their element type for |
| 257 |
// aliasing purposes. So when creating a TBAA tag for a pointer type, we |
| 258 |
// recursively ignore both qualifiers and array types when decomposing the |
| 259 |
// pointee type. The only meaningful remaining structure is the number of |
| 260 |
// pointer types we encountered along the way, so we just produce the tag |
| 261 |
// "p<depth> <base type tag>". If we do find a member pointer type, for now |
| 262 |
// we just conservatively bail out with AnyPtr (below) rather than trying to |
| 263 |
// create a tag that honors the similar-type rules while still |
| 264 |
// distinguishing different kinds of member pointer. |
| 265 |
unsigned PtrDepth = 0; |
| 266 |
do { |
| 267 |
PtrDepth++; |
| 268 |
Ty = Ty->getPointeeType()->getBaseElementTypeUnsafe(); |
| 269 |
} while (Ty->isPointerType()); |
| 270 |
|
| 271 |
// While there are no special rules in the standards regarding void pointers |
| 272 |
// and strict aliasing, emitting distinct tags for void pointers break some |
| 273 |
// common idioms and there is no good alternative to re-write the code |
| 274 |
// without strict-aliasing violations. |
| 275 |
if (Ty->isVoidType()) |
| 276 |
return getAnyPtr(PtrDepth); |
| 277 |
|
| 278 |
assert(!isa<VariableArrayType>(Ty)); |
| 279 |
// When the underlying type is a builtin type, we compute the pointee type |
| 280 |
// string recursively, which is implicitly more forgiving than the standards |
| 281 |
// require. Effectively, we are turning the question "are these types |
| 282 |
// compatible/similar" into "are accesses to these types allowed to alias". |
| 283 |
// In both C and C++, the latter question has special carve-outs for |
| 284 |
// signedness mismatches that only apply at the top level. As a result, we |
| 285 |
// are allowing e.g. `int *` l-values to access `unsigned *` objects. |
| 286 |
SmallString<256> TyName; |
| 287 |
if (isa<BuiltinType>(Ty)) { |
| 288 |
llvm::MDNode *ScalarMD = getTypeInfoHelper(Ty); |
| 289 |
StringRef Name = |
| 290 |
cast<llvm::MDString>( |
| 291 |
ScalarMD->getOperand(CodeGenOpts.NewStructPathTBAA ? 2 : 0)) |
| 292 |
->getString(); |
| 293 |
TyName = Name; |
| 294 |
} else { |
| 295 |
// Be conservative if the type isn't a RecordType. We are specifically |
| 296 |
// required to do this for member pointers until we implement the |
| 297 |
// similar-types rule. |
| 298 |
const auto *RT = Ty->getAsCanonical<RecordType>(); |
| 299 |
if (!RT) |
| 300 |
return getAnyPtr(PtrDepth); |
| 301 |
|
| 302 |
// For unnamed structs or unions C's compatible types rule applies. Two |
| 303 |
// compatible types in different compilation units can have different |
| 304 |
// mangled names, meaning the metadata emitted below would incorrectly |
| 305 |
// mark them as no-alias. Use AnyPtr for such types in both C and C++, as |
| 306 |
// C and C++ types may be visible when doing LTO. |
| 307 |
// |
| 308 |
// Note that using AnyPtr is overly conservative. We could summarize the |
| 309 |
// members of the type, as per the C compatibility rule in the future. |
| 310 |
// This also covers anonymous structs and unions, which have a different |
| 311 |
// compatibility rule, but it doesn't matter because you can never have a |
| 312 |
// pointer to an anonymous struct or union. |
| 313 |
if (!RT->getDecl()->getDeclName()) |
| 314 |
return getAnyPtr(PtrDepth); |
| 315 |
|
| 316 |
// For non-builtin types use the mangled name of the canonical type. |
| 317 |
llvm::raw_svector_ostream TyOut(TyName); |
| 318 |
MangleCtx->mangleCanonicalTypeName(QualType(Ty, 0), TyOut); |
| 319 |
} |
| 320 |
|
| 321 |
SmallString<256> OutName("p"); |
| 322 |
OutName += std::to_string(PtrDepth); |
| 323 |
OutName += " "; |
| 324 |
OutName += TyName; |
| 325 |
return createScalarTypeNode(OutName, getAnyPtr(PtrDepth), Size); |
| 326 |
} |
| 327 |
|
| 328 |
// Accesses to arrays are accesses to objects of their element types. |
| 329 |
if (CodeGenOpts.NewStructPathTBAA && Ty->isArrayType()) |
| 330 |
return getTypeInfo(cast<ArrayType>(Ty)->getElementType()); |
| 331 |
|
| 332 |
// Enum types are distinct types. In C++ they have "underlying types", |
| 333 |
// however they aren't related for TBAA. |
| 334 |
if (const EnumType *ETy = dyn_cast<EnumType>(Ty)) { |
| 335 |
const EnumDecl *ED = ETy->getDecl()->getDefinitionOrSelf(); |
| 336 |
if (!Features.CPlusPlus) |
| 337 |
return getTypeInfo(ED->getIntegerType()); |
| 338 |
|
| 339 |
// In C++ mode, types have linkage, so we can rely on the ODR and |
| 340 |
// on their mangled names, if they're external. |
| 341 |
// TODO: Is there a way to get a program-wide unique name for a |
| 342 |
// decl with local linkage or no linkage? |
| 343 |
if (!ED->isExternallyVisible()) |
| 344 |
return getChar(); |
| 345 |
|
| 346 |
SmallString<256> OutName; |
| 347 |
llvm::raw_svector_ostream Out(OutName); |
| 348 |
CGTypes.getCXXABI().getMangleContext().mangleCanonicalTypeName( |
| 349 |
QualType(ETy, 0), Out); |
| 350 |
return createScalarTypeNode(OutName, getChar(), Size); |
| 351 |
} |
| 352 |
|
| 353 |
if (const auto *EIT = dyn_cast<BitIntType>(Ty)) { |
| 354 |
SmallString<256> OutName; |
| 355 |
llvm::raw_svector_ostream Out(OutName); |
| 356 |
// Don't specify signed/unsigned since integer types can alias despite sign |
| 357 |
// differences. |
| 358 |
Out << "_BitInt(" << EIT->getNumBits() << ')'; |
| 359 |
return createScalarTypeNode(OutName, getChar(), Size); |
| 360 |
} |
| 361 |
|
| 362 |
// For now, handle any other kind of type conservatively. |
| 363 |
return getChar(); |
| 364 |
} |
| 365 |
|
| 366 |
llvm::MDNode *CodeGenTBAA::getTypeInfo(QualType QTy) { |
| 367 |
// At -O0 or relaxed aliasing, TBAA is not emitted for regular types (unless |
| 368 |
// we're running TypeSanitizer). |
| 369 |
if (!Features.Sanitize.has(SanitizerKind::Type) && |
| 370 |
(CodeGenOpts.OptimizationLevel == 0 || CodeGenOpts.RelaxedAliasing)) |
| 371 |
return nullptr; |
| 372 |
|
| 373 |
// If the type has the may_alias attribute (even on a typedef), it is |
| 374 |
// effectively in the general char alias class. |
| 375 |
if (TypeHasMayAlias(QTy)) |
| 376 |
return getChar(); |
| 377 |
|
| 378 |
// We need this function to not fall back to returning the "omnipotent char" |
| 379 |
// type node for aggregate and union types. Otherwise, any dereference of an |
| 380 |
// aggregate will result into the may-alias access descriptor, meaning all |
| 381 |
// subsequent accesses to direct and indirect members of that aggregate will |
| 382 |
// be considered may-alias too. |
| 383 |
// TODO: Combine getTypeInfo() and getValidBaseTypeInfo() into a single |
| 384 |
// function. |
| 385 |
if (isValidBaseType(QTy)) |
| 386 |
return getValidBaseTypeInfo(QTy); |
| 387 |
|
| 388 |
const Type *Ty = Context.getCanonicalType(QTy).getTypePtr(); |
| 389 |
if (llvm::MDNode *N = MetadataCache[Ty]) |
| 390 |
return N; |
| 391 |
|
| 392 |
// Note that the following helper call is allowed to add new nodes to the |
| 393 |
// cache, which invalidates all its previously obtained iterators. So we |
| 394 |
// first generate the node for the type and then add that node to the cache. |
| 395 |
llvm::MDNode *TypeNode = getTypeInfoHelper(Ty); |
| 396 |
return MetadataCache[Ty] = TypeNode; |
| 397 |
} |
| 398 |
|
| 399 |
TBAAAccessInfo CodeGenTBAA::getAccessInfo(QualType AccessType) { |
| 400 |
// Pointee values may have incomplete types, but they shall never be |
| 401 |
// dereferenced. |
| 402 |
if (AccessType->isIncompleteType()) |
| 403 |
return TBAAAccessInfo::getIncompleteInfo(); |
| 404 |
|
| 405 |
if (TypeHasMayAlias(AccessType)) |
| 406 |
return TBAAAccessInfo::getMayAliasInfo(); |
| 407 |
|
| 408 |
uint64_t Size = Context.getTypeSizeInChars(AccessType).getQuantity(); |
| 409 |
return TBAAAccessInfo(getTypeInfo(AccessType), Size); |
| 410 |
} |
| 411 |
|
| 412 |
TBAAAccessInfo CodeGenTBAA::getVTablePtrAccessInfo(llvm::Type *VTablePtrType) { |
| 413 |
const llvm::DataLayout &DL = Module.getDataLayout(); |
| 414 |
unsigned Size = DL.getPointerTypeSize(VTablePtrType); |
| 415 |
return TBAAAccessInfo(createScalarTypeNode("vtable pointer", getRoot(), Size), |
| 416 |
Size); |
| 417 |
} |
| 418 |
|
| 419 |
bool |
| 420 |
CodeGenTBAA::CollectFields(uint64_t BaseOffset, |
| 421 |
QualType QTy, |
| 422 |
SmallVectorImpl<llvm::MDBuilder::TBAAStructField> & |
| 423 |
Fields, |
| 424 |
bool MayAlias) { |
| 425 |
/* Things not handled yet include: C++ base classes, bitfields, */ |
| 426 |
|
| 427 |
if (const auto *TTy = QTy->getAsCanonical<RecordType>()) { |
| 428 |
if (TTy->isUnionType()) { |
| 429 |
uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity(); |
| 430 |
llvm::MDNode *TBAAType = getChar(); |
| 431 |
llvm::MDNode *TBAATag = getAccessTagInfo(TBAAAccessInfo(TBAAType, Size)); |
| 432 |
Fields.push_back( |
| 433 |
llvm::MDBuilder::TBAAStructField(BaseOffset, Size, TBAATag)); |
| 434 |
return true; |
| 435 |
} |
| 436 |
const RecordDecl *RD = TTy->getDecl()->getDefinition(); |
| 437 |
if (RD->hasFlexibleArrayMember()) |
| 438 |
return false; |
| 439 |
|
| 440 |
// TODO: Handle C++ base classes. |
| 441 |
if (const CXXRecordDecl *Decl = dyn_cast<CXXRecordDecl>(RD)) |
| 442 |
if (!Decl->bases().empty()) |
| 443 |
return false; |
| 444 |
|
| 445 |
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); |
| 446 |
const CGRecordLayout &CGRL = CGTypes.getCGRecordLayout(RD); |
| 447 |
|
| 448 |
unsigned idx = 0; |
| 449 |
for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); |
| 450 |
i != e; ++i, ++idx) { |
| 451 |
if (isEmptyFieldForLayout(Context, *i)) |
| 452 |
continue; |
| 453 |
|
| 454 |
uint64_t Offset = |
| 455 |
BaseOffset + Layout.getFieldOffset(idx) / Context.getCharWidth(); |
| 456 |
|
| 457 |
// Create a single field for consecutive named bitfields using char as |
| 458 |
// base type. |
| 459 |
if ((*i)->isBitField()) { |
| 460 |
const CGBitFieldInfo &Info = CGRL.getBitFieldInfo(*i); |
| 461 |
// For big endian targets the first bitfield in the consecutive run is |
| 462 |
// at the most-significant end; see CGRecordLowering::setBitFieldInfo |
| 463 |
// for more information. |
| 464 |
bool IsBE = Context.getTargetInfo().isBigEndian(); |
| 465 |
bool IsFirst = IsBE ? Info.StorageSize - (Info.Offset + Info.Size) == 0 |
| 466 |
: Info.Offset == 0; |
| 467 |
if (!IsFirst) |
| 468 |
continue; |
| 469 |
unsigned CurrentBitFieldSize = Info.StorageSize; |
| 470 |
uint64_t Size = |
| 471 |
llvm::divideCeil(CurrentBitFieldSize, Context.getCharWidth()); |
| 472 |
llvm::MDNode *TBAAType = getChar(); |
| 473 |
llvm::MDNode *TBAATag = |
| 474 |
getAccessTagInfo(TBAAAccessInfo(TBAAType, Size)); |
| 475 |
Fields.push_back( |
| 476 |
llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag)); |
| 477 |
continue; |
| 478 |
} |
| 479 |
|
| 480 |
QualType FieldQTy = i->getType(); |
| 481 |
if (!CollectFields(Offset, FieldQTy, Fields, |
| 482 |
MayAlias || TypeHasMayAlias(FieldQTy))) |
| 483 |
return false; |
| 484 |
} |
| 485 |
return true; |
| 486 |
} |
| 487 |
|
| 488 |
/* Otherwise, treat whatever it is as a field. */ |
| 489 |
uint64_t Offset = BaseOffset; |
| 490 |
uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity(); |
| 491 |
llvm::MDNode *TBAAType = MayAlias ? getChar() : getTypeInfo(QTy); |
| 492 |
llvm::MDNode *TBAATag = getAccessTagInfo(TBAAAccessInfo(TBAAType, Size)); |
| 493 |
Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag)); |
| 494 |
return true; |
| 495 |
} |
| 496 |
|
| 497 |
llvm::MDNode * |
| 498 |
CodeGenTBAA::getTBAAStructInfo(QualType QTy) { |
| 499 |
if (CodeGenOpts.OptimizationLevel == 0 || CodeGenOpts.RelaxedAliasing) |
| 500 |
return nullptr; |
| 501 |
|
| 502 |
const Type *Ty = Context.getCanonicalType(QTy).getTypePtr(); |
| 503 |
|
| 504 |
if (llvm::MDNode *N = StructMetadataCache[Ty]) |
| 505 |
return N; |
| 506 |
|
| 507 |
SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields; |
| 508 |
if (CollectFields(0, QTy, Fields, TypeHasMayAlias(QTy))) |
| 509 |
return MDHelper.createTBAAStructNode(Fields); |
| 510 |
|
| 511 |
// For now, handle any other kind of type conservatively. |
| 512 |
return StructMetadataCache[Ty] = nullptr; |
| 513 |
} |
| 514 |
|
| 515 |
llvm::MDNode *CodeGenTBAA::getBaseTypeInfoHelper(const Type *Ty) { |
| 516 |
if (auto *TTy = dyn_cast<RecordType>(Ty)) { |
| 517 |
const RecordDecl *RD = TTy->getDecl()->getDefinition(); |
| 518 |
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); |
| 519 |
using TBAAStructField = llvm::MDBuilder::TBAAStructField; |
| 520 |
SmallVector<TBAAStructField, 4> Fields; |
| 521 |
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { |
| 522 |
// Handle C++ base classes. Non-virtual bases can treated a kind of |
| 523 |
// field. Virtual bases are more complex and omitted, but avoid an |
| 524 |
// incomplete view for NewStructPathTBAA. |
| 525 |
if (CodeGenOpts.NewStructPathTBAA && CXXRD->getNumVBases() != 0) |
| 526 |
return nullptr; |
| 527 |
for (const CXXBaseSpecifier &B : CXXRD->bases()) { |
| 528 |
if (B.isVirtual()) |
| 529 |
continue; |
| 530 |
QualType BaseQTy = B.getType(); |
| 531 |
const CXXRecordDecl *BaseRD = BaseQTy->getAsCXXRecordDecl(); |
| 532 |
if (BaseRD->isEmpty()) |
| 533 |
continue; |
| 534 |
llvm::MDNode *TypeNode = isValidBaseType(BaseQTy) |
| 535 |
? getValidBaseTypeInfo(BaseQTy) |
| 536 |
: getTypeInfo(BaseQTy); |
| 537 |
if (!TypeNode) |
| 538 |
return nullptr; |
| 539 |
uint64_t Offset = Layout.getBaseClassOffset(BaseRD).getQuantity(); |
| 540 |
uint64_t Size = |
| 541 |
Context.getASTRecordLayout(BaseRD).getDataSize().getQuantity(); |
| 542 |
Fields.push_back( |
| 543 |
llvm::MDBuilder::TBAAStructField(Offset, Size, TypeNode)); |
| 544 |
} |
| 545 |
// The order in which base class subobjects are allocated is unspecified, |
| 546 |
// so may differ from declaration order. In particular, Itanium ABI will |
| 547 |
// allocate a primary base first. |
| 548 |
// Since we exclude empty subobjects, the objects are not overlapping and |
| 549 |
// their offsets are unique. |
| 550 |
llvm::sort(Fields, |
| 551 |
[](const TBAAStructField &A, const TBAAStructField &B) { |
| 552 |
return A.Offset < B.Offset; |
| 553 |
}); |
| 554 |
} |
| 555 |
for (FieldDecl *Field : RD->fields()) { |
| 556 |
if (Field->isZeroSize(Context) || Field->isUnnamedBitField()) |
| 557 |
continue; |
| 558 |
QualType FieldQTy = Field->getType(); |
| 559 |
llvm::MDNode *TypeNode = isValidBaseType(FieldQTy) |
| 560 |
? getValidBaseTypeInfo(FieldQTy) |
| 561 |
: getTypeInfo(FieldQTy); |
| 562 |
if (!TypeNode) |
| 563 |
return nullptr; |
| 564 |
|
| 565 |
uint64_t BitOffset = Layout.getFieldOffset(Field->getFieldIndex()); |
| 566 |
uint64_t Offset = Context.toCharUnitsFromBits(BitOffset).getQuantity(); |
| 567 |
uint64_t Size = Context.getTypeSizeInChars(FieldQTy).getQuantity(); |
| 568 |
Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, |
| 569 |
TypeNode)); |
| 570 |
} |
| 571 |
|
| 572 |
SmallString<256> OutName; |
| 573 |
if (Features.CPlusPlus) { |
| 574 |
// Don't use the mangler for C code. |
| 575 |
llvm::raw_svector_ostream Out(OutName); |
| 576 |
CGTypes.getCXXABI().getMangleContext().mangleCanonicalTypeName( |
| 577 |
QualType(Ty, 0), Out); |
| 578 |
} else { |
| 579 |
OutName = RD->getName(); |
| 580 |
} |
| 581 |
|
| 582 |
if (CodeGenOpts.NewStructPathTBAA) { |
| 583 |
llvm::MDNode *Parent = getChar(); |
| 584 |
uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity(); |
| 585 |
llvm::Metadata *Id = MDHelper.createString(OutName); |
| 586 |
return MDHelper.createTBAATypeNode(Parent, Size, Id, Fields); |
| 587 |
} |
| 588 |
|
| 589 |
// Create the struct type node with a vector of pairs (offset, type). |
| 590 |
SmallVector<std::pair<llvm::MDNode*, uint64_t>, 4> OffsetsAndTypes; |
| 591 |
for (const auto &Field : Fields) |
| 592 |
OffsetsAndTypes.push_back(std::make_pair(Field.Type, Field.Offset)); |
| 593 |
return MDHelper.createTBAAStructTypeNode(OutName, OffsetsAndTypes); |
| 594 |
} |
| 595 |
|
| 596 |
return nullptr; |
| 597 |
} |
| 598 |
|
| 599 |
llvm::MDNode *CodeGenTBAA::getValidBaseTypeInfo(QualType QTy) { |
| 600 |
assert(isValidBaseType(QTy) && "Must be a valid base type"); |
| 601 |
|
| 602 |
const Type *Ty = Context.getCanonicalType(QTy).getTypePtr(); |
| 603 |
|
| 604 |
// nullptr is a valid value in the cache, so use find rather than [] |
| 605 |
auto I = BaseTypeMetadataCache.find(Ty); |
| 606 |
if (I != BaseTypeMetadataCache.end()) |
| 607 |
return I->second; |
| 608 |
|
| 609 |
// First calculate the metadata, before recomputing the insertion point, as |
| 610 |
// the helper can recursively call us. |
| 611 |
llvm::MDNode *TypeNode = getBaseTypeInfoHelper(Ty); |
| 612 |
[[maybe_unused]] auto inserted = BaseTypeMetadataCache.insert({Ty, TypeNode}); |
| 613 |
assert(inserted.second && "BaseType metadata was already inserted"); |
| 614 |
|
| 615 |
return TypeNode; |
| 616 |
} |
| 617 |
|
| 618 |
llvm::MDNode *CodeGenTBAA::getBaseTypeInfo(QualType QTy) { |
| 619 |
return isValidBaseType(QTy) ? getValidBaseTypeInfo(QTy) : nullptr; |
| 620 |
} |
| 621 |
|
| 622 |
llvm::MDNode *CodeGenTBAA::getAccessTagInfo(TBAAAccessInfo Info) { |
| 623 |
assert(!Info.isIncomplete() && "Access to an object of an incomplete type!"); |
| 624 |
|
| 625 |
if (Info.isMayAlias()) |
| 626 |
Info = TBAAAccessInfo(getChar(), Info.Size); |
| 627 |
|
| 628 |
if (!Info.AccessType) |
| 629 |
return nullptr; |
| 630 |
|
| 631 |
if (!CodeGenOpts.StructPathTBAA) |
| 632 |
Info = TBAAAccessInfo(Info.AccessType, Info.Size); |
| 633 |
|
| 634 |
llvm::MDNode *&N = AccessTagMetadataCache[Info]; |
| 635 |
if (N) |
| 636 |
return N; |
| 637 |
|
| 638 |
if (!Info.BaseType) { |
| 639 |
Info.BaseType = Info.AccessType; |
| 640 |
assert(!Info.Offset && "Nonzero offset for an access with no base type!"); |
| 641 |
} |
| 642 |
if (CodeGenOpts.NewStructPathTBAA) { |
| 643 |
return N = MDHelper.createTBAAAccessTag(Info.BaseType, Info.AccessType, |
| 644 |
Info.Offset, Info.Size); |
| 645 |
} |
| 646 |
return N = MDHelper.createTBAAStructTagNode(Info.BaseType, Info.AccessType, |
| 647 |
Info.Offset); |
| 648 |
} |
| 649 |
|
| 650 |
TBAAAccessInfo CodeGenTBAA::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, |
| 651 |
TBAAAccessInfo TargetInfo) { |
| 652 |
if (SourceInfo.isMayAlias() || TargetInfo.isMayAlias()) |
| 653 |
return TBAAAccessInfo::getMayAliasInfo(); |
| 654 |
return TargetInfo; |
| 655 |
} |
| 656 |
|
| 657 |
TBAAAccessInfo |
| 658 |
CodeGenTBAA::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, |
| 659 |
TBAAAccessInfo InfoB) { |
| 660 |
if (InfoA == InfoB) |
| 661 |
return InfoA; |
| 662 |
|
| 663 |
if (!InfoA || !InfoB) |
| 664 |
return TBAAAccessInfo(); |
| 665 |
|
| 666 |
if (InfoA.isMayAlias() || InfoB.isMayAlias()) |
| 667 |
return TBAAAccessInfo::getMayAliasInfo(); |
| 668 |
|
| 669 |
// TODO: Implement the rest of the logic here. For example, two accesses |
| 670 |
// with same final access types result in an access to an object of that final |
| 671 |
// access type regardless of their base types. |
| 672 |
return TBAAAccessInfo::getMayAliasInfo(); |
| 673 |
} |
| 674 |
|
| 675 |
TBAAAccessInfo |
| 676 |
CodeGenTBAA::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, |
| 677 |
TBAAAccessInfo SrcInfo) { |
| 678 |
if (DestInfo == SrcInfo) |
| 679 |
return DestInfo; |
| 680 |
|
| 681 |
if (!DestInfo || !SrcInfo) |
| 682 |
return TBAAAccessInfo(); |
| 683 |
|
| 684 |
if (DestInfo.isMayAlias() || SrcInfo.isMayAlias()) |
| 685 |
return TBAAAccessInfo::getMayAliasInfo(); |
| 686 |
|
| 687 |
// TODO: Implement the rest of the logic here. For example, two accesses |
| 688 |
// with same final access types result in an access to an object of that final |
| 689 |
// access type regardless of their base types. |
| 690 |
return TBAAAccessInfo::getMayAliasInfo(); |
| 691 |
} |