30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Metadata.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
34#include "llvm/Support/Debug.h"
41 : Context(Ctx), CGTypes(CGTypes), Module(M), CodeGenOpts(CGO),
49llvm::MDNode *CodeGenTBAA::getRoot() {
55 if (Features.CPlusPlus)
56 Root = MDHelper.createTBAARoot(
"Simple C++ TBAA");
58 Root = MDHelper.createTBAARoot(
"Simple C/C++ TBAA");
64llvm::MDNode *CodeGenTBAA::createScalarTypeNode(StringRef Name,
67 if (CodeGenOpts.NewStructPathTBAA) {
68 llvm::Metadata *Id = MDHelper.createString(Name);
69 return MDHelper.createTBAATypeNode(Parent, Size, Id);
71 return MDHelper.createTBAAScalarTypeNode(Name, Parent);
80 Char = createScalarTypeNode(
"omnipotent char", getRoot(), 1);
85llvm::MDNode *CodeGenTBAA::getAnyPtr(
unsigned PtrDepth) {
86 assert(PtrDepth >= 1 &&
"Pointer must have some depth");
105 if (AnyPtrs.size() < PtrDepth) {
106 AnyPtrs.reserve(PtrDepth);
107 auto Size =
Module.getDataLayout().getPointerSize();
110 AnyPtrs.push_back(createScalarTypeNode(
"any pointer",
getChar(), Size));
112 for (
size_t Idx = AnyPtrs.size(); Idx < PtrDepth; ++Idx) {
113 auto Name = (
"any p" + llvm::Twine(Idx + 1) +
" pointer").str();
114 AnyPtrs.push_back(createScalarTypeNode(Name, AnyPtrs[Idx - 1], Size));
118 return AnyPtrs[PtrDepth - 1];
121llvm::MDNode *CodeGenTBAA::getTypeInfoHelper(
const Type *Ty) {
122 uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity();
125 if (
const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) {
126 switch (BTy->getKind()) {
132 case BuiltinType::Char_U:
133 case BuiltinType::Char_S:
134 case BuiltinType::UChar:
135 case BuiltinType::SChar:
150 return createScalarTypeNode(BTy->getName(Features),
getChar(), Size);
176 if (!CodeGenOpts.PointerTBAA)
194 unsigned PtrDepth = 0;
205 return getAnyPtr(PtrDepth);
215 SmallString<256> TyName;
217 llvm::MDNode *ScalarMD = getTypeInfoHelper(Ty);
220 ScalarMD->getOperand(CodeGenOpts.NewStructPathTBAA ? 2 : 0))
229 return getAnyPtr(PtrDepth);
242 if (!RT->getDecl()->getDeclName())
243 return getAnyPtr(PtrDepth);
246 llvm::raw_svector_ostream TyOut(TyName);
247 MangleCtx->mangleCanonicalTypeName(QualType(Ty, 0), TyOut);
250 SmallString<256> OutName(
"p");
251 OutName += std::to_string(PtrDepth);
254 return createScalarTypeNode(OutName, getAnyPtr(PtrDepth), Size);
258 if (CodeGenOpts.NewStructPathTBAA && Ty->
isArrayType())
262 if (
const auto *MTy = dyn_cast<MatrixType>(Ty)) {
264 "only ConstantMatrixType should reach CodeGen");
268 if (
const auto *CMTy = dyn_cast<CooperativeMatrixType>(Ty))
272 if (
const auto *CTy = dyn_cast<ComplexType>(Ty))
277 if (
const EnumType *ETy = dyn_cast<EnumType>(Ty)) {
278 const EnumDecl *ED = ETy->getDecl()->getDefinitionOrSelf();
279 if (!Features.CPlusPlus)
289 SmallString<256> OutName;
290 llvm::raw_svector_ostream
Out(OutName);
291 CGTypes.getCXXABI().getMangleContext().mangleCanonicalTypeName(
292 QualType(ETy, 0), Out);
293 return createScalarTypeNode(OutName,
getChar(), Size);
296 if (
const auto *EIT = dyn_cast<BitIntType>(Ty)) {
297 SmallString<256> OutName;
298 llvm::raw_svector_ostream
Out(OutName);
301 Out <<
"_BitInt(" << EIT->getNumBits() <<
')';
302 return createScalarTypeNode(OutName,
getChar(), Size);
312 if (!Features.Sanitize.has(SanitizerKind::Type) &&
313 (CodeGenOpts.OptimizationLevel == 0 || CodeGenOpts.RelaxedAliasing))
329 return getValidBaseTypeInfo(QTy);
331 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
332 if (llvm::MDNode *N = MetadataCache[Ty])
338 llvm::MDNode *TypeNode = getTypeInfoHelper(Ty);
339 return MetadataCache[Ty] = TypeNode;
351 uint64_t Size = Context.getTypeSizeInChars(AccessType).getQuantity();
356 const llvm::DataLayout &DL = Module.getDataLayout();
357 unsigned Size = DL.getPointerTypeSize(VTablePtrType);
358 return TBAAAccessInfo(createScalarTypeNode(
"vtable pointer", getRoot(), Size),
363CodeGenTBAA::CollectFields(uint64_t BaseOffset,
371 if (TTy->isUnionType()) {
372 uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity();
373 llvm::MDNode *TBAAType =
getChar();
376 llvm::MDBuilder::TBAAStructField(BaseOffset, Size, TBAATag));
385 if (!
Decl->bases().empty())
393 i != e; ++i, ++idx) {
402 if ((*i)->isBitField()) {
407 bool IsBE = Context.getTargetInfo().isBigEndian();
414 llvm::divideCeil(CurrentBitFieldSize, Context.getCharWidth());
415 llvm::MDNode *TBAAType =
getChar();
416 llvm::MDNode *TBAATag =
419 llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag));
424 if (!CollectFields(Offset, FieldQTy, Fields,
432 QualType ElemQTy = CTy->getElementType();
433 uint64_t Size = Context.getTypeSizeInChars(ElemQTy).getQuantity();
437 llvm::MDBuilder::TBAAStructField(BaseOffset, Size, TBAATag));
439 llvm::MDBuilder::TBAAStructField(BaseOffset + Size, Size, TBAATag));
445 uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity();
448 Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag));
454 if (CodeGenOpts.OptimizationLevel == 0 || CodeGenOpts.RelaxedAliasing)
457 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
459 if (llvm::MDNode *N = StructMetadataCache[Ty])
464 return MDHelper.createTBAAStructNode(Fields);
467 return StructMetadataCache[Ty] =
nullptr;
470llvm::MDNode *CodeGenTBAA::getBaseTypeInfoHelper(
const Type *Ty) {
471 if (
auto *TTy = dyn_cast<RecordType>(Ty)) {
474 using TBAAStructField = llvm::MDBuilder::TBAAStructField;
476 if (
const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
480 if (CodeGenOpts.NewStructPathTBAA && CXXRD->getNumVBases() != 0)
490 ? getValidBaseTypeInfo(BaseQTy)
496 Context.getASTRecordLayout(BaseRD).getDataSize().getQuantity();
498 llvm::MDBuilder::TBAAStructField(Offset, Size, TypeNode));
506 [](
const TBAAStructField &A,
const TBAAStructField &B) {
507 return A.Offset < B.Offset;
510 for (FieldDecl *Field : RD->
fields()) {
511 if (
Field->isZeroSize(Context) ||
Field->isUnnamedBitField())
513 QualType FieldQTy =
Field->getType();
515 ? getValidBaseTypeInfo(FieldQTy)
521 uint64_t Offset = Context.toCharUnitsFromBits(BitOffset).getQuantity();
522 uint64_t Size = Context.getTypeSizeInChars(FieldQTy).getQuantity();
523 Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size,
527 SmallString<256> OutName;
528 if (Features.CPlusPlus) {
530 llvm::raw_svector_ostream
Out(OutName);
531 CGTypes.getCXXABI().getMangleContext().mangleCanonicalTypeName(
532 QualType(Ty, 0), Out);
537 if (CodeGenOpts.NewStructPathTBAA) {
538 llvm::MDNode *Parent =
getChar();
539 uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity();
540 llvm::Metadata *Id = MDHelper.createString(OutName);
541 return MDHelper.createTBAATypeNode(Parent, Size, Id, Fields);
545 SmallVector<std::pair<llvm::MDNode*, uint64_t>, 4> OffsetsAndTypes;
546 for (
const auto &Field : Fields)
547 OffsetsAndTypes.push_back(std::make_pair(
Field.Type,
Field.Offset));
548 return MDHelper.createTBAAStructTypeNode(OutName, OffsetsAndTypes);
554llvm::MDNode *CodeGenTBAA::getValidBaseTypeInfo(QualType QTy) {
557 const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
560 auto I = BaseTypeMetadataCache.find(Ty);
561 if (I != BaseTypeMetadataCache.end())
566 llvm::MDNode *TypeNode = getBaseTypeInfoHelper(Ty);
567 [[maybe_unused]]
auto inserted = BaseTypeMetadataCache.insert({Ty, TypeNode});
568 assert(inserted.second &&
"BaseType metadata was already inserted");
579 assert(!Info.
isIncomplete() &&
"Access to an object of an incomplete type!");
587 if (!CodeGenOpts.StructPathTBAA)
590 llvm::MDNode *&N = AccessTagMetadataCache[Info];
596 assert(!Info.
Offset &&
"Nonzero offset for an access with no base type!");
598 if (CodeGenOpts.NewStructPathTBAA) {
619 if (!InfoA || !InfoB)
634 if (DestInfo == SrcInfo)
637 if (!DestInfo || !SrcInfo)
Defines the clang::ASTContext interface.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
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.
Represents a base class of a C++ class.
Represents a C++ struct/union/class.
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
llvm::MDNode * getBaseTypeInfo(QualType QTy)
getBaseTypeInfo - Get metadata that describes the given base access type.
llvm::MDNode * getTypeInfo(QualType QTy)
getTypeInfo - Get metadata used to describe accesses to objects of the given type.
TBAAAccessInfo getVTablePtrAccessInfo(llvm::Type *VTablePtrType)
getVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table pointer...
TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, TBAAAccessInfo SrcInfo)
mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the purpose of memory transfer calls...
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purpose of type casts.
llvm::MDNode * getChar()
getChar - This is the mdnode for "char", which is special, and any types considered to be equivalent ...
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purpose of conditional oper...
llvm::MDNode * getAccessTagInfo(TBAAAccessInfo Info)
getAccessTagInfo - Get TBAA tag for a given memory access.
llvm::MDNode * getTBAAStructInfo(QualType QTy)
getTBAAStructInfo - Get the TBAAStruct MDNode to be used for a memcpy of the given type.
CodeGenTBAA(ASTContext &Ctx, CodeGenTypes &CGTypes, llvm::Module &M, const CodeGenOptions &CGO, const LangOptions &Features)
TBAAAccessInfo getAccessInfo(QualType AccessType)
getAccessInfo - Get TBAA information that describes an access to an object of the given type.
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
Decl - This represents one declaration (or definition), e.g.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Describes a module or submodule.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
bool isExternallyVisible() const
A (possibly-)qualified type.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Represents a struct/union/class.
bool hasFlexibleArrayMember() const
field_iterator field_end() const
field_range fields() const
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
specific_decl_iterator< FieldDecl > field_iterator
field_iterator field_begin() const
Exposes information about the current target.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isPointerType() const
bool isReferenceType() const
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
bool isStdByteType() const
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
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_...
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,...
bool isValidTBAABaseType(QualType QTy)
Returns true if QTy is a valid base type to be used in TBAA access tags.
bool isEmptyFieldForLayout(const ASTContext &Ctx, const FieldDecl *FD)
Return true iff the field is "empty", that is, either a zero-width bit-field or an isEmptyRecordForLa...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
U cast(CodeGen::Address addr)
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
Structure with information about how a bitfield should be accessed.
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Size
The total size of the bit-field, in bits, not including padding.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
llvm::MDNode * AccessType
AccessType - The final access type.
uint64_t Offset
Offset - The byte offset of the final access within the base one.
static TBAAAccessInfo getMayAliasInfo()
uint64_t Size
Size - The size of access, in bytes.
static TBAAAccessInfo getIncompleteInfo()
llvm::MDNode * BaseType
BaseType - The base/leading access type.
bool isIncomplete() const