Page MenuHomePhabricator

No OneTemporary

File Metadata

Created
Sat, Jul 11, 2:26 AM
This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h
index 87f0e8f150d..ea07d5f80ef 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1,3068 +1,3067 @@
//===- ASTContext.h - Context to hold long-lived AST nodes ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// Defines the clang::ASTContext interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
#define LLVM_CLANG_AST_ASTCONTEXT_H
#include "clang/AST/ASTTypeTraits.h"
#include "clang/AST/CanonicalType.h"
#include "clang/AST/CommentCommandTraits.h"
#include "clang/AST/ComparisonCategories.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/RawCommentList.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/TemplateName.h"
#include "clang/AST/Type.h"
#include "clang/Basic/AddressSpaces.h"
-#include "clang/Basic/AttrKinds.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/Linkage.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/SanitizerBlacklist.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/XRayLists.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/AlignOf.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
namespace llvm {
struct fltSemantics;
} // namespace llvm
namespace clang {
class APFixedPoint;
class APValue;
class ASTMutationListener;
class ASTRecordLayout;
class AtomicExpr;
class BlockExpr;
class BuiltinTemplateDecl;
class CharUnits;
class CXXABI;
class CXXConstructorDecl;
class CXXMethodDecl;
class CXXRecordDecl;
class DiagnosticsEngine;
class Expr;
class FixedPointSemantics;
class MangleContext;
class MangleNumberingContext;
class MaterializeTemporaryExpr;
class MemberSpecializationInfo;
class Module;
class ObjCCategoryDecl;
class ObjCCategoryImplDecl;
class ObjCContainerDecl;
class ObjCImplDecl;
class ObjCImplementationDecl;
class ObjCInterfaceDecl;
class ObjCIvarDecl;
class ObjCMethodDecl;
class ObjCPropertyDecl;
class ObjCPropertyImplDecl;
class ObjCProtocolDecl;
class ObjCTypeParamDecl;
class Preprocessor;
class Stmt;
class StoredDeclsMap;
class TemplateDecl;
class TemplateParameterList;
class TemplateTemplateParmDecl;
class TemplateTypeParmDecl;
class UnresolvedSetIterator;
class UsingShadowDecl;
class VarTemplateDecl;
class VTableContextBase;
namespace Builtin {
class Context;
} // namespace Builtin
enum BuiltinTemplateKind : int;
namespace comments {
class FullComment;
} // namespace comments
struct TypeInfo {
uint64_t Width = 0;
unsigned Align = 0;
bool AlignIsRequired : 1;
TypeInfo() : AlignIsRequired(false) {}
TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
: Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
};
/// Holds long-lived AST nodes (such as types and decls) that can be
/// referred to throughout the semantic analysis of a file.
class ASTContext : public RefCountedBase<ASTContext> {
public:
/// Copy initialization expr of a __block variable and a boolean flag that
/// indicates whether the expression can throw.
struct BlockVarCopyInit {
BlockVarCopyInit() = default;
BlockVarCopyInit(Expr *CopyExpr, bool CanThrow)
: ExprAndFlag(CopyExpr, CanThrow) {}
void setExprAndFlag(Expr *CopyExpr, bool CanThrow) {
ExprAndFlag.setPointerAndInt(CopyExpr, CanThrow);
}
Expr *getCopyExpr() const { return ExprAndFlag.getPointer(); }
bool canThrow() const { return ExprAndFlag.getInt(); }
llvm::PointerIntPair<Expr *, 1, bool> ExprAndFlag;
};
private:
friend class NestedNameSpecifier;
mutable SmallVector<Type *, 0> Types;
mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
mutable llvm::FoldingSet<ComplexType> ComplexTypes;
mutable llvm::FoldingSet<PointerType> PointerTypes;
mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
mutable std::vector<VariableArrayType*> VariableArrayTypes;
mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
mutable llvm::FoldingSet<DependentSizedExtVectorType>
DependentSizedExtVectorTypes;
mutable llvm::FoldingSet<DependentAddressSpaceType>
DependentAddressSpaceTypes;
mutable llvm::FoldingSet<VectorType> VectorTypes;
mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes;
mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
FunctionProtoTypes;
mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
mutable llvm::FoldingSet<SubstTemplateTypeParmType>
SubstTemplateTypeParmTypes;
mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
SubstTemplateTypeParmPackTypes;
mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
TemplateSpecializationTypes;
mutable llvm::FoldingSet<ParenType> ParenTypes;
mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
ASTContext&>
DependentTemplateSpecializationTypes;
llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
mutable llvm::FoldingSet<DependentUnaryTransformType>
DependentUnaryTransformTypes;
mutable llvm::FoldingSet<AutoType> AutoTypes;
mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
DeducedTemplateSpecializationTypes;
mutable llvm::FoldingSet<AtomicType> AtomicTypes;
llvm::FoldingSet<AttributedType> AttributedTypes;
mutable llvm::FoldingSet<PipeType> PipeTypes;
mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
SubstTemplateTemplateParms;
mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
ASTContext&>
SubstTemplateTemplateParmPacks;
/// The set of nested name specifiers.
///
/// This set is managed by the NestedNameSpecifier class.
mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
/// A cache mapping from RecordDecls to ASTRecordLayouts.
///
/// This is lazily created. This is intentionally not serialized.
mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
ASTRecordLayouts;
mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
ObjCLayouts;
/// A cache from types to size and alignment information.
using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
mutable TypeInfoMap MemoizedTypeInfo;
/// A cache from types to unadjusted alignment information. Only ARM and
/// AArch64 targets need this information, keeping it separate prevents
/// imposing overhead on TypeInfo size.
using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>;
mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
/// A cache mapping from CXXRecordDecls to key functions.
llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
/// Mapping from ObjCContainers to their ObjCImplementations.
llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
/// Mapping from ObjCMethod to its duplicate declaration in the same
/// interface.
llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
/// Mapping from __block VarDecls to BlockVarCopyInit.
llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
/// Mapping from class scope functions specialization to their
/// template patterns.
llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
ClassScopeSpecializationPattern;
/// Mapping from materialized temporaries with static storage duration
/// that appear in constant initializers to their evaluated values. These are
/// allocated in a std::map because their address must be stable.
llvm::DenseMap<const MaterializeTemporaryExpr *, APValue *>
MaterializedTemporaryValues;
/// Representation of a "canonical" template template parameter that
/// is used in canonical template names.
class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
TemplateTemplateParmDecl *Parm;
public:
CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
: Parm(Parm) {}
TemplateTemplateParmDecl *getParam() const { return Parm; }
void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
static void Profile(llvm::FoldingSetNodeID &ID,
TemplateTemplateParmDecl *Parm);
};
mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
CanonTemplateTemplateParms;
TemplateTemplateParmDecl *
getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
/// The typedef for the __int128_t type.
mutable TypedefDecl *Int128Decl = nullptr;
/// The typedef for the __uint128_t type.
mutable TypedefDecl *UInt128Decl = nullptr;
/// The typedef for the target specific predefined
/// __builtin_va_list type.
mutable TypedefDecl *BuiltinVaListDecl = nullptr;
/// The typedef for the predefined \c __builtin_ms_va_list type.
mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
/// The typedef for the predefined \c id type.
mutable TypedefDecl *ObjCIdDecl = nullptr;
/// The typedef for the predefined \c SEL type.
mutable TypedefDecl *ObjCSelDecl = nullptr;
/// The typedef for the predefined \c Class type.
mutable TypedefDecl *ObjCClassDecl = nullptr;
/// The typedef for the predefined \c Protocol class in Objective-C.
mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
/// The typedef for the predefined 'BOOL' type.
mutable TypedefDecl *BOOLDecl = nullptr;
// Typedefs which may be provided defining the structure of Objective-C
// pseudo-builtins
QualType ObjCIdRedefinitionType;
QualType ObjCClassRedefinitionType;
QualType ObjCSelRedefinitionType;
/// The identifier 'bool'.
mutable IdentifierInfo *BoolName = nullptr;
/// The identifier 'NSObject'.
IdentifierInfo *NSObjectName = nullptr;
/// The identifier 'NSCopying'.
IdentifierInfo *NSCopyingName = nullptr;
/// The identifier '__make_integer_seq'.
mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
/// The identifier '__type_pack_element'.
mutable IdentifierInfo *TypePackElementName = nullptr;
QualType ObjCConstantStringType;
mutable RecordDecl *CFConstantStringTagDecl = nullptr;
mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
mutable QualType ObjCSuperType;
QualType ObjCNSStringType;
/// The typedef declaration for the Objective-C "instancetype" type.
TypedefDecl *ObjCInstanceTypeDecl = nullptr;
/// The type for the C FILE type.
TypeDecl *FILEDecl = nullptr;
/// The type for the C jmp_buf type.
TypeDecl *jmp_bufDecl = nullptr;
/// The type for the C sigjmp_buf type.
TypeDecl *sigjmp_bufDecl = nullptr;
/// The type for the C ucontext_t type.
TypeDecl *ucontext_tDecl = nullptr;
/// Type for the Block descriptor for Blocks CodeGen.
///
/// Since this is only used for generation of debug info, it is not
/// serialized.
mutable RecordDecl *BlockDescriptorType = nullptr;
/// Type for the Block descriptor for Blocks CodeGen.
///
/// Since this is only used for generation of debug info, it is not
/// serialized.
mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
/// Declaration for the CUDA cudaConfigureCall function.
FunctionDecl *cudaConfigureCallDecl = nullptr;
/// Keeps track of all declaration attributes.
///
/// Since so few decls have attrs, we keep them in a hash map instead of
/// wasting space in the Decl class.
llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
/// A mapping from non-redeclarable declarations in modules that were
/// merged with other declarations to the canonical declaration that they were
/// merged into.
llvm::DenseMap<Decl*, Decl*> MergedDecls;
/// A mapping from a defining declaration to a list of modules (other
/// than the owning module of the declaration) that contain merged
/// definitions of that entity.
llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
/// Initializers for a module, in order. Each Decl will be either
/// something that has a semantic effect on startup (such as a variable with
/// a non-constant initializer), or an ImportDecl (which recursively triggers
/// initialization of another module).
struct PerModuleInitializers {
llvm::SmallVector<Decl*, 4> Initializers;
llvm::SmallVector<uint32_t, 4> LazyInitializers;
void resolve(ASTContext &Ctx);
};
llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
ASTContext &this_() { return *this; }
public:
/// A type synonym for the TemplateOrInstantiation mapping.
using TemplateOrSpecializationInfo =
llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
private:
friend class ASTDeclReader;
friend class ASTReader;
friend class ASTWriter;
friend class CXXRecordDecl;
/// A mapping to contain the template or declaration that
/// a variable declaration describes or was instantiated from,
/// respectively.
///
/// For non-templates, this value will be NULL. For variable
/// declarations that describe a variable template, this will be a
/// pointer to a VarTemplateDecl. For static data members
/// of class template specializations, this will be the
/// MemberSpecializationInfo referring to the member variable that was
/// instantiated or specialized. Thus, the mapping will keep track of
/// the static data member templates from which static data members of
/// class template specializations were instantiated.
///
/// Given the following example:
///
/// \code
/// template<typename T>
/// struct X {
/// static T value;
/// };
///
/// template<typename T>
/// T X<T>::value = T(17);
///
/// int *x = &X<int>::value;
/// \endcode
///
/// This mapping will contain an entry that maps from the VarDecl for
/// X<int>::value to the corresponding VarDecl for X<T>::value (within the
/// class template X) and will be marked TSK_ImplicitInstantiation.
llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
TemplateOrInstantiation;
/// Keeps track of the declaration from which a using declaration was
/// created during instantiation.
///
/// The source and target declarations are always a UsingDecl, an
/// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
///
/// For example:
/// \code
/// template<typename T>
/// struct A {
/// void f();
/// };
///
/// template<typename T>
/// struct B : A<T> {
/// using A<T>::f;
/// };
///
/// template struct B<int>;
/// \endcode
///
/// This mapping will contain an entry that maps from the UsingDecl in
/// B<int> to the UnresolvedUsingDecl in B<T>.
llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
InstantiatedFromUsingShadowDecl;
llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
/// Mapping that stores the methods overridden by a given C++
/// member function.
///
/// Since most C++ member functions aren't virtual and therefore
/// don't override anything, we store the overridden functions in
/// this map on the side rather than within the CXXMethodDecl structure.
using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
/// Mapping from each declaration context to its corresponding
/// mangling numbering context (used for constructs like lambdas which
/// need to be consistently numbered for the mangler).
llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
MangleNumberingContexts;
/// Side-table of mangling numbers for declarations which rarely
/// need them (like static local vars).
llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
/// Mapping that stores parameterIndex values for ParmVarDecls when
/// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
ParameterIndexTable ParamIndices;
ImportDecl *FirstLocalImport = nullptr;
ImportDecl *LastLocalImport = nullptr;
TranslationUnitDecl *TUDecl;
mutable ExternCContextDecl *ExternCContext = nullptr;
mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
/// The associated SourceManager object.
SourceManager &SourceMgr;
/// The language options used to create the AST associated with
/// this ASTContext object.
LangOptions &LangOpts;
/// Blacklist object that is used by sanitizers to decide which
/// entities should not be instrumented.
std::unique_ptr<SanitizerBlacklist> SanitizerBL;
/// Function filtering mechanism to determine whether a given function
/// should be imbued with the XRay "always" or "never" attributes.
std::unique_ptr<XRayFunctionFilter> XRayFilter;
/// The allocator used to create AST objects.
///
/// AST objects are never destructed; rather, all memory associated with the
/// AST objects will be released when the ASTContext itself is destroyed.
mutable llvm::BumpPtrAllocator BumpAlloc;
/// Allocator for partial diagnostics.
PartialDiagnostic::StorageAllocator DiagAllocator;
/// The current C++ ABI.
std::unique_ptr<CXXABI> ABI;
CXXABI *createCXXABI(const TargetInfo &T);
/// The logical -> physical address space map.
const LangASMap *AddrSpaceMap = nullptr;
/// Address space map mangling must be used with language specific
/// address spaces (e.g. OpenCL/CUDA)
bool AddrSpaceMapMangling;
const TargetInfo *Target = nullptr;
const TargetInfo *AuxTarget = nullptr;
clang::PrintingPolicy PrintingPolicy;
public:
IdentifierTable &Idents;
SelectorTable &Selectors;
Builtin::Context &BuiltinInfo;
mutable DeclarationNameTable DeclarationNames;
IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
ASTMutationListener *Listener = nullptr;
/// Contains parents of a node.
using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
/// Maps from a node to its parents. This is used for nodes that have
/// pointer identity only, which are more common and we can save space by
/// only storing a unique pointer to them.
using ParentMapPointers =
llvm::DenseMap<const void *,
llvm::PointerUnion4<const Decl *, const Stmt *,
ast_type_traits::DynTypedNode *,
ParentVector *>>;
/// Parent map for nodes without pointer identity. We store a full
/// DynTypedNode for all keys.
using ParentMapOtherNodes =
llvm::DenseMap<ast_type_traits::DynTypedNode,
llvm::PointerUnion4<const Decl *, const Stmt *,
ast_type_traits::DynTypedNode *,
ParentVector *>>;
/// Container for either a single DynTypedNode or for an ArrayRef to
/// DynTypedNode. For use with ParentMap.
class DynTypedNodeList {
using DynTypedNode = ast_type_traits::DynTypedNode;
llvm::AlignedCharArrayUnion<ast_type_traits::DynTypedNode,
ArrayRef<DynTypedNode>> Storage;
bool IsSingleNode;
public:
DynTypedNodeList(const DynTypedNode &N) : IsSingleNode(true) {
new (Storage.buffer) DynTypedNode(N);
}
DynTypedNodeList(ArrayRef<DynTypedNode> A) : IsSingleNode(false) {
new (Storage.buffer) ArrayRef<DynTypedNode>(A);
}
const ast_type_traits::DynTypedNode *begin() const {
if (!IsSingleNode)
return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
->begin();
return reinterpret_cast<const DynTypedNode *>(Storage.buffer);
}
const ast_type_traits::DynTypedNode *end() const {
if (!IsSingleNode)
return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
->end();
return reinterpret_cast<const DynTypedNode *>(Storage.buffer) + 1;
}
size_t size() const { return end() - begin(); }
bool empty() const { return begin() == end(); }
const DynTypedNode &operator[](size_t N) const {
assert(N < size() && "Out of bounds!");
return *(begin() + N);
}
};
/// Returns the parents of the given node.
///
/// Note that this will lazily compute the parents of all nodes
/// and store them for later retrieval. Thus, the first call is O(n)
/// in the number of AST nodes.
///
/// Caveats and FIXMEs:
/// Calculating the parent map over all AST nodes will need to load the
/// full AST. This can be undesirable in the case where the full AST is
/// expensive to create (for example, when using precompiled header
/// preambles). Thus, there are good opportunities for optimization here.
/// One idea is to walk the given node downwards, looking for references
/// to declaration contexts - once a declaration context is found, compute
/// the parent map for the declaration context; if that can satisfy the
/// request, loading the whole AST can be avoided. Note that this is made
/// more complex by statements in templates having multiple parents - those
/// problems can be solved by building closure over the templated parts of
/// the AST, which also avoids touching large parts of the AST.
/// Additionally, we will want to add an interface to already give a hint
/// where to search for the parents, for example when looking at a statement
/// inside a certain function.
///
/// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
/// NestedNameSpecifier or NestedNameSpecifierLoc.
template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node) {
return getParents(ast_type_traits::DynTypedNode::create(Node));
}
DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node);
const clang::PrintingPolicy &getPrintingPolicy() const {
return PrintingPolicy;
}
void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
PrintingPolicy = Policy;
}
SourceManager& getSourceManager() { return SourceMgr; }
const SourceManager& getSourceManager() const { return SourceMgr; }
llvm::BumpPtrAllocator &getAllocator() const {
return BumpAlloc;
}
void *Allocate(size_t Size, unsigned Align = 8) const {
return BumpAlloc.Allocate(Size, Align);
}
template <typename T> T *Allocate(size_t Num = 1) const {
return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
}
void Deallocate(void *Ptr) const {}
/// Return the total amount of physical memory allocated for representing
/// AST nodes and type information.
size_t getASTAllocatedMemory() const {
return BumpAlloc.getTotalMemory();
}
/// Return the total memory used for various side tables.
size_t getSideTableAllocatedMemory() const;
PartialDiagnostic::StorageAllocator &getDiagAllocator() {
return DiagAllocator;
}
const TargetInfo &getTargetInfo() const { return *Target; }
const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
/// getIntTypeForBitwidth -
/// sets integer QualTy according to specified details:
/// bitwidth, signed/unsigned.
/// Returns empty type if there is no appropriate target types.
QualType getIntTypeForBitwidth(unsigned DestWidth,
unsigned Signed) const;
/// getRealTypeForBitwidth -
/// sets floating point QualTy according to specified bitwidth.
/// Returns empty type if there is no appropriate target types.
QualType getRealTypeForBitwidth(unsigned DestWidth) const;
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
const LangOptions& getLangOpts() const { return LangOpts; }
const SanitizerBlacklist &getSanitizerBlacklist() const {
return *SanitizerBL;
}
const XRayFunctionFilter &getXRayFilter() const {
return *XRayFilter;
}
DiagnosticsEngine &getDiagnostics() const;
FullSourceLoc getFullLoc(SourceLocation Loc) const {
return FullSourceLoc(Loc,SourceMgr);
}
/// All comments in this translation unit.
RawCommentList Comments;
/// True if comments are already loaded from ExternalASTSource.
mutable bool CommentsLoaded = false;
class RawCommentAndCacheFlags {
public:
enum Kind {
/// We searched for a comment attached to the particular declaration, but
/// didn't find any.
///
/// getRaw() == 0.
NoCommentInDecl = 0,
/// We have found a comment attached to this particular declaration.
///
/// getRaw() != 0.
FromDecl,
/// This declaration does not have an attached comment, and we have
/// searched the redeclaration chain.
///
/// If getRaw() == 0, the whole redeclaration chain does not have any
/// comments.
///
/// If getRaw() != 0, it is a comment propagated from other
/// redeclaration.
FromRedecl
};
Kind getKind() const LLVM_READONLY {
return Data.getInt();
}
void setKind(Kind K) {
Data.setInt(K);
}
const RawComment *getRaw() const LLVM_READONLY {
return Data.getPointer();
}
void setRaw(const RawComment *RC) {
Data.setPointer(RC);
}
const Decl *getOriginalDecl() const LLVM_READONLY {
return OriginalDecl;
}
void setOriginalDecl(const Decl *Orig) {
OriginalDecl = Orig;
}
private:
llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
const Decl *OriginalDecl;
};
/// Mapping from declarations to comments attached to any
/// redeclaration.
///
/// Raw comments are owned by Comments list. This mapping is populated
/// lazily.
mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
/// Mapping from declarations to parsed comments attached to any
/// redeclaration.
mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
/// Return the documentation comment attached to a given declaration,
/// without looking into cache.
RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
public:
RawCommentList &getRawCommentList() {
return Comments;
}
void addComment(const RawComment &RC) {
assert(LangOpts.RetainCommentsFromSystemHeaders ||
!SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
}
/// Return the documentation comment attached to a given declaration.
/// Returns nullptr if no comment is attached.
///
/// \param OriginalDecl if not nullptr, is set to declaration AST node that
/// had the comment, if the comment we found comes from a redeclaration.
const RawComment *
getRawCommentForAnyRedecl(const Decl *D,
const Decl **OriginalDecl = nullptr) const;
/// Return parsed documentation comment attached to a given declaration.
/// Returns nullptr if no comment is attached.
///
/// \param PP the Preprocessor used with this TU. Could be nullptr if
/// preprocessor is not available.
comments::FullComment *getCommentForDecl(const Decl *D,
const Preprocessor *PP) const;
/// Return parsed documentation comment attached to a given declaration.
/// Returns nullptr if no comment is attached. Does not look at any
/// redeclarations of the declaration.
comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
comments::FullComment *cloneFullComment(comments::FullComment *FC,
const Decl *D) const;
private:
mutable comments::CommandTraits CommentCommandTraits;
/// Iterator that visits import declarations.
class import_iterator {
ImportDecl *Import = nullptr;
public:
using value_type = ImportDecl *;
using reference = ImportDecl *;
using pointer = ImportDecl *;
using difference_type = int;
using iterator_category = std::forward_iterator_tag;
import_iterator() = default;
explicit import_iterator(ImportDecl *Import) : Import(Import) {}
reference operator*() const { return Import; }
pointer operator->() const { return Import; }
import_iterator &operator++() {
Import = ASTContext::getNextLocalImport(Import);
return *this;
}
import_iterator operator++(int) {
import_iterator Other(*this);
++(*this);
return Other;
}
friend bool operator==(import_iterator X, import_iterator Y) {
return X.Import == Y.Import;
}
friend bool operator!=(import_iterator X, import_iterator Y) {
return X.Import != Y.Import;
}
};
public:
comments::CommandTraits &getCommentCommandTraits() const {
return CommentCommandTraits;
}
/// Retrieve the attributes for the given declaration.
AttrVec& getDeclAttrs(const Decl *D);
/// Erase the attributes corresponding to the given declaration.
void eraseDeclAttrs(const Decl *D);
/// If this variable is an instantiated static data member of a
/// class template specialization, returns the templated static data member
/// from which it was instantiated.
// FIXME: Remove ?
MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
const VarDecl *Var);
TemplateOrSpecializationInfo
getTemplateOrSpecializationInfo(const VarDecl *Var);
FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
void setClassScopeSpecializationPattern(FunctionDecl *FD,
FunctionDecl *Pattern);
/// Note that the static data member \p Inst is an instantiation of
/// the static data member template \p Tmpl of a class template.
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
TemplateSpecializationKind TSK,
SourceLocation PointOfInstantiation = SourceLocation());
void setTemplateOrSpecializationInfo(VarDecl *Inst,
TemplateOrSpecializationInfo TSI);
/// If the given using decl \p Inst is an instantiation of a
/// (possibly unresolved) using decl from a template instantiation,
/// return it.
NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
/// Remember that the using decl \p Inst is an instantiation
/// of the using decl \p Pattern of a class template.
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
UsingShadowDecl *Pattern);
UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
// Access to the set of methods overridden by the given C++ method.
using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
overridden_cxx_method_iterator
overridden_methods_begin(const CXXMethodDecl *Method) const;
overridden_cxx_method_iterator
overridden_methods_end(const CXXMethodDecl *Method) const;
unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
using overridden_method_range =
llvm::iterator_range<overridden_cxx_method_iterator>;
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
/// Note that the given C++ \p Method overrides the given \p
/// Overridden method.
void addOverriddenMethod(const CXXMethodDecl *Method,
const CXXMethodDecl *Overridden);
/// Return C++ or ObjC overridden methods for the given \p Method.
///
/// An ObjC method is considered to override any method in the class's
/// base classes, its protocols, or its categories' protocols, that has
/// the same selector and is of the same kind (class or instance).
/// A method in an implementation is not considered as overriding the same
/// method in the interface or its categories.
void getOverriddenMethods(
const NamedDecl *Method,
SmallVectorImpl<const NamedDecl *> &Overridden) const;
/// Notify the AST context that a new import declaration has been
/// parsed or implicitly created within this translation unit.
void addedLocalImportDecl(ImportDecl *Import);
static ImportDecl *getNextLocalImport(ImportDecl *Import) {
return Import->NextLocalImport;
}
using import_range = llvm::iterator_range<import_iterator>;
import_range local_imports() const {
return import_range(import_iterator(FirstLocalImport), import_iterator());
}
Decl *getPrimaryMergedDecl(Decl *D) {
Decl *Result = MergedDecls.lookup(D);
return Result ? Result : D;
}
void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
MergedDecls[D] = Primary;
}
/// Note that the definition \p ND has been merged into module \p M,
/// and should be visible whenever \p M is visible.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
bool NotifyListeners = true);
/// Clean up the merged definition list. Call this if you might have
/// added duplicates into the list.
void deduplicateMergedDefinitonsFor(NamedDecl *ND);
/// Get the additional modules in which the definition \p Def has
/// been merged.
ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def) {
auto MergedIt = MergedDefModules.find(Def);
if (MergedIt == MergedDefModules.end())
return None;
return MergedIt->second;
}
/// Add a declaration to the list of declarations that are initialized
/// for a module. This will typically be a global variable (with internal
/// linkage) that runs module initializers, such as the iostream initializer,
/// or an ImportDecl nominating another module that has initializers.
void addModuleInitializer(Module *M, Decl *Init);
void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs);
/// Get the initializations to perform when importing a module, if any.
ArrayRef<Decl*> getModuleInitializers(Module *M);
TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
ExternCContextDecl *getExternCContextDecl() const;
BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
BuiltinTemplateDecl *getTypePackElementDecl() const;
// Builtin Types.
CanQualType VoidTy;
CanQualType BoolTy;
CanQualType CharTy;
CanQualType WCharTy; // [C++ 3.9.1p5].
CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
CanQualType Char8Ty; // [C++20 proposal]
CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty;
CanQualType ShortAccumTy, AccumTy,
LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension
CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
CanQualType ShortFractTy, FractTy, LongFractTy;
CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy;
CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy,
SatUnsignedLongAccumTy;
CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
SatUnsignedLongFractTy;
CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
CanQualType Float128ComplexTy;
CanQualType VoidPtrTy, NullPtrTy;
CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
CanQualType BuiltinFnTy;
CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
CanQualType ObjCBuiltinBoolTy;
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
CanQualType SingletonId;
#include "clang/Basic/OpenCLImageTypes.def"
CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
CanQualType OCLQueueTy, OCLReserveIDTy;
CanQualType OMPArraySectionTy;
// Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
mutable QualType AutoDeductTy; // Deduction against 'auto'.
mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
// Decl used to help define __builtin_va_list for some targets.
// The decl is built when constructing 'BuiltinVaListDecl'.
mutable Decl *VaListTagDecl;
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
SelectorTable &sels, Builtin::Context &builtins);
ASTContext(const ASTContext &) = delete;
ASTContext &operator=(const ASTContext &) = delete;
~ASTContext();
/// Attach an external AST source to the AST context.
///
/// The external AST source provides the ability to load parts of
/// the abstract syntax tree as needed from some external storage,
/// e.g., a precompiled header.
void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
/// Retrieve a pointer to the external AST source associated
/// with this AST context, if any.
ExternalASTSource *getExternalSource() const {
return ExternalSource.get();
}
/// Attach an AST mutation listener to the AST context.
///
/// The AST mutation listener provides the ability to track modifications to
/// the abstract syntax tree entities committed after they were initially
/// created.
void setASTMutationListener(ASTMutationListener *Listener) {
this->Listener = Listener;
}
/// Retrieve a pointer to the AST mutation listener associated
/// with this AST context, if any.
ASTMutationListener *getASTMutationListener() const { return Listener; }
void PrintStats() const;
const SmallVectorImpl<Type *>& getTypes() const { return Types; }
BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
const IdentifierInfo *II) const;
/// Create a new implicit TU-level CXXRecordDecl or RecordDecl
/// declaration.
RecordDecl *buildImplicitRecord(StringRef Name,
RecordDecl::TagKind TK = TTK_Struct) const;
/// Create a new implicit TU-level typedef declaration.
TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
/// Retrieve the declaration for the 128-bit signed integer type.
TypedefDecl *getInt128Decl() const;
/// Retrieve the declaration for the 128-bit unsigned integer type.
TypedefDecl *getUInt128Decl() const;
//===--------------------------------------------------------------------===//
// Type Constructors
//===--------------------------------------------------------------------===//
private:
/// Return a type with extended qualifiers.
QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
QualType getPipeType(QualType T, bool ReadOnly) const;
public:
/// Return the uniqued reference to the type for an address space
/// qualified type with the specified type and address space.
///
/// The resulting type has a union of the qualifiers from T and the address
/// space. If T already has an address space specifier, it is silently
/// replaced.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
/// Remove any existing address space on the type and returns the type
/// with qualifiers intact (or that's the idea anyway)
///
/// The return type should be T with all prior qualifiers minus the address
/// space.
QualType removeAddrSpaceQualType(QualType T) const;
/// Apply Objective-C protocol qualifiers to the given type.
/// \param allowOnPointerType specifies if we can apply protocol
/// qualifiers on ObjCObjectPointerType. It can be set to true when
/// constructing the canonical type of a Objective-C type parameter.
QualType applyObjCProtocolQualifiers(QualType type,
ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
bool allowOnPointerType = false) const;
/// Return the uniqued reference to the type for an Objective-C
/// gc-qualified type.
///
/// The resulting type has a union of the qualifiers from T and the gc
/// attribute.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
/// Return the uniqued reference to the type for a \c restrict
/// qualified type.
///
/// The resulting type has a union of the qualifiers from \p T and
/// \c restrict.
QualType getRestrictType(QualType T) const {
return T.withFastQualifiers(Qualifiers::Restrict);
}
/// Return the uniqued reference to the type for a \c volatile
/// qualified type.
///
/// The resulting type has a union of the qualifiers from \p T and
/// \c volatile.
QualType getVolatileType(QualType T) const {
return T.withFastQualifiers(Qualifiers::Volatile);
}
/// Return the uniqued reference to the type for a \c const
/// qualified type.
///
/// The resulting type has a union of the qualifiers from \p T and \c const.
///
/// It can be reasonably expected that this will always be equivalent to
/// calling T.withConst().
QualType getConstType(QualType T) const { return T.withConst(); }
/// Change the ExtInfo on a function type.
const FunctionType *adjustFunctionType(const FunctionType *Fn,
FunctionType::ExtInfo EInfo);
/// Adjust the given function result type.
CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
/// Change the result type of a function type once it is deduced.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
/// Get a function type and produce the equivalent function type with the
/// specified exception specification. Type sugar that can be present on a
/// declaration of a function with an exception specification is permitted
/// and preserved. Other type sugar (for instance, typedefs) is not.
QualType getFunctionTypeWithExceptionSpec(
QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI);
/// Determine whether two function types are the same, ignoring
/// exception specifications in cases where they're part of the type.
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U);
/// Change the exception specification on a function once it is
/// delay-parsed, instantiated, or computed.
void adjustExceptionSpec(FunctionDecl *FD,
const FunctionProtoType::ExceptionSpecInfo &ESI,
bool AsWritten = false);
/// Return the uniqued reference to the type for a complex
/// number with the specified element type.
QualType getComplexType(QualType T) const;
CanQualType getComplexType(CanQualType T) const {
return CanQualType::CreateUnsafe(getComplexType((QualType) T));
}
/// Return the uniqued reference to the type for a pointer to
/// the specified type.
QualType getPointerType(QualType T) const;
CanQualType getPointerType(CanQualType T) const {
return CanQualType::CreateUnsafe(getPointerType((QualType) T));
}
/// Return the uniqued reference to a type adjusted from the original
/// type to a new type.
QualType getAdjustedType(QualType Orig, QualType New) const;
CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
return CanQualType::CreateUnsafe(
getAdjustedType((QualType)Orig, (QualType)New));
}
/// Return the uniqued reference to the decayed version of the given
/// type. Can only be called on array and function types which decay to
/// pointer types.
QualType getDecayedType(QualType T) const;
CanQualType getDecayedType(CanQualType T) const {
return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
}
/// Return the uniqued reference to the atomic type for the specified
/// type.
QualType getAtomicType(QualType T) const;
/// Return the uniqued reference to the type for a block of the
/// specified type.
QualType getBlockPointerType(QualType T) const;
/// Gets the struct used to keep track of the descriptor for pointer to
/// blocks.
QualType getBlockDescriptorType() const;
/// Return a read_only pipe type for the specified type.
QualType getReadPipeType(QualType T) const;
/// Return a write_only pipe type for the specified type.
QualType getWritePipeType(QualType T) const;
/// Gets the struct used to keep track of the extended descriptor for
/// pointer to blocks.
QualType getBlockDescriptorExtendedType() const;
/// Map an AST Type to an OpenCLTypeKind enum value.
TargetInfo::OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
/// Get address space for OpenCL type.
LangAS getOpenCLTypeAddrSpace(const Type *T) const;
void setcudaConfigureCallDecl(FunctionDecl *FD) {
cudaConfigureCallDecl = FD;
}
FunctionDecl *getcudaConfigureCallDecl() {
return cudaConfigureCallDecl;
}
/// Returns true iff we need copy/dispose helpers for the given type.
bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
/// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
/// is set to false in this case. If HasByrefExtendedLayout returns true,
/// byref variable has extended lifetime.
bool getByrefLifetime(QualType Ty,
Qualifiers::ObjCLifetime &Lifetime,
bool &HasByrefExtendedLayout) const;
/// Return the uniqued reference to the type for an lvalue reference
/// to the specified type.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
const;
/// Return the uniqued reference to the type for an rvalue reference
/// to the specified type.
QualType getRValueReferenceType(QualType T) const;
/// Return the uniqued reference to the type for a member pointer to
/// the specified type in the specified class.
///
/// The class \p Cls is a \c Type because it could be a dependent name.
QualType getMemberPointerType(QualType T, const Type *Cls) const;
/// Return a non-unique reference to the type for a variable array of
/// the specified element type.
QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
ArrayType::ArraySizeModifier ASM,
unsigned IndexTypeQuals,
SourceRange Brackets) const;
/// Return a non-unique reference to the type for a dependently-sized
/// array of the specified element type.
///
/// FIXME: We will need these to be uniqued, or at least comparable, at some
/// point.
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
ArrayType::ArraySizeModifier ASM,
unsigned IndexTypeQuals,
SourceRange Brackets) const;
/// Return a unique reference to the type for an incomplete array of
/// the specified element type.
QualType getIncompleteArrayType(QualType EltTy,
ArrayType::ArraySizeModifier ASM,
unsigned IndexTypeQuals) const;
/// Return the unique reference to the type for a constant array of
/// the specified element type.
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
ArrayType::ArraySizeModifier ASM,
unsigned IndexTypeQuals) const;
/// Returns a vla type where known sizes are replaced with [*].
QualType getVariableArrayDecayedType(QualType Ty) const;
/// Return the unique reference to a vector type of the specified
/// element type and size.
///
/// \pre \p VectorType must be a built-in type.
QualType getVectorType(QualType VectorType, unsigned NumElts,
VectorType::VectorKind VecKind) const;
/// Return the unique reference to the type for a dependently sized vector of
/// the specified element type.
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr,
SourceLocation AttrLoc,
VectorType::VectorKind VecKind) const;
/// Return the unique reference to an extended vector type
/// of the specified element type and size.
///
/// \pre \p VectorType must be a built-in type.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
/// \pre Return a non-unique reference to the type for a dependently-sized
/// vector of the specified element type.
///
/// FIXME: We will need these to be uniqued, or at least comparable, at some
/// point.
QualType getDependentSizedExtVectorType(QualType VectorType,
Expr *SizeExpr,
SourceLocation AttrLoc) const;
QualType getDependentAddressSpaceType(QualType PointeeType,
Expr *AddrSpaceExpr,
SourceLocation AttrLoc) const;
/// Return a K&R style C function type like 'int()'.
QualType getFunctionNoProtoType(QualType ResultTy,
const FunctionType::ExtInfo &Info) const;
QualType getFunctionNoProtoType(QualType ResultTy) const {
return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
}
/// Return a normal function type with a typed argument list.
QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
const FunctionProtoType::ExtProtoInfo &EPI) const {
return getFunctionTypeInternal(ResultTy, Args, EPI, false);
}
QualType adjustStringLiteralBaseType(QualType StrLTy) const;
private:
/// Return a normal function type with a typed argument list.
QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
const FunctionProtoType::ExtProtoInfo &EPI,
bool OnlyWantCanonical) const;
public:
/// Return the unique reference to the type for the specified type
/// declaration.
QualType getTypeDeclType(const TypeDecl *Decl,
const TypeDecl *PrevDecl = nullptr) const {
assert(Decl && "Passed null for Decl param");
if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
if (PrevDecl) {
assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
Decl->TypeForDecl = PrevDecl->TypeForDecl;
return QualType(PrevDecl->TypeForDecl, 0);
}
return getTypeDeclTypeSlow(Decl);
}
/// Return the unique reference to the type for the specified
/// typedef-name decl.
QualType getTypedefType(const TypedefNameDecl *Decl,
QualType Canon = QualType()) const;
QualType getRecordType(const RecordDecl *Decl) const;
QualType getEnumType(const EnumDecl *Decl) const;
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
- QualType getAttributedType(attr::Kind attrKind,
+ QualType getAttributedType(AttributedType::Kind attrKind,
QualType modifiedType,
QualType equivalentType);
QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
QualType Replacement) const;
QualType getSubstTemplateTypeParmPackType(
const TemplateTypeParmType *Replaced,
const TemplateArgument &ArgPack);
QualType
getTemplateTypeParmType(unsigned Depth, unsigned Index,
bool ParameterPack,
TemplateTypeParmDecl *ParmDecl = nullptr) const;
QualType getTemplateSpecializationType(TemplateName T,
ArrayRef<TemplateArgument> Args,
QualType Canon = QualType()) const;
QualType
getCanonicalTemplateSpecializationType(TemplateName T,
ArrayRef<TemplateArgument> Args) const;
QualType getTemplateSpecializationType(TemplateName T,
const TemplateArgumentListInfo &Args,
QualType Canon = QualType()) const;
TypeSourceInfo *
getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
const TemplateArgumentListInfo &Args,
QualType Canon = QualType()) const;
QualType getParenType(QualType NamedType) const;
QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
NestedNameSpecifier *NNS, QualType NamedType,
TagDecl *OwnedTagDecl = nullptr) const;
QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
NestedNameSpecifier *NNS,
const IdentifierInfo *Name,
QualType Canon = QualType()) const;
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
NestedNameSpecifier *NNS,
const IdentifierInfo *Name,
const TemplateArgumentListInfo &Args) const;
QualType getDependentTemplateSpecializationType(
ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
/// Get a template argument list with one argument per template parameter
/// in a template parameter list, such as for the injected class name of
/// a class template.
void getInjectedTemplateArgs(const TemplateParameterList *Params,
SmallVectorImpl<TemplateArgument> &Args);
QualType getPackExpansionType(QualType Pattern,
Optional<unsigned> NumExpansions);
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
ObjCInterfaceDecl *PrevDecl = nullptr) const;
/// Legacy interface: cannot provide type arguments or __kindof.
QualType getObjCObjectType(QualType Base,
ObjCProtocolDecl * const *Protocols,
unsigned NumProtocols) const;
QualType getObjCObjectType(QualType Base,
ArrayRef<QualType> typeArgs,
ArrayRef<ObjCProtocolDecl *> protocols,
bool isKindOf) const;
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
ArrayRef<ObjCProtocolDecl *> protocols,
QualType Canonical = QualType()) const;
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
/// QT's qualified-id protocol list adopt all protocols in IDecl's list
/// of protocols.
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
ObjCInterfaceDecl *IDecl);
/// Return a ObjCObjectPointerType type for the given ObjCObjectType.
QualType getObjCObjectPointerType(QualType OIT) const;
/// GCC extension.
QualType getTypeOfExprType(Expr *e) const;
QualType getTypeOfType(QualType t) const;
/// C++11 decltype.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
/// Unary type transforms
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
UnaryTransformType::UTTKind UKind) const;
/// C++11 deduced auto type.
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
bool IsDependent) const;
/// C++11 deduction pattern for 'auto' type.
QualType getAutoDeductType() const;
/// C++11 deduction pattern for 'auto &&' type.
QualType getAutoRRefDeductType() const;
/// C++17 deduced class template specialization type.
QualType getDeducedTemplateSpecializationType(TemplateName Template,
QualType DeducedType,
bool IsDependent) const;
/// Return the unique reference to the type for the specified TagDecl
/// (struct/union/class/enum) decl.
QualType getTagDeclType(const TagDecl *Decl) const;
/// Return the unique type for "size_t" (C99 7.17), defined in
/// <stddef.h>.
///
/// The sizeof operator requires this (C99 6.5.3.4p4).
CanQualType getSizeType() const;
/// Return the unique signed counterpart of
/// the integer type corresponding to size_t.
CanQualType getSignedSizeType() const;
/// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
/// <stdint.h>.
CanQualType getIntMaxType() const;
/// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
/// <stdint.h>.
CanQualType getUIntMaxType() const;
/// Return the unique wchar_t type available in C++ (and available as
/// __wchar_t as a Microsoft extension).
QualType getWCharType() const { return WCharTy; }
/// Return the type of wide characters. In C++, this returns the
/// unique wchar_t type. In C99, this returns a type compatible with the type
/// defined in <stddef.h> as defined by the target.
QualType getWideCharType() const { return WideCharTy; }
/// Return the type of "signed wchar_t".
///
/// Used when in C++, as a GCC extension.
QualType getSignedWCharType() const;
/// Return the type of "unsigned wchar_t".
///
/// Used when in C++, as a GCC extension.
QualType getUnsignedWCharType() const;
/// In C99, this returns a type compatible with the type
/// defined in <stddef.h> as defined by the target.
QualType getWIntType() const { return WIntTy; }
/// Return a type compatible with "intptr_t" (C99 7.18.1.4),
/// as defined by the target.
QualType getIntPtrType() const;
/// Return a type compatible with "uintptr_t" (C99 7.18.1.4),
/// as defined by the target.
QualType getUIntPtrType() const;
/// Return the unique type for "ptrdiff_t" (C99 7.17) defined in
/// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
QualType getPointerDiffType() const;
/// Return the unique unsigned counterpart of "ptrdiff_t"
/// integer type. The standard (C11 7.21.6.1p7) refers to this type
/// in the definition of %tu format specifier.
QualType getUnsignedPointerDiffType() const;
/// Return the unique type for "pid_t" defined in
/// <sys/types.h>. We need this to compute the correct type for vfork().
QualType getProcessIDType() const;
/// Return the C structure type used to represent constant CFStrings.
QualType getCFConstantStringType() const;
/// Returns the C struct type for objc_super
QualType getObjCSuperType() const;
void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
/// Get the structure type used to representation CFStrings, or NULL
/// if it hasn't yet been built.
QualType getRawCFConstantStringType() const {
if (CFConstantStringTypeDecl)
return getTypedefType(CFConstantStringTypeDecl);
return QualType();
}
void setCFConstantStringType(QualType T);
TypedefDecl *getCFConstantStringDecl() const;
RecordDecl *getCFConstantStringTagDecl() const;
// This setter/getter represents the ObjC type for an NSConstantString.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
QualType getObjCConstantStringInterface() const {
return ObjCConstantStringType;
}
QualType getObjCNSStringType() const {
return ObjCNSStringType;
}
void setObjCNSStringType(QualType T) {
ObjCNSStringType = T;
}
/// Retrieve the type that \c id has been defined to, which may be
/// different from the built-in \c id if \c id has been typedef'd.
QualType getObjCIdRedefinitionType() const {
if (ObjCIdRedefinitionType.isNull())
return getObjCIdType();
return ObjCIdRedefinitionType;
}
/// Set the user-written type that redefines \c id.
void setObjCIdRedefinitionType(QualType RedefType) {
ObjCIdRedefinitionType = RedefType;
}
/// Retrieve the type that \c Class has been defined to, which may be
/// different from the built-in \c Class if \c Class has been typedef'd.
QualType getObjCClassRedefinitionType() const {
if (ObjCClassRedefinitionType.isNull())
return getObjCClassType();
return ObjCClassRedefinitionType;
}
/// Set the user-written type that redefines 'SEL'.
void setObjCClassRedefinitionType(QualType RedefType) {
ObjCClassRedefinitionType = RedefType;
}
/// Retrieve the type that 'SEL' has been defined to, which may be
/// different from the built-in 'SEL' if 'SEL' has been typedef'd.
QualType getObjCSelRedefinitionType() const {
if (ObjCSelRedefinitionType.isNull())
return getObjCSelType();
return ObjCSelRedefinitionType;
}
/// Set the user-written type that redefines 'SEL'.
void setObjCSelRedefinitionType(QualType RedefType) {
ObjCSelRedefinitionType = RedefType;
}
/// Retrieve the identifier 'NSObject'.
IdentifierInfo *getNSObjectName() {
if (!NSObjectName) {
NSObjectName = &Idents.get("NSObject");
}
return NSObjectName;
}
/// Retrieve the identifier 'NSCopying'.
IdentifierInfo *getNSCopyingName() {
if (!NSCopyingName) {
NSCopyingName = &Idents.get("NSCopying");
}
return NSCopyingName;
}
CanQualType getNSUIntegerType() const {
assert(Target && "Expected target to be initialized");
const llvm::Triple &T = Target->getTriple();
// Windows is LLP64 rather than LP64
if (T.isOSWindows() && T.isArch64Bit())
return UnsignedLongLongTy;
return UnsignedLongTy;
}
CanQualType getNSIntegerType() const {
assert(Target && "Expected target to be initialized");
const llvm::Triple &T = Target->getTriple();
// Windows is LLP64 rather than LP64
if (T.isOSWindows() && T.isArch64Bit())
return LongLongTy;
return LongTy;
}
/// Retrieve the identifier 'bool'.
IdentifierInfo *getBoolName() const {
if (!BoolName)
BoolName = &Idents.get("bool");
return BoolName;
}
IdentifierInfo *getMakeIntegerSeqName() const {
if (!MakeIntegerSeqName)
MakeIntegerSeqName = &Idents.get("__make_integer_seq");
return MakeIntegerSeqName;
}
IdentifierInfo *getTypePackElementName() const {
if (!TypePackElementName)
TypePackElementName = &Idents.get("__type_pack_element");
return TypePackElementName;
}
/// Retrieve the Objective-C "instancetype" type, if already known;
/// otherwise, returns a NULL type;
QualType getObjCInstanceType() {
return getTypeDeclType(getObjCInstanceTypeDecl());
}
/// Retrieve the typedef declaration corresponding to the Objective-C
/// "instancetype" type.
TypedefDecl *getObjCInstanceTypeDecl();
/// Set the type for the C FILE type.
void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
/// Retrieve the C FILE type.
QualType getFILEType() const {
if (FILEDecl)
return getTypeDeclType(FILEDecl);
return QualType();
}
/// Set the type for the C jmp_buf type.
void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
this->jmp_bufDecl = jmp_bufDecl;
}
/// Retrieve the C jmp_buf type.
QualType getjmp_bufType() const {
if (jmp_bufDecl)
return getTypeDeclType(jmp_bufDecl);
return QualType();
}
/// Set the type for the C sigjmp_buf type.
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
this->sigjmp_bufDecl = sigjmp_bufDecl;
}
/// Retrieve the C sigjmp_buf type.
QualType getsigjmp_bufType() const {
if (sigjmp_bufDecl)
return getTypeDeclType(sigjmp_bufDecl);
return QualType();
}
/// Set the type for the C ucontext_t type.
void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
this->ucontext_tDecl = ucontext_tDecl;
}
/// Retrieve the C ucontext_t type.
QualType getucontext_tType() const {
if (ucontext_tDecl)
return getTypeDeclType(ucontext_tDecl);
return QualType();
}
/// The result type of logical operations, '<', '>', '!=', etc.
QualType getLogicalOperationType() const {
return getLangOpts().CPlusPlus ? BoolTy : IntTy;
}
/// Emit the Objective-CC type encoding for the given type \p T into
/// \p S.
///
/// If \p Field is specified then record field names are also encoded.
void getObjCEncodingForType(QualType T, std::string &S,
const FieldDecl *Field=nullptr,
QualType *NotEncodedT=nullptr) const;
/// Emit the Objective-C property type encoding for the given
/// type \p T into \p S.
void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
void getLegacyIntegralTypeEncoding(QualType &t) const;
/// Put the string version of the type qualifiers \p QT into \p S.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
std::string &S) const;
/// Emit the encoded type for the function \p Decl into \p S.
///
/// This is in the same format as Objective-C method encodings.
///
/// \returns true if an error occurred (e.g., because one of the parameter
/// types is incomplete), false otherwise.
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
/// Emit the encoded type for the method declaration \p Decl into
/// \p S.
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
bool Extended = false) const;
/// Return the encoded type for this block declaration.
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
/// getObjCEncodingForPropertyDecl - Return the encoded type for
/// this method declaration. If non-NULL, Container must be either
/// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
/// only be NULL when getting encodings for protocol properties.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
const Decl *Container) const;
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
ObjCProtocolDecl *rProto) const;
ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
const ObjCPropertyDecl *PD,
const Decl *Container) const;
/// Return the size of type \p T for Objective-C encoding purpose,
/// in characters.
CharUnits getObjCEncodingTypeSize(QualType T) const;
/// Retrieve the typedef corresponding to the predefined \c id type
/// in Objective-C.
TypedefDecl *getObjCIdDecl() const;
/// Represents the Objective-CC \c id type.
///
/// This is set up lazily, by Sema. \c id is always a (typedef for a)
/// pointer type, a pointer to a struct.
QualType getObjCIdType() const {
return getTypeDeclType(getObjCIdDecl());
}
/// Retrieve the typedef corresponding to the predefined 'SEL' type
/// in Objective-C.
TypedefDecl *getObjCSelDecl() const;
/// Retrieve the type that corresponds to the predefined Objective-C
/// 'SEL' type.
QualType getObjCSelType() const {
return getTypeDeclType(getObjCSelDecl());
}
/// Retrieve the typedef declaration corresponding to the predefined
/// Objective-C 'Class' type.
TypedefDecl *getObjCClassDecl() const;
/// Represents the Objective-C \c Class type.
///
/// This is set up lazily, by Sema. \c Class is always a (typedef for a)
/// pointer type, a pointer to a struct.
QualType getObjCClassType() const {
return getTypeDeclType(getObjCClassDecl());
}
/// Retrieve the Objective-C class declaration corresponding to
/// the predefined \c Protocol class.
ObjCInterfaceDecl *getObjCProtocolDecl() const;
/// Retrieve declaration of 'BOOL' typedef
TypedefDecl *getBOOLDecl() const {
return BOOLDecl;
}
/// Save declaration of 'BOOL' typedef
void setBOOLDecl(TypedefDecl *TD) {
BOOLDecl = TD;
}
/// type of 'BOOL' type.
QualType getBOOLType() const {
return getTypeDeclType(getBOOLDecl());
}
/// Retrieve the type of the Objective-C \c Protocol class.
QualType getObjCProtoType() const {
return getObjCInterfaceType(getObjCProtocolDecl());
}
/// Retrieve the C type declaration corresponding to the predefined
/// \c __builtin_va_list type.
TypedefDecl *getBuiltinVaListDecl() const;
/// Retrieve the type of the \c __builtin_va_list type.
QualType getBuiltinVaListType() const {
return getTypeDeclType(getBuiltinVaListDecl());
}
/// Retrieve the C type declaration corresponding to the predefined
/// \c __va_list_tag type used to help define the \c __builtin_va_list type
/// for some targets.
Decl *getVaListTagDecl() const;
/// Retrieve the C type declaration corresponding to the predefined
/// \c __builtin_ms_va_list type.
TypedefDecl *getBuiltinMSVaListDecl() const;
/// Retrieve the type of the \c __builtin_ms_va_list type.
QualType getBuiltinMSVaListType() const {
return getTypeDeclType(getBuiltinMSVaListDecl());
}
/// Return whether a declaration to a builtin is allowed to be
/// overloaded/redeclared.
bool canBuiltinBeRedeclared(const FunctionDecl *) const;
/// Return a type with additional \c const, \c volatile, or
/// \c restrict qualifiers.
QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
}
/// Un-split a SplitQualType.
QualType getQualifiedType(SplitQualType split) const {
return getQualifiedType(split.Ty, split.Quals);
}
/// Return a type with additional qualifiers.
QualType getQualifiedType(QualType T, Qualifiers Qs) const {
if (!Qs.hasNonFastQualifiers())
return T.withFastQualifiers(Qs.getFastQualifiers());
QualifierCollector Qc(Qs);
const Type *Ptr = Qc.strip(T);
return getExtQualType(Ptr, Qc);
}
/// Return a type with additional qualifiers.
QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
if (!Qs.hasNonFastQualifiers())
return QualType(T, Qs.getFastQualifiers());
return getExtQualType(T, Qs);
}
/// Return a type with the given lifetime qualifier.
///
/// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
QualType getLifetimeQualifiedType(QualType type,
Qualifiers::ObjCLifetime lifetime) {
assert(type.getObjCLifetime() == Qualifiers::OCL_None);
assert(lifetime != Qualifiers::OCL_None);
Qualifiers qs;
qs.addObjCLifetime(lifetime);
return getQualifiedType(type, qs);
}
/// getUnqualifiedObjCPointerType - Returns version of
/// Objective-C pointer type with lifetime qualifier removed.
QualType getUnqualifiedObjCPointerType(QualType type) const {
if (!type.getTypePtr()->isObjCObjectPointerType() ||
!type.getQualifiers().hasObjCLifetime())
return type;
Qualifiers Qs = type.getQualifiers();
Qs.removeObjCLifetime();
return getQualifiedType(type.getUnqualifiedType(), Qs);
}
unsigned char getFixedPointScale(QualType Ty) const;
unsigned char getFixedPointIBits(QualType Ty) const;
FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
APFixedPoint getFixedPointMax(QualType Ty) const;
APFixedPoint getFixedPointMin(QualType Ty) const;
DeclarationNameInfo getNameForTemplate(TemplateName Name,
SourceLocation NameLoc) const;
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
UnresolvedSetIterator End) const;
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
bool TemplateKeyword,
TemplateDecl *Template) const;
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
const IdentifierInfo *Name) const;
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
OverloadedOperatorKind Operator) const;
TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
TemplateName replacement) const;
TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
const TemplateArgument &ArgPack) const;
enum GetBuiltinTypeError {
/// No error
GE_None,
/// Missing a type from <stdio.h>
GE_Missing_stdio,
/// Missing a type from <setjmp.h>
GE_Missing_setjmp,
/// Missing a type from <ucontext.h>
GE_Missing_ucontext
};
/// Return the type for the specified builtin.
///
/// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
/// arguments to the builtin that are required to be integer constant
/// expressions.
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
unsigned *IntegerConstantArgs = nullptr) const;
/// Types and expressions required to build C++2a three-way comparisons
/// using operator<=>, including the values return by builtin <=> operators.
ComparisonCategories CompCategories;
private:
CanQualType getFromTargetType(unsigned Type) const;
TypeInfo getTypeInfoImpl(const Type *T) const;
//===--------------------------------------------------------------------===//
// Type Predicates.
//===--------------------------------------------------------------------===//
public:
/// Return one of the GCNone, Weak or Strong Objective-C garbage
/// collection attributes.
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
/// Return true if the given vector types are of the same unqualified
/// type or if they are equivalent to the same GCC vector type.
///
/// \note This ignores whether they are target-specific (AltiVec or Neon)
/// types.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
/// Return true if this is an \c NSObject object with its \c NSObject
/// attribute set.
static bool isObjCNSObjectType(QualType Ty) {
return Ty->isObjCNSObjectType();
}
//===--------------------------------------------------------------------===//
// Type Sizing and Analysis
//===--------------------------------------------------------------------===//
/// Return the APFloat 'semantics' for the specified scalar floating
/// point type.
const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
/// Get the size and alignment of the specified complete type in bits.
TypeInfo getTypeInfo(const Type *T) const;
TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
/// Get default simd alignment of the specified complete type in bits.
unsigned getOpenMPDefaultSimdAlign(QualType T) const;
/// Return the size of the specified (complete) type \p T, in bits.
uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
/// Return the size of the character type, in bits.
uint64_t getCharWidth() const {
return getTypeSize(CharTy);
}
/// Convert a size in bits to a size in characters.
CharUnits toCharUnitsFromBits(int64_t BitSize) const;
/// Convert a size in characters to a size in bits.
int64_t toBits(CharUnits CharSize) const;
/// Return the size of the specified (complete) type \p T, in
/// characters.
CharUnits getTypeSizeInChars(QualType T) const;
CharUnits getTypeSizeInChars(const Type *T) const;
/// Return the ABI-specified alignment of a (complete) type \p T, in
/// bits.
unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
/// Return the ABI-specified natural alignment of a (complete) type \p T,
/// before alignment adjustments, in bits.
///
/// This alignment is curently used only by ARM and AArch64 when passing
/// arguments of a composite type.
unsigned getTypeUnadjustedAlign(QualType T) const {
return getTypeUnadjustedAlign(T.getTypePtr());
}
unsigned getTypeUnadjustedAlign(const Type *T) const;
/// Return the ABI-specified alignment of a type, in bits, or 0 if
/// the type is incomplete and we cannot determine the alignment (for
/// example, from alignment attributes).
unsigned getTypeAlignIfKnown(QualType T) const;
/// Return the ABI-specified alignment of a (complete) type \p T, in
/// characters.
CharUnits getTypeAlignInChars(QualType T) const;
CharUnits getTypeAlignInChars(const Type *T) const;
/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
/// in characters, before alignment adjustments. This method does not work on
/// incomplete types.
CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
// getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
// type is a record, its data size is returned.
std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
/// Determine if the alignment the type has was required using an
/// alignment attribute.
bool isAlignmentRequired(const Type *T) const;
bool isAlignmentRequired(QualType T) const;
/// Return the "preferred" alignment of the specified type \p T for
/// the current target, in bits.
///
/// This can be different than the ABI alignment in cases where it is
/// beneficial for performance to overalign a data type.
unsigned getPreferredTypeAlign(const Type *T) const;
/// Return the default alignment for __attribute__((aligned)) on
/// this target, to be used if no alignment value is specified.
unsigned getTargetDefaultAlignForAttributeAligned() const;
/// Return the alignment in bits that should be given to a
/// global variable with type \p T.
unsigned getAlignOfGlobalVar(QualType T) const;
/// Return the alignment in characters that should be given to a
/// global variable with type \p T.
CharUnits getAlignOfGlobalVarInChars(QualType T) const;
/// Return a conservative estimate of the alignment of the specified
/// decl \p D.
///
/// \pre \p D must not be a bitfield type, as bitfields do not have a valid
/// alignment.
///
/// If \p ForAlignof, references are treated like their underlying type
/// and large arrays don't get any special treatment. If not \p ForAlignof
/// it computes the value expected by CodeGen: references are treated like
/// pointers and large arrays get extra alignment.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
/// Get or compute information about the layout of the specified
/// record (struct/union/class) \p D, which indicates its size and field
/// position information.
const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
/// Get or compute information about the layout of the specified
/// Objective-C interface.
const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
const;
void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
bool Simple = false) const;
/// Get or compute information about the layout of the specified
/// Objective-C implementation.
///
/// This may differ from the interface if synthesized ivars are present.
const ASTRecordLayout &
getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
/// Get our current best idea for the key function of the
/// given record decl, or nullptr if there isn't one.
///
/// The key function is, according to the Itanium C++ ABI section 5.2.3:
/// ...the first non-pure virtual function that is not inline at the
/// point of class definition.
///
/// Other ABIs use the same idea. However, the ARM C++ ABI ignores
/// virtual functions that are defined 'inline', which means that
/// the result of this computation can change.
const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
/// Observe that the given method cannot be a key function.
/// Checks the key-function cache for the method's class and clears it
/// if matches the given declaration.
///
/// This is used in ABIs where out-of-line definitions marked
/// inline are not considered to be key functions.
///
/// \param method should be the declaration from the class definition
void setNonKeyFunction(const CXXMethodDecl *method);
/// Loading virtual member pointers using the virtual inheritance model
/// always results in an adjustment using the vbtable even if the index is
/// zero.
///
/// This is usually OK because the first slot in the vbtable points
/// backwards to the top of the MDC. However, the MDC might be reusing a
/// vbptr from an nv-base. In this case, the first slot in the vbtable
/// points to the start of the nv-base which introduced the vbptr and *not*
/// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
/// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
uint64_t getFieldOffset(const ValueDecl *FD) const;
/// Get the offset of an ObjCIvarDecl in bits.
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
const ObjCImplementationDecl *ID,
const ObjCIvarDecl *Ivar) const;
bool isNearlyEmpty(const CXXRecordDecl *RD) const;
VTableContextBase *getVTableContext();
MangleContext *createMangleContext();
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
void CollectInheritedProtocols(const Decl *CDecl,
llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
/// Return true if the specified type has unique object representations
/// according to (C++17 [meta.unary.prop]p9)
bool hasUniqueObjectRepresentations(QualType Ty) const;
//===--------------------------------------------------------------------===//
// Type Operators
//===--------------------------------------------------------------------===//
/// Return the canonical (structural) type corresponding to the
/// specified potentially non-canonical type \p T.
///
/// The non-canonical version of a type may have many "decorated" versions of
/// types. Decorators can include typedefs, 'typeof' operators, etc. The
/// returned type is guaranteed to be free of any of these, allowing two
/// canonical types to be compared for exact equality with a simple pointer
/// comparison.
CanQualType getCanonicalType(QualType T) const {
return CanQualType::CreateUnsafe(T.getCanonicalType());
}
const Type *getCanonicalType(const Type *T) const {
return T->getCanonicalTypeInternal().getTypePtr();
}
/// Return the canonical parameter type corresponding to the specific
/// potentially non-canonical one.
///
/// Qualifiers are stripped off, functions are turned into function
/// pointers, and arrays decay one level into pointers.
CanQualType getCanonicalParamType(QualType T) const;
/// Determine whether the given types \p T1 and \p T2 are equivalent.
bool hasSameType(QualType T1, QualType T2) const {
return getCanonicalType(T1) == getCanonicalType(T2);
}
bool hasSameType(const Type *T1, const Type *T2) const {
return getCanonicalType(T1) == getCanonicalType(T2);
}
/// Return this type as a completely-unqualified array type,
/// capturing the qualifiers in \p Quals.
///
/// This will remove the minimal amount of sugaring from the types, similar
/// to the behavior of QualType::getUnqualifiedType().
///
/// \param T is the qualified type, which may be an ArrayType
///
/// \param Quals will receive the full set of qualifiers that were
/// applied to the array.
///
/// \returns if this is an array type, the completely unqualified array type
/// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
/// Determine whether the given types are equivalent after
/// cvr-qualifiers have been removed.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
return getCanonicalType(T1).getTypePtr() ==
getCanonicalType(T2).getTypePtr();
}
bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
bool IsParam) const {
auto SubTnullability = SubT->getNullability(*this);
auto SuperTnullability = SuperT->getNullability(*this);
if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
// Neither has nullability; return true
if (!SubTnullability)
return true;
// Both have nullability qualifier.
if (*SubTnullability == *SuperTnullability ||
*SubTnullability == NullabilityKind::Unspecified ||
*SuperTnullability == NullabilityKind::Unspecified)
return true;
if (IsParam) {
// Ok for the superclass method parameter to be "nonnull" and the subclass
// method parameter to be "nullable"
return (*SuperTnullability == NullabilityKind::NonNull &&
*SubTnullability == NullabilityKind::Nullable);
}
else {
// For the return type, it's okay for the superclass method to specify
// "nullable" and the subclass method specify "nonnull"
return (*SuperTnullability == NullabilityKind::Nullable &&
*SubTnullability == NullabilityKind::NonNull);
}
}
return true;
}
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
const ObjCMethodDecl *MethodImp);
bool UnwrapSimilarTypes(QualType &T1, QualType &T2);
bool UnwrapSimilarArrayTypes(QualType &T1, QualType &T2);
/// Determine if two types are similar, according to the C++ rules. That is,
/// determine if they are the same other than qualifiers on the initial
/// sequence of pointer / pointer-to-member / array (and in Clang, object
/// pointer) types and their element types.
///
/// Clang offers a number of qualifiers in addition to the C++ qualifiers;
/// those qualifiers are also ignored in the 'similarity' check.
bool hasSimilarType(QualType T1, QualType T2);
/// Determine if two types are similar, ignoring only CVR qualifiers.
bool hasCvrSimilarType(QualType T1, QualType T2);
/// Retrieves the "canonical" nested name specifier for a
/// given nested name specifier.
///
/// The canonical nested name specifier is a nested name specifier
/// that uniquely identifies a type or namespace within the type
/// system. For example, given:
///
/// \code
/// namespace N {
/// struct S {
/// template<typename T> struct X { typename T* type; };
/// };
/// }
///
/// template<typename T> struct Y {
/// typename N::S::X<T>::type member;
/// };
/// \endcode
///
/// Here, the nested-name-specifier for N::S::X<T>:: will be
/// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
/// by declarations in the type system and the canonical type for
/// the template type parameter 'T' is template-param-0-0.
NestedNameSpecifier *
getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
/// Retrieves the default calling convention for the current target.
CallingConv getDefaultCallingConvention(bool IsVariadic,
bool IsCXXMethod) const;
/// Retrieves the "canonical" template name that refers to a
/// given template.
///
/// The canonical template name is the simplest expression that can
/// be used to refer to a given template. For most templates, this
/// expression is just the template declaration itself. For example,
/// the template std::vector can be referred to via a variety of
/// names---std::vector, \::std::vector, vector (if vector is in
/// scope), etc.---but all of these names map down to the same
/// TemplateDecl, which is used to form the canonical template name.
///
/// Dependent template names are more interesting. Here, the
/// template name could be something like T::template apply or
/// std::allocator<T>::template rebind, where the nested name
/// specifier itself is dependent. In this case, the canonical
/// template name uses the shortest form of the dependent
/// nested-name-specifier, which itself contains all canonical
/// types, values, and templates.
TemplateName getCanonicalTemplateName(TemplateName Name) const;
/// Determine whether the given template names refer to the same
/// template.
bool hasSameTemplateName(TemplateName X, TemplateName Y);
/// Retrieve the "canonical" template argument.
///
/// The canonical template argument is the simplest template argument
/// (which may be a type, value, expression, or declaration) that
/// expresses the value of the argument.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
const;
/// Type Query functions. If the type is an instance of the specified class,
/// return the Type pointer for the underlying maximally pretty type. This
/// is a member of ASTContext because this may need to do some amount of
/// canonicalization, e.g. to move type qualifiers into the element type.
const ArrayType *getAsArrayType(QualType T) const;
const ConstantArrayType *getAsConstantArrayType(QualType T) const {
return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
}
const VariableArrayType *getAsVariableArrayType(QualType T) const {
return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
}
const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
}
const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
const {
return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
}
/// Return the innermost element type of an array type.
///
/// For example, will return "int" for int[m][n]
QualType getBaseElementType(const ArrayType *VAT) const;
/// Return the innermost element type of a type (which needn't
/// actually be an array type).
QualType getBaseElementType(QualType QT) const;
/// Return number of constant array elements.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
/// Perform adjustment on the parameter type of a function.
///
/// This routine adjusts the given parameter type @p T to the actual
/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
/// C++ [dcl.fct]p3). The adjusted parameter type is returned.
QualType getAdjustedParameterType(QualType T) const;
/// Retrieve the parameter type as adjusted for use in the signature
/// of a function, decaying array and function types and removing top-level
/// cv-qualifiers.
QualType getSignatureParameterType(QualType T) const;
QualType getExceptionObjectType(QualType T) const;
/// Return the properly qualified result of decaying the specified
/// array type to a pointer.
///
/// This operation is non-trivial when handling typedefs etc. The canonical
/// type of \p T must be an array type, this returns a pointer to a properly
/// qualified element of the array.
///
/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
QualType getArrayDecayedType(QualType T) const;
/// Return the type that \p PromotableType will promote to: C99
/// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
QualType getPromotedIntegerType(QualType PromotableType) const;
/// Recurses in pointer/array types until it finds an Objective-C
/// retainable type and returns its ownership.
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
/// Whether this is a promotable bitfield reference according
/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
///
/// \returns the type this bit-field will promote to, or NULL if no
/// promotion occurs.
QualType isPromotableBitField(Expr *E) const;
/// Return the highest ranked integer type, see C99 6.3.1.8p1.
///
/// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
/// \p LHS < \p RHS, return -1.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
/// Compare the rank of the two specified floating point types,
/// ignoring the domain of the type (i.e. 'double' == '_Complex double').
///
/// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
/// \p LHS < \p RHS, return -1.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
/// Return a real floating point or a complex type (based on
/// \p typeDomain/\p typeSize).
///
/// \param typeDomain a real floating point or complex type.
/// \param typeSize a real floating point or complex type.
QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
QualType typeDomain) const;
unsigned getTargetAddressSpace(QualType T) const {
return getTargetAddressSpace(T.getQualifiers());
}
unsigned getTargetAddressSpace(Qualifiers Q) const {
return getTargetAddressSpace(Q.getAddressSpace());
}
unsigned getTargetAddressSpace(LangAS AS) const;
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;
/// Get target-dependent integer value for null pointer which is used for
/// constant folding.
uint64_t getTargetNullPointerValue(QualType QT) const;
bool addressSpaceMapManglingFor(LangAS AS) const {
return AddrSpaceMapMangling || isTargetAddressSpace(AS);
}
private:
// Helper for integer ordering
unsigned getIntegerRank(const Type *T) const;
public:
//===--------------------------------------------------------------------===//
// Type Compatibility Predicates
//===--------------------------------------------------------------------===//
/// Compatibility predicates used to check assignment expressions.
bool typesAreCompatible(QualType T1, QualType T2,
bool CompareUnqualified = false); // C99 6.2.7p1
bool propertyTypesAreCompatible(QualType, QualType);
bool typesAreBlockPointerCompatible(QualType, QualType);
bool isObjCIdType(QualType T) const {
return T == getObjCIdType();
}
bool isObjCClassType(QualType T) const {
return T == getObjCClassType();
}
bool isObjCSelType(QualType T) const {
return T == getObjCSelType();
}
bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
bool ForCompare);
bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
// Check the safety of assignment from LHS to RHS
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
const ObjCObjectPointerType *RHSOPT);
bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
const ObjCObjectType *RHS);
bool canAssignObjCInterfacesInBlockPointer(
const ObjCObjectPointerType *LHSOPT,
const ObjCObjectPointerType *RHSOPT,
bool BlockReturnType);
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
const ObjCObjectPointerType *RHSOPT);
bool canBindObjCObjectType(QualType To, QualType From);
// Functions for calculating composite types
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
bool Unqualified = false, bool BlockReturnType = false);
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
bool Unqualified = false);
QualType mergeFunctionParameterTypes(QualType, QualType,
bool OfBlockPointer = false,
bool Unqualified = false);
QualType mergeTransparentUnionType(QualType, QualType,
bool OfBlockPointer=false,
bool Unqualified = false);
QualType mergeObjCGCQualifiers(QualType, QualType);
/// This function merges the ExtParameterInfo lists of two functions. It
/// returns true if the lists are compatible. The merged list is returned in
/// NewParamInfos.
///
/// \param FirstFnType The type of the first function.
///
/// \param SecondFnType The type of the second function.
///
/// \param CanUseFirst This flag is set to true if the first function's
/// ExtParameterInfo list can be used as the composite list of
/// ExtParameterInfo.
///
/// \param CanUseSecond This flag is set to true if the second function's
/// ExtParameterInfo list can be used as the composite list of
/// ExtParameterInfo.
///
/// \param NewParamInfos The composite list of ExtParameterInfo. The list is
/// empty if none of the flags are set.
///
bool mergeExtParameterInfo(
const FunctionProtoType *FirstFnType,
const FunctionProtoType *SecondFnType,
bool &CanUseFirst, bool &CanUseSecond,
SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
void ResetObjCLayout(const ObjCContainerDecl *CD);
//===--------------------------------------------------------------------===//
// Integer Predicates
//===--------------------------------------------------------------------===//
// The width of an integer, as defined in C99 6.2.6.2. This is the number
// of bits in an integer type excluding any padding bits.
unsigned getIntWidth(QualType T) const;
// Per C99 6.2.5p6, for every signed integer type, there is a corresponding
// unsigned integer type. This method takes a signed type, and returns the
// corresponding unsigned integer type.
// With the introduction of fixed point types in ISO N1169, this method also
// accepts fixed point types and returns the corresponding unsigned type for
// a given fixed point type.
QualType getCorrespondingUnsignedType(QualType T) const;
// Per ISO N1169, this method accepts fixed point types and returns the
// corresponding saturated type for a given fixed point type.
QualType getCorrespondingSaturatedType(QualType Ty) const;
//===--------------------------------------------------------------------===//
// Integer Values
//===--------------------------------------------------------------------===//
/// Make an APSInt of the appropriate width and signedness for the
/// given \p Value and integer \p Type.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
// If Type is a signed integer type larger than 64 bits, we need to be sure
// to sign extend Res appropriately.
llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
Res = Value;
unsigned Width = getIntWidth(Type);
if (Width != Res.getBitWidth())
return Res.extOrTrunc(Width);
return Res;
}
bool isSentinelNullExpr(const Expr *E);
/// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
/// none exists.
ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
/// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
/// none exists.
ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
/// Return true if there is at least one \@implementation in the TU.
bool AnyObjCImplementation() {
return !ObjCImpls.empty();
}
/// Set the implementation of ObjCInterfaceDecl.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
ObjCImplementationDecl *ImplD);
/// Set the implementation of ObjCCategoryDecl.
void setObjCImplementation(ObjCCategoryDecl *CatD,
ObjCCategoryImplDecl *ImplD);
/// Get the duplicate declaration of a ObjCMethod in the same
/// interface, or null if none exists.
const ObjCMethodDecl *
getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
const ObjCMethodDecl *Redecl);
/// Returns the Objective-C interface that \p ND belongs to if it is
/// an Objective-C method/property/ivar etc. that is part of an interface,
/// otherwise returns null.
const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
/// Set the copy inialization expression of a block var decl. \p CanThrow
/// indicates whether the copy expression can throw or not.
void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow);
/// Get the copy initialization expression of the VarDecl \p VD, or
/// nullptr if none exists.
BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const;
/// Allocate an uninitialized TypeSourceInfo.
///
/// The caller should initialize the memory held by TypeSourceInfo using
/// the TypeLoc wrappers.
///
/// \param T the type that will be the basis for type source info. This type
/// should refer to how the declarator was written in source code, not to
/// what type semantic analysis resolved the declarator to.
///
/// \param Size the size of the type info to create, or 0 if the size
/// should be calculated based on the type.
TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
/// Allocate a TypeSourceInfo where all locations have been
/// initialized to a given location, which defaults to the empty
/// location.
TypeSourceInfo *
getTrivialTypeSourceInfo(QualType T,
SourceLocation Loc = SourceLocation()) const;
/// Add a deallocation callback that will be invoked when the
/// ASTContext is destroyed.
///
/// \param Callback A callback function that will be invoked on destruction.
///
/// \param Data Pointer data that will be provided to the callback function
/// when it is called.
void AddDeallocation(void (*Callback)(void*), void *Data);
/// If T isn't trivially destructible, calls AddDeallocation to register it
/// for destruction.
template <typename T>
void addDestruction(T *Ptr) {
if (!std::is_trivially_destructible<T>::value) {
auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
AddDeallocation(DestroyPtr, Ptr);
}
}
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
/// Determines if the decl can be CodeGen'ed or deserialized from PCH
/// lazily, only when used; this is only relevant for function or file scoped
/// var definitions.
///
/// \returns true if the function/var must be CodeGen'ed/deserialized even if
/// it is not used.
bool DeclMustBeEmitted(const Decl *D);
/// Visits all versions of a multiversioned function with the passed
/// predicate.
void forEachMultiversionedFunctionVersion(
const FunctionDecl *FD,
llvm::function_ref<void(FunctionDecl *)> Pred) const;
const CXXConstructorDecl *
getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
CXXConstructorDecl *CD);
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
void setManglingNumber(const NamedDecl *ND, unsigned Number);
unsigned getManglingNumber(const NamedDecl *ND) const;
void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
unsigned getStaticLocalNumber(const VarDecl *VD) const;
/// Retrieve the context for computing mangling numbers in the given
/// DeclContext.
MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
/// Used by ParmVarDecl to store on the side the
/// index of the parameter when it exceeds the size of the normal bitfield.
void setParameterIndex(const ParmVarDecl *D, unsigned index);
/// Used by ParmVarDecl to retrieve on the side the
/// index of the parameter when it exceeds the size of the normal bitfield.
unsigned getParameterIndex(const ParmVarDecl *D) const;
/// Get the storage for the constant value of a materialized temporary
/// of static storage duration.
APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
bool MayCreate);
//===--------------------------------------------------------------------===//
// Statistics
//===--------------------------------------------------------------------===//
/// The number of implicitly-declared default constructors.
static unsigned NumImplicitDefaultConstructors;
/// The number of implicitly-declared default constructors for
/// which declarations were built.
static unsigned NumImplicitDefaultConstructorsDeclared;
/// The number of implicitly-declared copy constructors.
static unsigned NumImplicitCopyConstructors;
/// The number of implicitly-declared copy constructors for
/// which declarations were built.
static unsigned NumImplicitCopyConstructorsDeclared;
/// The number of implicitly-declared move constructors.
static unsigned NumImplicitMoveConstructors;
/// The number of implicitly-declared move constructors for
/// which declarations were built.
static unsigned NumImplicitMoveConstructorsDeclared;
/// The number of implicitly-declared copy assignment operators.
static unsigned NumImplicitCopyAssignmentOperators;
/// The number of implicitly-declared copy assignment operators for
/// which declarations were built.
static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
/// The number of implicitly-declared move assignment operators.
static unsigned NumImplicitMoveAssignmentOperators;
/// The number of implicitly-declared move assignment operators for
/// which declarations were built.
static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
/// The number of implicitly-declared destructors.
static unsigned NumImplicitDestructors;
/// The number of implicitly-declared destructors for which
/// declarations were built.
static unsigned NumImplicitDestructorsDeclared;
public:
/// Initialize built-in types.
///
/// This routine may only be invoked once for a given ASTContext object.
/// It is normally invoked after ASTContext construction.
///
/// \param Target The target
void InitBuiltinTypes(const TargetInfo &Target,
const TargetInfo *AuxTarget = nullptr);
private:
void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
// Return the Objective-C type encoding for a given type.
void getObjCEncodingForTypeImpl(QualType t, std::string &S,
bool ExpandPointedToStructures,
bool ExpandStructures,
const FieldDecl *Field,
bool OutermostType = false,
bool EncodingProperty = false,
bool StructField = false,
bool EncodeBlockParameters = false,
bool EncodeClassNames = false,
bool EncodePointerToObjCTypedef = false,
QualType *NotEncodedT=nullptr) const;
// Adds the encoding of the structure's members.
void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
const FieldDecl *Field,
bool includeVBases = true,
QualType *NotEncodedT=nullptr) const;
public:
// Adds the encoding of a method parameter or return type.
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
QualType T, std::string& S,
bool Extended) const;
/// Returns true if this is an inline-initialized static data member
/// which is treated as a definition for MSVC compatibility.
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
enum class InlineVariableDefinitionKind {
/// Not an inline variable.
None,
/// Weak definition of inline variable.
Weak,
/// Weak for now, might become strong later in this TU.
WeakUnknown,
/// Strong definition.
Strong
};
/// Determine whether a definition of this inline variable should
/// be treated as a weak or strong definition. For compatibility with
/// C++14 and before, for a constexpr static data member, if there is an
/// out-of-line declaration of the member, we may promote it from weak to
/// strong.
InlineVariableDefinitionKind
getInlineVariableDefinitionKind(const VarDecl *VD) const;
private:
friend class DeclarationNameTable;
friend class DeclContext;
const ASTRecordLayout &
getObjCLayout(const ObjCInterfaceDecl *D,
const ObjCImplementationDecl *Impl) const;
/// A set of deallocations that should be performed when the
/// ASTContext is destroyed.
// FIXME: We really should have a better mechanism in the ASTContext to
// manage running destructors for types which do variable sized allocation
// within the AST. In some places we thread the AST bump pointer allocator
// into the datastructures which avoids this mess during deallocation but is
// wasteful of memory, and here we require a lot of error prone book keeping
// in order to track and run destructors while we're tearing things down.
using DeallocationFunctionsAndArguments =
llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
DeallocationFunctionsAndArguments Deallocations;
// FIXME: This currently contains the set of StoredDeclMaps used
// by DeclContext objects. This probably should not be in ASTContext,
// but we include it here so that ASTContext can quickly deallocate them.
llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
std::unique_ptr<ParentMapPointers> PointerParents;
std::unique_ptr<ParentMapOtherNodes> OtherParents;
std::unique_ptr<VTableContextBase> VTContext;
void ReleaseDeclContextMaps();
void ReleaseParentMapEntries();
public:
enum PragmaSectionFlag : unsigned {
PSF_None = 0,
PSF_Read = 0x1,
PSF_Write = 0x2,
PSF_Execute = 0x4,
PSF_Implicit = 0x8,
PSF_Invalid = 0x80000000U,
};
struct SectionInfo {
DeclaratorDecl *Decl;
SourceLocation PragmaSectionLocation;
int SectionFlags;
SectionInfo() = default;
SectionInfo(DeclaratorDecl *Decl,
SourceLocation PragmaSectionLocation,
int SectionFlags)
: Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
SectionFlags(SectionFlags) {}
};
llvm::StringMap<SectionInfo> SectionInfos;
};
/// Utility function for constructing a nullary selector.
inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
IdentifierInfo* II = &Ctx.Idents.get(name);
return Ctx.Selectors.getSelector(0, &II);
}
/// Utility function for constructing an unary selector.
inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
IdentifierInfo* II = &Ctx.Idents.get(name);
return Ctx.Selectors.getSelector(1, &II);
}
} // namespace clang
// operator new and delete aren't allowed inside namespaces.
/// Placement new for using the ASTContext's allocator.
///
/// This placement form of operator new uses the ASTContext's allocator for
/// obtaining memory.
///
/// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
/// here need to also be made there.
///
/// We intentionally avoid using a nothrow specification here so that the calls
/// to this operator will not perform a null check on the result -- the
/// underlying allocator never returns null pointers.
///
/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
/// @code
/// // Default alignment (8)
/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
/// // Specific alignment
/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
/// @endcode
/// Memory allocated through this placement new operator does not need to be
/// explicitly freed, as ASTContext will free all of this memory when it gets
/// destroyed. Please note that you cannot use delete on the pointer.
///
/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
/// @param C The ASTContext that provides the allocator.
/// @param Alignment The alignment of the allocated memory (if the underlying
/// allocator supports it).
/// @return The allocated memory. Could be nullptr.
inline void *operator new(size_t Bytes, const clang::ASTContext &C,
size_t Alignment) {
return C.Allocate(Bytes, Alignment);
}
/// Placement delete companion to the new above.
///
/// This operator is just a companion to the new above. There is no way of
/// invoking it directly; see the new operator for more details. This operator
/// is called implicitly by the compiler if a placement new expression using
/// the ASTContext throws in the object constructor.
inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
C.Deallocate(Ptr);
}
/// This placement form of operator new[] uses the ASTContext's allocator for
/// obtaining memory.
///
/// We intentionally avoid using a nothrow specification here so that the calls
/// to this operator will not perform a null check on the result -- the
/// underlying allocator never returns null pointers.
///
/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
/// @code
/// // Default alignment (8)
/// char *data = new (Context) char[10];
/// // Specific alignment
/// char *data = new (Context, 4) char[10];
/// @endcode
/// Memory allocated through this placement new[] operator does not need to be
/// explicitly freed, as ASTContext will free all of this memory when it gets
/// destroyed. Please note that you cannot use delete on the pointer.
///
/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
/// @param C The ASTContext that provides the allocator.
/// @param Alignment The alignment of the allocated memory (if the underlying
/// allocator supports it).
/// @return The allocated memory. Could be nullptr.
inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
size_t Alignment = 8) {
return C.Allocate(Bytes, Alignment);
}
/// Placement delete[] companion to the new[] above.
///
/// This operator is just a companion to the new[] above. There is no way of
/// invoking it directly; see the new[] operator for more details. This operator
/// is called implicitly by the compiler if a placement new[] expression using
/// the ASTContext throws in the object constructor.
inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
C.Deallocate(Ptr);
}
/// Create the representation of a LazyGenerationalUpdatePtr.
template <typename Owner, typename T,
void (clang::ExternalASTSource::*Update)(Owner)>
typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
const clang::ASTContext &Ctx, T Value) {
// Note, this is implemented here so that ExternalASTSource.h doesn't need to
// include ASTContext.h. We explicitly instantiate it for all relevant types
// in ASTContext.cpp.
if (auto *Source = Ctx.getExternalSource())
return new (Ctx) LazyData(Source, Value);
return Value;
}
#endif // LLVM_CLANG_AST_ASTCONTEXT_H
diff --git a/clang/include/clang/AST/Attr.h b/clang/include/clang/AST/Attr.h
index 3ca24cd434d..183ca2c4d69 100644
--- a/clang/include/clang/AST/Attr.h
+++ b/clang/include/clang/AST/Attr.h
@@ -1,351 +1,338 @@
//===--- Attr.h - Classes for representing attributes ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the Attr interface and subclasses.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_ATTR_H
#define LLVM_CLANG_AST_ATTR_H
#include "clang/AST/AttrIterator.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"
#include "clang/Basic/AttrKinds.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/Sanitizers.h"
#include "clang/Basic/SourceLocation.h"
#include "llvm/ADT/PointerEmbeddedInt.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/VersionTuple.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
namespace clang {
class ASTContext;
class IdentifierInfo;
class ObjCInterfaceDecl;
class Expr;
class QualType;
class FunctionDecl;
class TypeSourceInfo;
/// Attr - This represents one attribute.
class Attr {
private:
SourceRange Range;
unsigned AttrKind : 16;
protected:
/// An index into the spelling list of an
/// attribute defined in Attr.td file.
unsigned SpellingListIndex : 4;
unsigned Inherited : 1;
unsigned IsPackExpansion : 1;
unsigned Implicit : 1;
// FIXME: These are properties of the attribute kind, not state for this
// instance of the attribute.
unsigned IsLateParsed : 1;
unsigned InheritEvenIfAlreadyPresent : 1;
void *operator new(size_t bytes) noexcept {
llvm_unreachable("Attrs cannot be allocated with regular 'new'.");
}
void operator delete(void *data) noexcept {
llvm_unreachable("Attrs cannot be released with regular 'delete'.");
}
public:
// Forward so that the regular new and delete do not hide global ones.
void *operator new(size_t Bytes, ASTContext &C,
size_t Alignment = 8) noexcept {
return ::operator new(Bytes, C, Alignment);
}
void operator delete(void *Ptr, ASTContext &C, size_t Alignment) noexcept {
return ::operator delete(Ptr, C, Alignment);
}
protected:
Attr(attr::Kind AK, SourceRange R, unsigned SpellingListIndex,
bool IsLateParsed)
: Range(R), AttrKind(AK), SpellingListIndex(SpellingListIndex),
Inherited(false), IsPackExpansion(false), Implicit(false),
IsLateParsed(IsLateParsed), InheritEvenIfAlreadyPresent(false) {}
public:
attr::Kind getKind() const {
return static_cast<attr::Kind>(AttrKind);
}
unsigned getSpellingListIndex() const { return SpellingListIndex; }
const char *getSpelling() const;
SourceLocation getLocation() const { return Range.getBegin(); }
SourceRange getRange() const { return Range; }
void setRange(SourceRange R) { Range = R; }
bool isInherited() const { return Inherited; }
/// Returns true if the attribute has been implicitly created instead
/// of explicitly written by the user.
bool isImplicit() const { return Implicit; }
void setImplicit(bool I) { Implicit = I; }
void setPackExpansion(bool PE) { IsPackExpansion = PE; }
bool isPackExpansion() const { return IsPackExpansion; }
// Clone this attribute.
Attr *clone(ASTContext &C) const;
bool isLateParsed() const { return IsLateParsed; }
// Pretty print this attribute.
void printPretty(raw_ostream &OS, const PrintingPolicy &Policy) const;
};
-class TypeAttr : public Attr {
-protected:
- TypeAttr(attr::Kind AK, SourceRange R, unsigned SpellingListIndex,
- bool IsLateParsed)
- : Attr(AK, R, SpellingListIndex, IsLateParsed) {}
-
-public:
- static bool classof(const Attr *A) {
- return A->getKind() >= attr::FirstTypeAttr &&
- A->getKind() <= attr::LastTypeAttr;
- }
-};
-
class StmtAttr : public Attr {
protected:
StmtAttr(attr::Kind AK, SourceRange R, unsigned SpellingListIndex,
bool IsLateParsed)
: Attr(AK, R, SpellingListIndex, IsLateParsed) {}
public:
static bool classof(const Attr *A) {
return A->getKind() >= attr::FirstStmtAttr &&
A->getKind() <= attr::LastStmtAttr;
}
};
class InheritableAttr : public Attr {
protected:
InheritableAttr(attr::Kind AK, SourceRange R, unsigned SpellingListIndex,
bool IsLateParsed, bool InheritEvenIfAlreadyPresent)
: Attr(AK, R, SpellingListIndex, IsLateParsed) {
this->InheritEvenIfAlreadyPresent = InheritEvenIfAlreadyPresent;
}
public:
void setInherited(bool I) { Inherited = I; }
/// Should this attribute be inherited from a prior declaration even if it's
/// explicitly provided in the current declaration?
bool shouldInheritEvenIfAlreadyPresent() const {
return InheritEvenIfAlreadyPresent;
}
// Implement isa/cast/dyncast/etc.
static bool classof(const Attr *A) {
return A->getKind() >= attr::FirstInheritableAttr &&
A->getKind() <= attr::LastInheritableAttr;
}
};
class InheritableParamAttr : public InheritableAttr {
protected:
InheritableParamAttr(attr::Kind AK, SourceRange R, unsigned SpellingListIndex,
bool IsLateParsed, bool InheritEvenIfAlreadyPresent)
: InheritableAttr(AK, R, SpellingListIndex, IsLateParsed,
InheritEvenIfAlreadyPresent) {}
public:
// Implement isa/cast/dyncast/etc.
static bool classof(const Attr *A) {
return A->getKind() >= attr::FirstInheritableParamAttr &&
A->getKind() <= attr::LastInheritableParamAttr;
}
};
/// A parameter attribute which changes the argument-passing ABI rule
/// for the parameter.
class ParameterABIAttr : public InheritableParamAttr {
protected:
ParameterABIAttr(attr::Kind AK, SourceRange R,
unsigned SpellingListIndex, bool IsLateParsed,
bool InheritEvenIfAlreadyPresent)
: InheritableParamAttr(AK, R, SpellingListIndex, IsLateParsed,
InheritEvenIfAlreadyPresent) {}
public:
ParameterABI getABI() const {
switch (getKind()) {
case attr::SwiftContext:
return ParameterABI::SwiftContext;
case attr::SwiftErrorResult:
return ParameterABI::SwiftErrorResult;
case attr::SwiftIndirectResult:
return ParameterABI::SwiftIndirectResult;
default:
llvm_unreachable("bad parameter ABI attribute kind");
}
}
static bool classof(const Attr *A) {
return A->getKind() >= attr::FirstParameterABIAttr &&
A->getKind() <= attr::LastParameterABIAttr;
}
};
/// A single parameter index whose accessors require each use to make explicit
/// the parameter index encoding needed.
class ParamIdx {
// Idx is exposed only via accessors that specify specific encodings.
unsigned Idx : 30;
unsigned HasThis : 1;
unsigned IsValid : 1;
void assertComparable(const ParamIdx &I) const {
assert(isValid() && I.isValid() &&
"ParamIdx must be valid to be compared");
// It's possible to compare indices from separate functions, but so far
// it's not proven useful. Moreover, it might be confusing because a
// comparison on the results of getASTIndex might be inconsistent with a
// comparison on the ParamIdx objects themselves.
assert(HasThis == I.HasThis &&
"ParamIdx must be for the same function to be compared");
}
public:
/// Construct an invalid parameter index (\c isValid returns false and
/// accessors fail an assert).
ParamIdx() : Idx(0), HasThis(false), IsValid(false) {}
/// \param Idx is the parameter index as it is normally specified in
/// attributes in the source: one-origin including any C++ implicit this
/// parameter.
///
/// \param D is the declaration containing the parameters. It is used to
/// determine if there is a C++ implicit this parameter.
ParamIdx(unsigned Idx, const Decl *D)
: Idx(Idx), HasThis(false), IsValid(true) {
assert(Idx >= 1 && "Idx must be one-origin");
if (const auto *FD = dyn_cast<FunctionDecl>(D))
HasThis = FD->isCXXInstanceMember();
}
/// A type into which \c ParamIdx can be serialized.
///
/// A static assertion that it's of the correct size follows the \c ParamIdx
/// class definition.
typedef uint32_t SerialType;
/// Produce a representation that can later be passed to \c deserialize to
/// construct an equivalent \c ParamIdx.
SerialType serialize() const {
return *reinterpret_cast<const SerialType *>(this);
}
/// Construct from a result from \c serialize.
static ParamIdx deserialize(SerialType S) {
ParamIdx P(*reinterpret_cast<ParamIdx *>(&S));
assert((!P.IsValid || P.Idx >= 1) && "valid Idx must be one-origin");
return P;
}
/// Is this parameter index valid?
bool isValid() const { return IsValid; }
/// Get the parameter index as it would normally be encoded for attributes at
/// the source level of representation: one-origin including any C++ implicit
/// this parameter.
///
/// This encoding thus makes sense for diagnostics, pretty printing, and
/// constructing new attributes from a source-like specification.
unsigned getSourceIndex() const {
assert(isValid() && "ParamIdx must be valid");
return Idx;
}
/// Get the parameter index as it would normally be encoded at the AST level
/// of representation: zero-origin not including any C++ implicit this
/// parameter.
///
/// This is the encoding primarily used in Sema. However, in diagnostics,
/// Sema uses \c getSourceIndex instead.
unsigned getASTIndex() const {
assert(isValid() && "ParamIdx must be valid");
assert(Idx >= 1 + HasThis &&
"stored index must be base-1 and not specify C++ implicit this");
return Idx - 1 - HasThis;
}
/// Get the parameter index as it would normally be encoded at the LLVM level
/// of representation: zero-origin including any C++ implicit this parameter.
///
/// This is the encoding primarily used in CodeGen.
unsigned getLLVMIndex() const {
assert(isValid() && "ParamIdx must be valid");
assert(Idx >= 1 && "stored index must be base-1");
return Idx - 1;
}
bool operator==(const ParamIdx &I) const {
assertComparable(I);
return Idx == I.Idx;
}
bool operator!=(const ParamIdx &I) const {
assertComparable(I);
return Idx != I.Idx;
}
bool operator<(const ParamIdx &I) const {
assertComparable(I);
return Idx < I.Idx;
}
bool operator>(const ParamIdx &I) const {
assertComparable(I);
return Idx > I.Idx;
}
bool operator<=(const ParamIdx &I) const {
assertComparable(I);
return Idx <= I.Idx;
}
bool operator>=(const ParamIdx &I) const {
assertComparable(I);
return Idx >= I.Idx;
}
};
static_assert(sizeof(ParamIdx) == sizeof(ParamIdx::SerialType),
"ParamIdx does not fit its serialization type");
#include "clang/AST/Attrs.inc"
inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
const Attr *At) {
DB.AddTaggedVal(reinterpret_cast<intptr_t>(At),
DiagnosticsEngine::ak_attr);
return DB;
}
inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
const Attr *At) {
PD.AddTaggedVal(reinterpret_cast<intptr_t>(At),
DiagnosticsEngine::ak_attr);
return PD;
}
} // end namespace clang
#endif
diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 9bc1a53732b..93dafc47dd0 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -1,6596 +1,6631 @@
//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// C Language Family Type Representation
///
/// This file defines the clang::Type interface and subclasses, used to
/// represent types for languages in the C family.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_TYPE_H
#define LLVM_CLANG_AST_TYPE_H
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/TemplateName.h"
#include "clang/Basic/AddressSpaces.h"
-#include "clang/Basic/AttrKinds.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/ExceptionSpecificationType.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/Linkage.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/Visibility.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/PointerLikeTypeTraits.h"
#include "llvm/Support/type_traits.h"
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string>
#include <type_traits>
#include <utility>
namespace clang {
class ExtQuals;
class QualType;
class TagDecl;
class Type;
enum {
TypeAlignmentInBits = 4,
TypeAlignment = 1 << TypeAlignmentInBits
};
} // namespace clang
namespace llvm {
template <typename T>
struct PointerLikeTypeTraits;
template<>
struct PointerLikeTypeTraits< ::clang::Type*> {
static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
static inline ::clang::Type *getFromVoidPointer(void *P) {
return static_cast< ::clang::Type*>(P);
}
enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
};
template<>
struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
return static_cast< ::clang::ExtQuals*>(P);
}
enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
};
template <>
struct isPodLike<clang::QualType> { static const bool value = true; };
} // namespace llvm
namespace clang {
class ASTContext;
template <typename> class CanQual;
class CXXRecordDecl;
class DeclContext;
class EnumDecl;
class Expr;
class ExtQualsTypeCommonBase;
class FunctionDecl;
class IdentifierInfo;
class NamedDecl;
class ObjCInterfaceDecl;
class ObjCProtocolDecl;
class ObjCTypeParamDecl;
struct PrintingPolicy;
class RecordDecl;
class Stmt;
class TagDecl;
class TemplateArgument;
class TemplateArgumentListInfo;
class TemplateArgumentLoc;
class TemplateTypeParmDecl;
class TypedefNameDecl;
class UnresolvedUsingTypenameDecl;
using CanQualType = CanQual<Type>;
// Provide forward declarations for all of the *Type classes.
#define TYPE(Class, Base) class Class##Type;
#include "clang/AST/TypeNodes.def"
/// The collection of all-type qualifiers we support.
/// Clang supports five independent qualifiers:
/// * C99: const, volatile, and restrict
/// * MS: __unaligned
/// * Embedded C (TR18037): address spaces
/// * Objective C: the GC attributes (none, weak, or strong)
class Qualifiers {
public:
enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
Const = 0x1,
Restrict = 0x2,
Volatile = 0x4,
CVRMask = Const | Volatile | Restrict
};
enum GC {
GCNone = 0,
Weak,
Strong
};
enum ObjCLifetime {
/// There is no lifetime qualification on this type.
OCL_None,
/// This object can be modified without requiring retains or
/// releases.
OCL_ExplicitNone,
/// Assigning into this object requires the old value to be
/// released and the new value to be retained. The timing of the
/// release of the old value is inexact: it may be moved to
/// immediately after the last known point where the value is
/// live.
OCL_Strong,
/// Reading or writing from this object requires a barrier call.
OCL_Weak,
/// Assigning into this object requires a lifetime extension.
OCL_Autoreleasing
};
enum {
/// The maximum supported address space number.
/// 23 bits should be enough for anyone.
MaxAddressSpace = 0x7fffffu,
/// The width of the "fast" qualifier mask.
FastWidth = 3,
/// The fast qualifier mask.
FastMask = (1 << FastWidth) - 1
};
/// Returns the common set of qualifiers while removing them from
/// the given sets.
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
// If both are only CVR-qualified, bit operations are sufficient.
if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
Qualifiers Q;
Q.Mask = L.Mask & R.Mask;
L.Mask &= ~Q.Mask;
R.Mask &= ~Q.Mask;
return Q;
}
Qualifiers Q;
unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
Q.addCVRQualifiers(CommonCRV);
L.removeCVRQualifiers(CommonCRV);
R.removeCVRQualifiers(CommonCRV);
if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
Q.setObjCGCAttr(L.getObjCGCAttr());
L.removeObjCGCAttr();
R.removeObjCGCAttr();
}
if (L.getObjCLifetime() == R.getObjCLifetime()) {
Q.setObjCLifetime(L.getObjCLifetime());
L.removeObjCLifetime();
R.removeObjCLifetime();
}
if (L.getAddressSpace() == R.getAddressSpace()) {
Q.setAddressSpace(L.getAddressSpace());
L.removeAddressSpace();
R.removeAddressSpace();
}
return Q;
}
static Qualifiers fromFastMask(unsigned Mask) {
Qualifiers Qs;
Qs.addFastQualifiers(Mask);
return Qs;
}
static Qualifiers fromCVRMask(unsigned CVR) {
Qualifiers Qs;
Qs.addCVRQualifiers(CVR);
return Qs;
}
static Qualifiers fromCVRUMask(unsigned CVRU) {
Qualifiers Qs;
Qs.addCVRUQualifiers(CVRU);
return Qs;
}
// Deserialize qualifiers from an opaque representation.
static Qualifiers fromOpaqueValue(unsigned opaque) {
Qualifiers Qs;
Qs.Mask = opaque;
return Qs;
}
// Serialize these qualifiers into an opaque representation.
unsigned getAsOpaqueValue() const {
return Mask;
}
bool hasConst() const { return Mask & Const; }
void setConst(bool flag) {
Mask = (Mask & ~Const) | (flag ? Const : 0);
}
void removeConst() { Mask &= ~Const; }
void addConst() { Mask |= Const; }
bool hasVolatile() const { return Mask & Volatile; }
void setVolatile(bool flag) {
Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
}
void removeVolatile() { Mask &= ~Volatile; }
void addVolatile() { Mask |= Volatile; }
bool hasRestrict() const { return Mask & Restrict; }
void setRestrict(bool flag) {
Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
}
void removeRestrict() { Mask &= ~Restrict; }
void addRestrict() { Mask |= Restrict; }
bool hasCVRQualifiers() const { return getCVRQualifiers(); }
unsigned getCVRQualifiers() const { return Mask & CVRMask; }
void setCVRQualifiers(unsigned mask) {
assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
Mask = (Mask & ~CVRMask) | mask;
}
void removeCVRQualifiers(unsigned mask) {
assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
Mask &= ~mask;
}
void removeCVRQualifiers() {
removeCVRQualifiers(CVRMask);
}
void addCVRQualifiers(unsigned mask) {
assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
Mask |= mask;
}
void addCVRUQualifiers(unsigned mask) {
assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
Mask |= mask;
}
bool hasUnaligned() const { return Mask & UMask; }
void setUnaligned(bool flag) {
Mask = (Mask & ~UMask) | (flag ? UMask : 0);
}
void removeUnaligned() { Mask &= ~UMask; }
void addUnaligned() { Mask |= UMask; }
bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
void setObjCGCAttr(GC type) {
Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
}
void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
void addObjCGCAttr(GC type) {
assert(type);
setObjCGCAttr(type);
}
Qualifiers withoutObjCGCAttr() const {
Qualifiers qs = *this;
qs.removeObjCGCAttr();
return qs;
}
Qualifiers withoutObjCLifetime() const {
Qualifiers qs = *this;
qs.removeObjCLifetime();
return qs;
}
bool hasObjCLifetime() const { return Mask & LifetimeMask; }
ObjCLifetime getObjCLifetime() const {
return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
}
void setObjCLifetime(ObjCLifetime type) {
Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
}
void removeObjCLifetime() { setObjCLifetime(OCL_None); }
void addObjCLifetime(ObjCLifetime type) {
assert(type);
assert(!hasObjCLifetime());
Mask |= (type << LifetimeShift);
}
/// True if the lifetime is neither None or ExplicitNone.
bool hasNonTrivialObjCLifetime() const {
ObjCLifetime lifetime = getObjCLifetime();
return (lifetime > OCL_ExplicitNone);
}
/// True if the lifetime is either strong or weak.
bool hasStrongOrWeakObjCLifetime() const {
ObjCLifetime lifetime = getObjCLifetime();
return (lifetime == OCL_Strong || lifetime == OCL_Weak);
}
bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
LangAS getAddressSpace() const {
return static_cast<LangAS>(Mask >> AddressSpaceShift);
}
bool hasTargetSpecificAddressSpace() const {
return isTargetAddressSpace(getAddressSpace());
}
/// Get the address space attribute value to be printed by diagnostics.
unsigned getAddressSpaceAttributePrintValue() const {
auto Addr = getAddressSpace();
// This function is not supposed to be used with language specific
// address spaces. If that happens, the diagnostic message should consider
// printing the QualType instead of the address space value.
assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace());
if (Addr != LangAS::Default)
return toTargetAddressSpace(Addr);
// TODO: The diagnostic messages where Addr may be 0 should be fixed
// since it cannot differentiate the situation where 0 denotes the default
// address space or user specified __attribute__((address_space(0))).
return 0;
}
void setAddressSpace(LangAS space) {
assert((unsigned)space <= MaxAddressSpace);
Mask = (Mask & ~AddressSpaceMask)
| (((uint32_t) space) << AddressSpaceShift);
}
void removeAddressSpace() { setAddressSpace(LangAS::Default); }
void addAddressSpace(LangAS space) {
assert(space != LangAS::Default);
setAddressSpace(space);
}
// Fast qualifiers are those that can be allocated directly
// on a QualType object.
bool hasFastQualifiers() const { return getFastQualifiers(); }
unsigned getFastQualifiers() const { return Mask & FastMask; }
void setFastQualifiers(unsigned mask) {
assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
Mask = (Mask & ~FastMask) | mask;
}
void removeFastQualifiers(unsigned mask) {
assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
Mask &= ~mask;
}
void removeFastQualifiers() {
removeFastQualifiers(FastMask);
}
void addFastQualifiers(unsigned mask) {
assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
Mask |= mask;
}
/// Return true if the set contains any qualifiers which require an ExtQuals
/// node to be allocated.
bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
Qualifiers getNonFastQualifiers() const {
Qualifiers Quals = *this;
Quals.setFastQualifiers(0);
return Quals;
}
/// Return true if the set contains any qualifiers.
bool hasQualifiers() const { return Mask; }
bool empty() const { return !Mask; }
/// Add the qualifiers from the given set to this set.
void addQualifiers(Qualifiers Q) {
// If the other set doesn't have any non-boolean qualifiers, just
// bit-or it in.
if (!(Q.Mask & ~CVRMask))
Mask |= Q.Mask;
else {
Mask |= (Q.Mask & CVRMask);
if (Q.hasAddressSpace())
addAddressSpace(Q.getAddressSpace());
if (Q.hasObjCGCAttr())
addObjCGCAttr(Q.getObjCGCAttr());
if (Q.hasObjCLifetime())
addObjCLifetime(Q.getObjCLifetime());
}
}
/// Remove the qualifiers from the given set from this set.
void removeQualifiers(Qualifiers Q) {
// If the other set doesn't have any non-boolean qualifiers, just
// bit-and the inverse in.
if (!(Q.Mask & ~CVRMask))
Mask &= ~Q.Mask;
else {
Mask &= ~(Q.Mask & CVRMask);
if (getObjCGCAttr() == Q.getObjCGCAttr())
removeObjCGCAttr();
if (getObjCLifetime() == Q.getObjCLifetime())
removeObjCLifetime();
if (getAddressSpace() == Q.getAddressSpace())
removeAddressSpace();
}
}
/// Add the qualifiers from the given set to this set, given that
/// they don't conflict.
void addConsistentQualifiers(Qualifiers qs) {
assert(getAddressSpace() == qs.getAddressSpace() ||
!hasAddressSpace() || !qs.hasAddressSpace());
assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
!hasObjCGCAttr() || !qs.hasObjCGCAttr());
assert(getObjCLifetime() == qs.getObjCLifetime() ||
!hasObjCLifetime() || !qs.hasObjCLifetime());
Mask |= qs.Mask;
}
/// Returns true if this address space is a superset of the other one.
/// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
/// overlapping address spaces.
/// CL1.1 or CL1.2:
/// every address space is a superset of itself.
/// CL2.0 adds:
/// __generic is a superset of any address space except for __constant.
bool isAddressSpaceSupersetOf(Qualifiers other) const {
return
// Address spaces must match exactly.
getAddressSpace() == other.getAddressSpace() ||
// Otherwise in OpenCLC v2.0 s6.5.5: every address space except
// for __constant can be used as __generic.
(getAddressSpace() == LangAS::opencl_generic &&
other.getAddressSpace() != LangAS::opencl_constant);
}
/// Determines if these qualifiers compatibly include another set.
/// Generally this answers the question of whether an object with the other
/// qualifiers can be safely used as an object with these qualifiers.
bool compatiblyIncludes(Qualifiers other) const {
return isAddressSpaceSupersetOf(other) &&
// ObjC GC qualifiers can match, be added, or be removed, but can't
// be changed.
(getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
!other.hasObjCGCAttr()) &&
// ObjC lifetime qualifiers must match exactly.
getObjCLifetime() == other.getObjCLifetime() &&
// CVR qualifiers may subset.
(((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
// U qualifier may superset.
(!other.hasUnaligned() || hasUnaligned());
}
/// Determines if these qualifiers compatibly include another set of
/// qualifiers from the narrow perspective of Objective-C ARC lifetime.
///
/// One set of Objective-C lifetime qualifiers compatibly includes the other
/// if the lifetime qualifiers match, or if both are non-__weak and the
/// including set also contains the 'const' qualifier, or both are non-__weak
/// and one is None (which can only happen in non-ARC modes).
bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
if (getObjCLifetime() == other.getObjCLifetime())
return true;
if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
return false;
if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
return true;
return hasConst();
}
/// Determine whether this set of qualifiers is a strict superset of
/// another set of qualifiers, not considering qualifier compatibility.
bool isStrictSupersetOf(Qualifiers Other) const;
bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
explicit operator bool() const { return hasQualifiers(); }
Qualifiers &operator+=(Qualifiers R) {
addQualifiers(R);
return *this;
}
// Union two qualifier sets. If an enumerated qualifier appears
// in both sets, use the one from the right.
friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
L += R;
return L;
}
Qualifiers &operator-=(Qualifiers R) {
removeQualifiers(R);
return *this;
}
/// Compute the difference between two qualifier sets.
friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
L -= R;
return L;
}
std::string getAsString() const;
std::string getAsString(const PrintingPolicy &Policy) const;
bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
void print(raw_ostream &OS, const PrintingPolicy &Policy,
bool appendSpaceIfNonEmpty = false) const;
void Profile(llvm::FoldingSetNodeID &ID) const {
ID.AddInteger(Mask);
}
private:
// bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
// |C R V|U|GCAttr|Lifetime|AddressSpace|
uint32_t Mask = 0;
static const uint32_t UMask = 0x8;
static const uint32_t UShift = 3;
static const uint32_t GCAttrMask = 0x30;
static const uint32_t GCAttrShift = 4;
static const uint32_t LifetimeMask = 0x1C0;
static const uint32_t LifetimeShift = 6;
static const uint32_t AddressSpaceMask =
~(CVRMask | UMask | GCAttrMask | LifetimeMask);
static const uint32_t AddressSpaceShift = 9;
};
/// A std::pair-like structure for storing a qualified type split
/// into its local qualifiers and its locally-unqualified type.
struct SplitQualType {
/// The locally-unqualified type.
const Type *Ty = nullptr;
/// The local qualifiers.
Qualifiers Quals;
SplitQualType() = default;
SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
SplitQualType getSingleStepDesugaredType() const; // end of this file
// Make std::tie work.
std::pair<const Type *,Qualifiers> asPair() const {
return std::pair<const Type *, Qualifiers>(Ty, Quals);
}
friend bool operator==(SplitQualType a, SplitQualType b) {
return a.Ty == b.Ty && a.Quals == b.Quals;
}
friend bool operator!=(SplitQualType a, SplitQualType b) {
return a.Ty != b.Ty || a.Quals != b.Quals;
}
};
/// The kind of type we are substituting Objective-C type arguments into.
///
/// The kind of substitution affects the replacement of type parameters when
/// no concrete type information is provided, e.g., when dealing with an
/// unspecialized type.
enum class ObjCSubstitutionContext {
/// An ordinary type.
Ordinary,
/// The result type of a method or function.
Result,
/// The parameter type of a method or function.
Parameter,
/// The type of a property.
Property,
/// The superclass of a type.
Superclass,
};
/// A (possibly-)qualified type.
///
/// For efficiency, we don't store CV-qualified types as nodes on their
/// own: instead each reference to a type stores the qualifiers. This
/// greatly reduces the number of nodes we need to allocate for types (for
/// example we only need one for 'int', 'const int', 'volatile int',
/// 'const volatile int', etc).
///
/// As an added efficiency bonus, instead of making this a pair, we
/// just store the two bits we care about in the low bits of the
/// pointer. To handle the packing/unpacking, we make QualType be a
/// simple wrapper class that acts like a smart pointer. A third bit
/// indicates whether there are extended qualifiers present, in which
/// case the pointer points to a special structure.
class QualType {
friend class QualifierCollector;
// Thankfully, these are efficiently composable.
llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
Qualifiers::FastWidth> Value;
const ExtQuals *getExtQualsUnsafe() const {
return Value.getPointer().get<const ExtQuals*>();
}
const Type *getTypePtrUnsafe() const {
return Value.getPointer().get<const Type*>();
}
const ExtQualsTypeCommonBase *getCommonPtr() const {
assert(!isNull() && "Cannot retrieve a NULL type pointer");
auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
}
public:
QualType() = default;
QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
unsigned getLocalFastQualifiers() const { return Value.getInt(); }
void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
/// Retrieves a pointer to the underlying (unqualified) type.
///
/// This function requires that the type not be NULL. If the type might be
/// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
const Type *getTypePtr() const;
const Type *getTypePtrOrNull() const;
/// Retrieves a pointer to the name of the base type.
const IdentifierInfo *getBaseTypeIdentifier() const;
/// Divides a QualType into its unqualified type and a set of local
/// qualifiers.
SplitQualType split() const;
void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
static QualType getFromOpaquePtr(const void *Ptr) {
QualType T;
T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
return T;
}
const Type &operator*() const {
return *getTypePtr();
}
const Type *operator->() const {
return getTypePtr();
}
bool isCanonical() const;
bool isCanonicalAsParam() const;
/// Return true if this QualType doesn't point to a type yet.
bool isNull() const {
return Value.getPointer().isNull();
}
/// Determine whether this particular QualType instance has the
/// "const" qualifier set, without looking through typedefs that may have
/// added "const" at a different level.
bool isLocalConstQualified() const {
return (getLocalFastQualifiers() & Qualifiers::Const);
}
/// Determine whether this type is const-qualified.
bool isConstQualified() const;
/// Determine whether this particular QualType instance has the
/// "restrict" qualifier set, without looking through typedefs that may have
/// added "restrict" at a different level.
bool isLocalRestrictQualified() const {
return (getLocalFastQualifiers() & Qualifiers::Restrict);
}
/// Determine whether this type is restrict-qualified.
bool isRestrictQualified() const;
/// Determine whether this particular QualType instance has the
/// "volatile" qualifier set, without looking through typedefs that may have
/// added "volatile" at a different level.
bool isLocalVolatileQualified() const {
return (getLocalFastQualifiers() & Qualifiers::Volatile);
}
/// Determine whether this type is volatile-qualified.
bool isVolatileQualified() const;
/// Determine whether this particular QualType instance has any
/// qualifiers, without looking through any typedefs that might add
/// qualifiers at a different level.
bool hasLocalQualifiers() const {
return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
}
/// Determine whether this type has any qualifiers.
bool hasQualifiers() const;
/// Determine whether this particular QualType instance has any
/// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
/// instance.
bool hasLocalNonFastQualifiers() const {
return Value.getPointer().is<const ExtQuals*>();
}
/// Retrieve the set of qualifiers local to this particular QualType
/// instance, not including any qualifiers acquired through typedefs or
/// other sugar.
Qualifiers getLocalQualifiers() const;
/// Retrieve the set of qualifiers applied to this type.
Qualifiers getQualifiers() const;
/// Retrieve the set of CVR (const-volatile-restrict) qualifiers
/// local to this particular QualType instance, not including any qualifiers
/// acquired through typedefs or other sugar.
unsigned getLocalCVRQualifiers() const {
return getLocalFastQualifiers();
}
/// Retrieve the set of CVR (const-volatile-restrict) qualifiers
/// applied to this type.
unsigned getCVRQualifiers() const;
bool isConstant(const ASTContext& Ctx) const {
return QualType::isConstant(*this, Ctx);
}
/// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
bool isPODType(const ASTContext &Context) const;
/// Return true if this is a POD type according to the rules of the C++98
/// standard, regardless of the current compilation's language.
bool isCXX98PODType(const ASTContext &Context) const;
/// Return true if this is a POD type according to the more relaxed rules
/// of the C++11 standard, regardless of the current compilation's language.
/// (C++0x [basic.types]p9). Note that, unlike
/// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
bool isCXX11PODType(const ASTContext &Context) const;
/// Return true if this is a trivial type per (C++0x [basic.types]p9)
bool isTrivialType(const ASTContext &Context) const;
/// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
bool isTriviallyCopyableType(const ASTContext &Context) const;
/// Returns true if it is a class and it might be dynamic.
bool mayBeDynamicClass() const;
/// Returns true if it is not a class or if the class might not be dynamic.
bool mayBeNotDynamicClass() const;
// Don't promise in the API that anything besides 'const' can be
// easily added.
/// Add the `const` type qualifier to this QualType.
void addConst() {
addFastQualifiers(Qualifiers::Const);
}
QualType withConst() const {
return withFastQualifiers(Qualifiers::Const);
}
/// Add the `volatile` type qualifier to this QualType.
void addVolatile() {
addFastQualifiers(Qualifiers::Volatile);
}
QualType withVolatile() const {
return withFastQualifiers(Qualifiers::Volatile);
}
/// Add the `restrict` qualifier to this QualType.
void addRestrict() {
addFastQualifiers(Qualifiers::Restrict);
}
QualType withRestrict() const {
return withFastQualifiers(Qualifiers::Restrict);
}
QualType withCVRQualifiers(unsigned CVR) const {
return withFastQualifiers(CVR);
}
void addFastQualifiers(unsigned TQs) {
assert(!(TQs & ~Qualifiers::FastMask)
&& "non-fast qualifier bits set in mask!");
Value.setInt(Value.getInt() | TQs);
}
void removeLocalConst();
void removeLocalVolatile();
void removeLocalRestrict();
void removeLocalCVRQualifiers(unsigned Mask);
void removeLocalFastQualifiers() { Value.setInt(0); }
void removeLocalFastQualifiers(unsigned Mask) {
assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
Value.setInt(Value.getInt() & ~Mask);
}
// Creates a type with the given qualifiers in addition to any
// qualifiers already on this type.
QualType withFastQualifiers(unsigned TQs) const {
QualType T = *this;
T.addFastQualifiers(TQs);
return T;
}
// Creates a type with exactly the given fast qualifiers, removing
// any existing fast qualifiers.
QualType withExactLocalFastQualifiers(unsigned TQs) const {
return withoutLocalFastQualifiers().withFastQualifiers(TQs);
}
// Removes fast qualifiers, but leaves any extended qualifiers in place.
QualType withoutLocalFastQualifiers() const {
QualType T = *this;
T.removeLocalFastQualifiers();
return T;
}
QualType getCanonicalType() const;
/// Return this type with all of the instance-specific qualifiers
/// removed, but without removing any qualifiers that may have been applied
/// through typedefs.
QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
/// Retrieve the unqualified variant of the given type,
/// removing as little sugar as possible.
///
/// This routine looks through various kinds of sugar to find the
/// least-desugared type that is unqualified. For example, given:
///
/// \code
/// typedef int Integer;
/// typedef const Integer CInteger;
/// typedef CInteger DifferenceType;
/// \endcode
///
/// Executing \c getUnqualifiedType() on the type \c DifferenceType will
/// desugar until we hit the type \c Integer, which has no qualifiers on it.
///
/// The resulting type might still be qualified if it's sugar for an array
/// type. To strip qualifiers even from within a sugared array type, use
/// ASTContext::getUnqualifiedArrayType.
inline QualType getUnqualifiedType() const;
/// Retrieve the unqualified variant of the given type, removing as little
/// sugar as possible.
///
/// Like getUnqualifiedType(), but also returns the set of
/// qualifiers that were built up.
///
/// The resulting type might still be qualified if it's sugar for an array
/// type. To strip qualifiers even from within a sugared array type, use
/// ASTContext::getUnqualifiedArrayType.
inline SplitQualType getSplitUnqualifiedType() const;
/// Determine whether this type is more qualified than the other
/// given type, requiring exact equality for non-CVR qualifiers.
bool isMoreQualifiedThan(QualType Other) const;
/// Determine whether this type is at least as qualified as the other
/// given type, requiring exact equality for non-CVR qualifiers.
bool isAtLeastAsQualifiedAs(QualType Other) const;
QualType getNonReferenceType() const;
/// Determine the type of a (typically non-lvalue) expression with the
/// specified result type.
///
/// This routine should be used for expressions for which the return type is
/// explicitly specified (e.g., in a cast or call) and isn't necessarily
/// an lvalue. It removes a top-level reference (since there are no
/// expressions of reference type) and deletes top-level cvr-qualifiers
/// from non-class types (in C++) or all types (in C).
QualType getNonLValueExprType(const ASTContext &Context) const;
/// Return the specified type with any "sugar" removed from
/// the type. This takes off typedefs, typeof's etc. If the outer level of
/// the type is already concrete, it returns it unmodified. This is similar
/// to getting the canonical type, but it doesn't remove *all* typedefs. For
/// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
/// concrete.
///
/// Qualifiers are left in place.
QualType getDesugaredType(const ASTContext &Context) const {
return getDesugaredType(*this, Context);
}
SplitQualType getSplitDesugaredType() const {
return getSplitDesugaredType(*this);
}
/// Return the specified type with one level of "sugar" removed from
/// the type.
///
/// This routine takes off the first typedef, typeof, etc. If the outer level
/// of the type is already concrete, it returns it unmodified.
QualType getSingleStepDesugaredType(const ASTContext &Context) const {
return getSingleStepDesugaredTypeImpl(*this, Context);
}
/// Returns the specified type after dropping any
/// outer-level parentheses.
QualType IgnoreParens() const {
if (isa<ParenType>(*this))
return QualType::IgnoreParens(*this);
return *this;
}
/// Indicate whether the specified types and qualifiers are identical.
friend bool operator==(const QualType &LHS, const QualType &RHS) {
return LHS.Value == RHS.Value;
}
friend bool operator!=(const QualType &LHS, const QualType &RHS) {
return LHS.Value != RHS.Value;
}
static std::string getAsString(SplitQualType split,
const PrintingPolicy &Policy) {
return getAsString(split.Ty, split.Quals, Policy);
}
static std::string getAsString(const Type *ty, Qualifiers qs,
const PrintingPolicy &Policy);
std::string getAsString() const;
std::string getAsString(const PrintingPolicy &Policy) const;
void print(raw_ostream &OS, const PrintingPolicy &Policy,
const Twine &PlaceHolder = Twine(),
unsigned Indentation = 0) const {
print(split(), OS, Policy, PlaceHolder, Indentation);
}
static void print(SplitQualType split, raw_ostream &OS,
const PrintingPolicy &policy, const Twine &PlaceHolder,
unsigned Indentation = 0) {
return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
}
static void print(const Type *ty, Qualifiers qs,
raw_ostream &OS, const PrintingPolicy &policy,
const Twine &PlaceHolder,
unsigned Indentation = 0);
void getAsStringInternal(std::string &Str,
const PrintingPolicy &Policy) const {
return getAsStringInternal(split(), Str, Policy);
}
static void getAsStringInternal(SplitQualType split, std::string &out,
const PrintingPolicy &policy) {
return getAsStringInternal(split.Ty, split.Quals, out, policy);
}
static void getAsStringInternal(const Type *ty, Qualifiers qs,
std::string &out,
const PrintingPolicy &policy);
class StreamedQualTypeHelper {
const QualType &T;
const PrintingPolicy &Policy;
const Twine &PlaceHolder;
unsigned Indentation;
public:
StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
const Twine &PlaceHolder, unsigned Indentation)
: T(T), Policy(Policy), PlaceHolder(PlaceHolder),
Indentation(Indentation) {}
friend raw_ostream &operator<<(raw_ostream &OS,
const StreamedQualTypeHelper &SQT) {
SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
return OS;
}
};
StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
const Twine &PlaceHolder = Twine(),
unsigned Indentation = 0) const {
return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
}
void dump(const char *s) const;
void dump() const;
void dump(llvm::raw_ostream &OS) const;
void Profile(llvm::FoldingSetNodeID &ID) const {
ID.AddPointer(getAsOpaquePtr());
}
/// Return the address space of this type.
inline LangAS getAddressSpace() const;
/// Returns gc attribute of this type.
inline Qualifiers::GC getObjCGCAttr() const;
/// true when Type is objc's weak.
bool isObjCGCWeak() const {
return getObjCGCAttr() == Qualifiers::Weak;
}
/// true when Type is objc's strong.
bool isObjCGCStrong() const {
return getObjCGCAttr() == Qualifiers::Strong;
}
/// Returns lifetime attribute of this type.
Qualifiers::ObjCLifetime getObjCLifetime() const {
return getQualifiers().getObjCLifetime();
}
bool hasNonTrivialObjCLifetime() const {
return getQualifiers().hasNonTrivialObjCLifetime();
}
bool hasStrongOrWeakObjCLifetime() const {
return getQualifiers().hasStrongOrWeakObjCLifetime();
}
// true when Type is objc's weak and weak is enabled but ARC isn't.
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
enum PrimitiveDefaultInitializeKind {
/// The type does not fall into any of the following categories. Note that
/// this case is zero-valued so that values of this enum can be used as a
/// boolean condition for non-triviality.
PDIK_Trivial,
/// The type is an Objective-C retainable pointer type that is qualified
/// with the ARC __strong qualifier.
PDIK_ARCStrong,
/// The type is an Objective-C retainable pointer type that is qualified
/// with the ARC __weak qualifier.
PDIK_ARCWeak,
/// The type is a struct containing a field whose type is not PCK_Trivial.
PDIK_Struct
};
/// Functions to query basic properties of non-trivial C struct types.
/// Check if this is a non-trivial type that would cause a C struct
/// transitively containing this type to be non-trivial to default initialize
/// and return the kind.
PrimitiveDefaultInitializeKind
isNonTrivialToPrimitiveDefaultInitialize() const;
enum PrimitiveCopyKind {
/// The type does not fall into any of the following categories. Note that
/// this case is zero-valued so that values of this enum can be used as a
/// boolean condition for non-triviality.
PCK_Trivial,
/// The type would be trivial except that it is volatile-qualified. Types
/// that fall into one of the other non-trivial cases may additionally be
/// volatile-qualified.
PCK_VolatileTrivial,
/// The type is an Objective-C retainable pointer type that is qualified
/// with the ARC __strong qualifier.
PCK_ARCStrong,
/// The type is an Objective-C retainable pointer type that is qualified
/// with the ARC __weak qualifier.
PCK_ARCWeak,
/// The type is a struct containing a field whose type is neither
/// PCK_Trivial nor PCK_VolatileTrivial.
/// Note that a C++ struct type does not necessarily match this; C++ copying
/// semantics are too complex to express here, in part because they depend
/// on the exact constructor or assignment operator that is chosen by
/// overload resolution to do the copy.
PCK_Struct
};
/// Check if this is a non-trivial type that would cause a C struct
/// transitively containing this type to be non-trivial to copy and return the
/// kind.
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
/// Check if this is a non-trivial type that would cause a C struct
/// transitively containing this type to be non-trivial to destructively
/// move and return the kind. Destructive move in this context is a C++-style
/// move in which the source object is placed in a valid but unspecified state
/// after it is moved, as opposed to a truly destructive move in which the
/// source object is placed in an uninitialized state.
PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
enum DestructionKind {
DK_none,
DK_cxx_destructor,
DK_objc_strong_lifetime,
DK_objc_weak_lifetime,
DK_nontrivial_c_struct
};
/// Returns a nonzero value if objects of this type require
/// non-trivial work to clean up after. Non-zero because it's
/// conceivable that qualifiers (objc_gc(weak)?) could make
/// something require destruction.
DestructionKind isDestructedType() const {
return isDestructedTypeImpl(*this);
}
/// Determine whether expressions of the given type are forbidden
/// from being lvalues in C.
///
/// The expression types that are forbidden to be lvalues are:
/// - 'void', but not qualified void
/// - function types
///
/// The exact rule here is C99 6.3.2.1:
/// An lvalue is an expression with an object type or an incomplete
/// type other than void.
bool isCForbiddenLValueType() const;
/// Substitute type arguments for the Objective-C type parameters used in the
/// subject type.
///
/// \param ctx ASTContext in which the type exists.
///
/// \param typeArgs The type arguments that will be substituted for the
/// Objective-C type parameters in the subject type, which are generally
/// computed via \c Type::getObjCSubstitutions. If empty, the type
/// parameters will be replaced with their bounds or id/Class, as appropriate
/// for the context.
///
/// \param context The context in which the subject type was written.
///
/// \returns the resulting type.
QualType substObjCTypeArgs(ASTContext &ctx,
ArrayRef<QualType> typeArgs,
ObjCSubstitutionContext context) const;
/// Substitute type arguments from an object type for the Objective-C type
/// parameters used in the subject type.
///
/// This operation combines the computation of type arguments for
/// substitution (\c Type::getObjCSubstitutions) with the actual process of
/// substitution (\c QualType::substObjCTypeArgs) for the convenience of
/// callers that need to perform a single substitution in isolation.
///
/// \param objectType The type of the object whose member type we're
/// substituting into. For example, this might be the receiver of a message
/// or the base of a property access.
///
/// \param dc The declaration context from which the subject type was
/// retrieved, which indicates (for example) which type parameters should
/// be substituted.
///
/// \param context The context in which the subject type was written.
///
/// \returns the subject type after replacing all of the Objective-C type
/// parameters with their corresponding arguments.
QualType substObjCMemberType(QualType objectType,
const DeclContext *dc,
ObjCSubstitutionContext context) const;
/// Strip Objective-C "__kindof" types from the given type.
QualType stripObjCKindOfType(const ASTContext &ctx) const;
/// Remove all qualifiers including _Atomic.
QualType getAtomicUnqualifiedType() const;
private:
// These methods are implemented in a separate translation unit;
// "static"-ize them to avoid creating temporary QualTypes in the
// caller.
static bool isConstant(QualType T, const ASTContext& Ctx);
static QualType getDesugaredType(QualType T, const ASTContext &Context);
static SplitQualType getSplitDesugaredType(QualType T);
static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
static QualType getSingleStepDesugaredTypeImpl(QualType type,
const ASTContext &C);
static QualType IgnoreParens(QualType T);
static DestructionKind isDestructedTypeImpl(QualType type);
};
} // namespace clang
namespace llvm {
/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
/// to a specific Type class.
template<> struct simplify_type< ::clang::QualType> {
using SimpleType = const ::clang::Type *;
static SimpleType getSimplifiedValue(::clang::QualType Val) {
return Val.getTypePtr();
}
};
// Teach SmallPtrSet that QualType is "basically a pointer".
template<>
struct PointerLikeTypeTraits<clang::QualType> {
static inline void *getAsVoidPointer(clang::QualType P) {
return P.getAsOpaquePtr();
}
static inline clang::QualType getFromVoidPointer(void *P) {
return clang::QualType::getFromOpaquePtr(P);
}
// Various qualifiers go in low bits.
enum { NumLowBitsAvailable = 0 };
};
} // namespace llvm
namespace clang {
/// Base class that is common to both the \c ExtQuals and \c Type
/// classes, which allows \c QualType to access the common fields between the
/// two.
class ExtQualsTypeCommonBase {
friend class ExtQuals;
friend class QualType;
friend class Type;
/// The "base" type of an extended qualifiers type (\c ExtQuals) or
/// a self-referential pointer (for \c Type).
///
/// This pointer allows an efficient mapping from a QualType to its
/// underlying type pointer.
const Type *const BaseType;
/// The canonical type of this type. A QualType.
QualType CanonicalType;
ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
: BaseType(baseType), CanonicalType(canon) {}
};
/// We can encode up to four bits in the low bits of a
/// type pointer, but there are many more type qualifiers that we want
/// to be able to apply to an arbitrary type. Therefore we have this
/// struct, intended to be heap-allocated and used by QualType to
/// store qualifiers.
///
/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
/// in three low bits on the QualType pointer; a fourth bit records whether
/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
/// Objective-C GC attributes) are much more rare.
class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
// NOTE: changing the fast qualifiers should be straightforward as
// long as you don't make 'const' non-fast.
// 1. Qualifiers:
// a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
// Fast qualifiers must occupy the low-order bits.
// b) Update Qualifiers::FastWidth and FastMask.
// 2. QualType:
// a) Update is{Volatile,Restrict}Qualified(), defined inline.
// b) Update remove{Volatile,Restrict}, defined near the end of
// this header.
// 3. ASTContext:
// a) Update get{Volatile,Restrict}Type.
/// The immutable set of qualifiers applied by this node. Always contains
/// extended qualifiers.
Qualifiers Quals;
ExtQuals *this_() { return this; }
public:
ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
: ExtQualsTypeCommonBase(baseType,
canon.isNull() ? QualType(this_(), 0) : canon),
Quals(quals) {
assert(Quals.hasNonFastQualifiers()
&& "ExtQuals created with no fast qualifiers");
assert(!Quals.hasFastQualifiers()
&& "ExtQuals created with fast qualifiers");
}
Qualifiers getQualifiers() const { return Quals; }
bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
Qualifiers::ObjCLifetime getObjCLifetime() const {
return Quals.getObjCLifetime();
}
bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
const Type *getBaseType() const { return BaseType; }
public:
void Profile(llvm::FoldingSetNodeID &ID) const {
Profile(ID, getBaseType(), Quals);
}
static void Profile(llvm::FoldingSetNodeID &ID,
const Type *BaseType,
Qualifiers Quals) {
assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
ID.AddPointer(BaseType);
Quals.Profile(ID);
}
};
/// The kind of C++11 ref-qualifier associated with a function type.
/// This determines whether a member function's "this" object can be an
/// lvalue, rvalue, or neither.
enum RefQualifierKind {
/// No ref-qualifier was provided.
RQ_None = 0,
/// An lvalue ref-qualifier was provided (\c &).
RQ_LValue,
/// An rvalue ref-qualifier was provided (\c &&).
RQ_RValue
};
/// Which keyword(s) were used to create an AutoType.
enum class AutoTypeKeyword {
/// auto
Auto,
/// decltype(auto)
DecltypeAuto,
/// __auto_type (GNU extension)
GNUAutoType
};
/// The base class of the type hierarchy.
///
/// A central concept with types is that each type always has a canonical
/// type. A canonical type is the type with any typedef names stripped out
/// of it or the types it references. For example, consider:
///
/// typedef int foo;
/// typedef foo* bar;
/// 'int *' 'foo *' 'bar'
///
/// There will be a Type object created for 'int'. Since int is canonical, its
/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
/// there is a PointerType that represents 'int*', which, like 'int', is
/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
/// is also 'int*'.
///
/// Non-canonical types are useful for emitting diagnostics, without losing
/// information about typedefs being used. Canonical types are useful for type
/// comparisons (they allow by-pointer equality tests) and useful for reasoning
/// about whether something has a particular form (e.g. is a function type),
/// because they implicitly, recursively, strip all typedefs out of a type.
///
/// Types, once created, are immutable.
///
class Type : public ExtQualsTypeCommonBase {
public:
enum TypeClass {
#define TYPE(Class, Base) Class,
#define LAST_TYPE(Class) TypeLast = Class,
#define ABSTRACT_TYPE(Class, Base)
#include "clang/AST/TypeNodes.def"
TagFirst = Record, TagLast = Enum
};
private:
/// Bitfields required by the Type class.
class TypeBitfields {
friend class Type;
template <class T> friend class TypePropertyCache;
/// TypeClass bitfield - Enum that specifies what subclass this belongs to.
unsigned TC : 8;
/// Whether this type is a dependent type (C++ [temp.dep.type]).
unsigned Dependent : 1;
/// Whether this type somehow involves a template parameter, even
/// if the resolution of the type does not depend on a template parameter.
unsigned InstantiationDependent : 1;
/// Whether this type is a variably-modified type (C99 6.7.5).
unsigned VariablyModified : 1;
/// Whether this type contains an unexpanded parameter pack
/// (for C++11 variadic templates).
unsigned ContainsUnexpandedParameterPack : 1;
/// True if the cache (i.e. the bitfields here starting with
/// 'Cache') is valid.
mutable unsigned CacheValid : 1;
/// Linkage of this type.
mutable unsigned CachedLinkage : 3;
/// Whether this type involves and local or unnamed types.
mutable unsigned CachedLocalOrUnnamed : 1;
/// Whether this type comes from an AST file.
mutable unsigned FromAST : 1;
bool isCacheValid() const {
return CacheValid;
}
Linkage getLinkage() const {
assert(isCacheValid() && "getting linkage from invalid cache");
return static_cast<Linkage>(CachedLinkage);
}
bool hasLocalOrUnnamedType() const {
assert(isCacheValid() && "getting linkage from invalid cache");
return CachedLocalOrUnnamed;
}
};
enum { NumTypeBits = 18 };
protected:
// These classes allow subclasses to somewhat cleanly pack bitfields
// into Type.
class ArrayTypeBitfields {
friend class ArrayType;
unsigned : NumTypeBits;
/// CVR qualifiers from declarations like
/// 'int X[static restrict 4]'. For function parameters only.
unsigned IndexTypeQuals : 3;
/// Storage class qualifiers from declarations like
/// 'int X[static restrict 4]'. For function parameters only.
/// Actually an ArrayType::ArraySizeModifier.
unsigned SizeModifier : 3;
};
class BuiltinTypeBitfields {
friend class BuiltinType;
unsigned : NumTypeBits;
/// The kind (BuiltinType::Kind) of builtin type this is.
unsigned Kind : 8;
};
class FunctionTypeBitfields {
friend class FunctionProtoType;
friend class FunctionType;
unsigned : NumTypeBits;
/// Extra information which affects how the function is called, like
/// regparm and the calling convention.
unsigned ExtInfo : 12;
/// Used only by FunctionProtoType, put here to pack with the
/// other bitfields.
/// The qualifiers are part of FunctionProtoType because...
///
/// C++ 8.3.5p4: The return type, the parameter type list and the
/// cv-qualifier-seq, [...], are part of the function type.
unsigned TypeQuals : 4;
/// The ref-qualifier associated with a \c FunctionProtoType.
///
/// This is a value of type \c RefQualifierKind.
unsigned RefQualifier : 2;
};
class ObjCObjectTypeBitfields {
friend class ObjCObjectType;
unsigned : NumTypeBits;
/// The number of type arguments stored directly on this object type.
unsigned NumTypeArgs : 7;
/// The number of protocols stored directly on this object type.
unsigned NumProtocols : 6;
/// Whether this is a "kindof" type.
unsigned IsKindOf : 1;
};
class ReferenceTypeBitfields {
friend class ReferenceType;
unsigned : NumTypeBits;
/// True if the type was originally spelled with an lvalue sigil.
/// This is never true of rvalue references but can also be false
/// on lvalue references because of C++0x [dcl.typedef]p9,
/// as follows:
///
/// typedef int &ref; // lvalue, spelled lvalue
/// typedef int &&rvref; // rvalue
/// ref &a; // lvalue, inner ref, spelled lvalue
/// ref &&a; // lvalue, inner ref
/// rvref &a; // lvalue, inner ref, spelled lvalue
/// rvref &&a; // rvalue, inner ref
unsigned SpelledAsLValue : 1;
/// True if the inner type is a reference type. This only happens
/// in non-canonical forms.
unsigned InnerRef : 1;
};
class TypeWithKeywordBitfields {
friend class TypeWithKeyword;
unsigned : NumTypeBits;
/// An ElaboratedTypeKeyword. 8 bits for efficient access.
unsigned Keyword : 8;
};
class VectorTypeBitfields {
friend class VectorType;
friend class DependentVectorType;
unsigned : NumTypeBits;
/// The kind of vector, either a generic vector type or some
/// target-specific vector type such as for AltiVec or Neon.
unsigned VecKind : 3;
/// The number of elements in the vector.
unsigned NumElements : 29 - NumTypeBits;
enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
};
class AttributedTypeBitfields {
friend class AttributedType;
unsigned : NumTypeBits;
/// An AttributedType::Kind
unsigned AttrKind : 32 - NumTypeBits;
};
class AutoTypeBitfields {
friend class AutoType;
unsigned : NumTypeBits;
/// Was this placeholder type spelled as 'auto', 'decltype(auto)',
/// or '__auto_type'? AutoTypeKeyword value.
unsigned Keyword : 2;
};
union {
TypeBitfields TypeBits;
ArrayTypeBitfields ArrayTypeBits;
AttributedTypeBitfields AttributedTypeBits;
AutoTypeBitfields AutoTypeBits;
BuiltinTypeBitfields BuiltinTypeBits;
FunctionTypeBitfields FunctionTypeBits;
ObjCObjectTypeBitfields ObjCObjectTypeBits;
ReferenceTypeBitfields ReferenceTypeBits;
TypeWithKeywordBitfields TypeWithKeywordBits;
VectorTypeBitfields VectorTypeBits;
static_assert(sizeof(TypeBitfields) <= 8,
"TypeBitfields is larger than 8 bytes!");
static_assert(sizeof(ArrayTypeBitfields) <= 8,
"ArrayTypeBitfields is larger than 8 bytes!");
static_assert(sizeof(AttributedTypeBitfields) <= 8,
"AttributedTypeBitfields is larger than 8 bytes!");
static_assert(sizeof(AutoTypeBitfields) <= 8,
"AutoTypeBitfields is larger than 8 bytes!");
static_assert(sizeof(BuiltinTypeBitfields) <= 8,
"BuiltinTypeBitfields is larger than 8 bytes!");
static_assert(sizeof(FunctionTypeBitfields) <= 8,
"FunctionTypeBitfields is larger than 8 bytes!");
static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
"ObjCObjectTypeBitfields is larger than 8 bytes!");
static_assert(sizeof(ReferenceTypeBitfields) <= 8,
"ReferenceTypeBitfields is larger than 8 bytes!");
static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
"TypeWithKeywordBitfields is larger than 8 bytes!");
static_assert(sizeof(VectorTypeBitfields) <= 8,
"VectorTypeBitfields is larger than 8 bytes!");
};
private:
template <class T> friend class TypePropertyCache;
/// Set whether this type comes from an AST file.
void setFromAST(bool V = true) const {
TypeBits.FromAST = V;
}
protected:
friend class ASTContext;
Type(TypeClass tc, QualType canon, bool Dependent,
bool InstantiationDependent, bool VariablyModified,
bool ContainsUnexpandedParameterPack)
: ExtQualsTypeCommonBase(this,
canon.isNull() ? QualType(this_(), 0) : canon) {
TypeBits.TC = tc;
TypeBits.Dependent = Dependent;
TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
TypeBits.VariablyModified = VariablyModified;
TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
TypeBits.CacheValid = false;
TypeBits.CachedLocalOrUnnamed = false;
TypeBits.CachedLinkage = NoLinkage;
TypeBits.FromAST = false;
}
// silence VC++ warning C4355: 'this' : used in base member initializer list
Type *this_() { return this; }
void setDependent(bool D = true) {
TypeBits.Dependent = D;
if (D)
TypeBits.InstantiationDependent = true;
}
void setInstantiationDependent(bool D = true) {
TypeBits.InstantiationDependent = D; }
void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
void setContainsUnexpandedParameterPack(bool PP = true) {
TypeBits.ContainsUnexpandedParameterPack = PP;
}
public:
friend class ASTReader;
friend class ASTWriter;
Type(const Type &) = delete;
Type &operator=(const Type &) = delete;
TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
/// Whether this type comes from an AST file.
bool isFromAST() const { return TypeBits.FromAST; }
/// Whether this type is or contains an unexpanded parameter
/// pack, used to support C++0x variadic templates.
///
/// A type that contains a parameter pack shall be expanded by the
/// ellipsis operator at some point. For example, the typedef in the
/// following example contains an unexpanded parameter pack 'T':
///
/// \code
/// template<typename ...T>
/// struct X {
/// typedef T* pointer_types; // ill-formed; T is a parameter pack.
/// };
/// \endcode
///
/// Note that this routine does not specify which
bool containsUnexpandedParameterPack() const {
return TypeBits.ContainsUnexpandedParameterPack;
}
/// Determines if this type would be canonical if it had no further
/// qualification.
bool isCanonicalUnqualified() const {
return CanonicalType == QualType(this, 0);
}
/// Pull a single level of sugar off of this locally-unqualified type.
/// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
/// or QualType::getSingleStepDesugaredType(const ASTContext&).
QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
/// Types are partitioned into 3 broad categories (C99 6.2.5p1):
/// object types, function types, and incomplete types.
/// Return true if this is an incomplete type.
/// A type that can describe objects, but which lacks information needed to
/// determine its size (e.g. void, or a fwd declared struct). Clients of this
/// routine will need to determine if the size is actually required.
///
/// Def If non-null, and the type refers to some kind of declaration
/// that can be completed (such as a C struct, C++ class, or Objective-C
/// class), will be set to the declaration.
bool isIncompleteType(NamedDecl **Def = nullptr) const;
/// Return true if this is an incomplete or object
/// type, in other words, not a function type.
bool isIncompleteOrObjectType() const {
return !isFunctionType();
}
/// Determine whether this type is an object type.
bool isObjectType() const {
// C++ [basic.types]p8:
// An object type is a (possibly cv-qualified) type that is not a
// function type, not a reference type, and not a void type.
return !isReferenceType() && !isFunctionType() && !isVoidType();
}
/// Return true if this is a literal type
/// (C++11 [basic.types]p10)
bool isLiteralType(const ASTContext &Ctx) const;
/// Test if this type is a standard-layout type.
/// (C++0x [basic.type]p9)
bool isStandardLayoutType() const;
/// Helper methods to distinguish type categories. All type predicates
/// operate on the canonical type, ignoring typedefs and qualifiers.
/// Returns true if the type is a builtin type.
bool isBuiltinType() const;
/// Test for a particular builtin type.
bool isSpecificBuiltinType(unsigned K) const;
/// Test for a type which does not represent an actual type-system type but
/// is instead used as a placeholder for various convenient purposes within
/// Clang. All such types are BuiltinTypes.
bool isPlaceholderType() const;
const BuiltinType *getAsPlaceholderType() const;
/// Test for a specific placeholder type.
bool isSpecificPlaceholderType(unsigned K) const;
/// Test for a placeholder type other than Overload; see
/// BuiltinType::isNonOverloadPlaceholderType.
bool isNonOverloadPlaceholderType() const;
/// isIntegerType() does *not* include complex integers (a GCC extension).
/// isComplexIntegerType() can be used to test for complex integers.
bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
bool isEnumeralType() const;
/// Determine whether this type is a scoped enumeration type.
bool isScopedEnumeralType() const;
bool isBooleanType() const;
bool isCharType() const;
bool isWideCharType() const;
bool isChar8Type() const;
bool isChar16Type() const;
bool isChar32Type() const;
bool isAnyCharacterType() const;
bool isIntegralType(const ASTContext &Ctx) const;
/// Determine whether this type is an integral or enumeration type.
bool isIntegralOrEnumerationType() const;
/// Determine whether this type is an integral or unscoped enumeration type.
bool isIntegralOrUnscopedEnumerationType() const;
/// Floating point categories.
bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
/// isComplexType() does *not* include complex integers (a GCC extension).
/// isComplexIntegerType() can be used to test for complex integers.
bool isComplexType() const; // C99 6.2.5p11 (complex)
bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
bool isFloat128Type() const;
bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
bool isVoidType() const; // C99 6.2.5p19
bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
bool isAggregateType() const;
bool isFundamentalType() const;
bool isCompoundType() const;
// Type Predicates: Check to see if this type is structurally the specified
// type, ignoring typedefs and qualifiers.
bool isFunctionType() const;
bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
bool isPointerType() const;
bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
bool isBlockPointerType() const;
bool isVoidPointerType() const;
bool isReferenceType() const;
bool isLValueReferenceType() const;
bool isRValueReferenceType() const;
bool isFunctionPointerType() const;
bool isMemberPointerType() const;
bool isMemberFunctionPointerType() const;
bool isMemberDataPointerType() const;
bool isArrayType() const;
bool isConstantArrayType() const;
bool isIncompleteArrayType() const;
bool isVariableArrayType() const;
bool isDependentSizedArrayType() const;
bool isRecordType() const;
bool isClassType() const;
bool isStructureType() const;
bool isObjCBoxableRecordType() const;
bool isInterfaceType() const;
bool isStructureOrClassType() const;
bool isUnionType() const;
bool isComplexIntegerType() const; // GCC _Complex integer type.
bool isVectorType() const; // GCC vector type.
bool isExtVectorType() const; // Extended vector type.
bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
bool isObjCObjectPointerType() const; // pointer to ObjC object
bool isObjCRetainableType() const; // ObjC object or block pointer
bool isObjCLifetimeType() const; // (array of)* retainable type
bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
bool isObjCNSObjectType() const; // __attribute__((NSObject))
bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
// FIXME: change this to 'raw' interface type, so we can used 'interface' type
// for the common case.
bool isObjCObjectType() const; // NSString or typeof(*(id)0)
bool isObjCQualifiedInterfaceType() const; // NSString<foo>
bool isObjCQualifiedIdType() const; // id<foo>
bool isObjCQualifiedClassType() const; // Class<foo>
bool isObjCObjectOrInterfaceType() const;
bool isObjCIdType() const; // id
-
- /// Was this type written with the special inert-in-ARC __unsafe_unretained
- /// qualifier?
- ///
- /// This approximates the answer to the following question: if this
- /// translation unit were compiled in ARC, would this type be qualified
- /// with __unsafe_unretained?
- bool isObjCInertUnsafeUnretainedType() const {
- return hasAttr(attr::ObjCInertUnsafeUnretained);
- }
+ bool isObjCInertUnsafeUnretainedType() const;
/// Whether the type is Objective-C 'id' or a __kindof type of an
/// object type, e.g., __kindof NSView * or __kindof id
/// <NSCopying>.
///
/// \param bound Will be set to the bound on non-id subtype types,
/// which will be (possibly specialized) Objective-C class type, or
/// null for 'id.
bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
const ObjCObjectType *&bound) const;
bool isObjCClassType() const; // Class
/// Whether the type is Objective-C 'Class' or a __kindof type of an
/// Class type, e.g., __kindof Class <NSCopying>.
///
/// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
/// here because Objective-C's type system cannot express "a class
/// object for a subclass of NSFoo".
bool isObjCClassOrClassKindOfType() const;
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
bool isObjCSelType() const; // Class
bool isObjCBuiltinType() const; // 'id' or 'Class'
bool isObjCARCBridgableType() const;
bool isCARCBridgableType() const;
bool isTemplateTypeParmType() const; // C++ template type parameter
bool isNullPtrType() const; // C++11 std::nullptr_t
bool isAlignValT() const; // C++17 std::align_val_t
bool isStdByteType() const; // C++17 std::byte
bool isAtomicType() const; // C11 _Atomic()
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
bool is##Id##Type() const;
#include "clang/Basic/OpenCLImageTypes.def"
bool isImageType() const; // Any OpenCL image type
bool isSamplerT() const; // OpenCL sampler_t
bool isEventT() const; // OpenCL event_t
bool isClkEventT() const; // OpenCL clk_event_t
bool isQueueT() const; // OpenCL queue_t
bool isReserveIDT() const; // OpenCL reserve_id_t
bool isPipeType() const; // OpenCL pipe type
bool isOpenCLSpecificType() const; // Any OpenCL specific type
/// Determines if this type, which must satisfy
/// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
/// than implicitly __strong.
bool isObjCARCImplicitlyUnretainedType() const;
/// Return the implicit lifetime for this type, which must not be dependent.
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
enum ScalarTypeKind {
STK_CPointer,
STK_BlockPointer,
STK_ObjCObjectPointer,
STK_MemberPointer,
STK_Bool,
STK_Integral,
STK_Floating,
STK_IntegralComplex,
STK_FloatingComplex
};
/// Given that this is a scalar type, classify it.
ScalarTypeKind getScalarTypeKind() const;
/// Whether this type is a dependent type, meaning that its definition
/// somehow depends on a template parameter (C++ [temp.dep.type]).
bool isDependentType() const { return TypeBits.Dependent; }
/// Determine whether this type is an instantiation-dependent type,
/// meaning that the type involves a template parameter (even if the
/// definition does not actually depend on the type substituted for that
/// template parameter).
bool isInstantiationDependentType() const {
return TypeBits.InstantiationDependent;
}
/// Determine whether this type is an undeduced type, meaning that
/// it somehow involves a C++11 'auto' type or similar which has not yet been
/// deduced.
bool isUndeducedType() const;
/// Whether this type is a variably-modified type (C99 6.7.5).
bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
/// Whether this type involves a variable-length array type
/// with a definite size.
bool hasSizedVLAType() const;
/// Whether this type is or contains a local or unnamed type.
bool hasUnnamedOrLocalType() const;
bool isOverloadableType() const;
/// Determine wither this type is a C++ elaborated-type-specifier.
bool isElaboratedTypeSpecifier() const;
bool canDecayToPointerType() const;
/// Whether this type is represented natively as a pointer. This includes
/// pointers, references, block pointers, and Objective-C interface,
/// qualified id, and qualified interface types, as well as nullptr_t.
bool hasPointerRepresentation() const;
/// Whether this type can represent an objective pointer type for the
/// purpose of GC'ability
bool hasObjCPointerRepresentation() const;
/// Determine whether this type has an integer representation
/// of some sort, e.g., it is an integer type or a vector.
bool hasIntegerRepresentation() const;
/// Determine whether this type has an signed integer representation
/// of some sort, e.g., it is an signed integer type or a vector.
bool hasSignedIntegerRepresentation() const;
/// Determine whether this type has an unsigned integer representation
/// of some sort, e.g., it is an unsigned integer type or a vector.
bool hasUnsignedIntegerRepresentation() const;
/// Determine whether this type has a floating-point representation
/// of some sort, e.g., it is a floating-point type or a vector thereof.
bool hasFloatingRepresentation() const;
// Type Checking Functions: Check to see if this type is structurally the
// specified type, ignoring typedefs and qualifiers, and return a pointer to
// the best type we can.
const RecordType *getAsStructureType() const;
/// NOTE: getAs*ArrayType are methods on ASTContext.
const RecordType *getAsUnionType() const;
const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
const ObjCObjectType *getAsObjCInterfaceType() const;
// The following is a convenience method that returns an ObjCObjectPointerType
// for object declared using an interface.
const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
/// Retrieves the CXXRecordDecl that this type refers to, either
/// because the type is a RecordType or because it is the injected-class-name
/// type of a class template or class template partial specialization.
CXXRecordDecl *getAsCXXRecordDecl() const;
/// Retrieves the RecordDecl this type refers to.
RecordDecl *getAsRecordDecl() const;
/// Retrieves the TagDecl that this type refers to, either
/// because the type is a TagType or because it is the injected-class-name
/// type of a class template or class template partial specialization.
TagDecl *getAsTagDecl() const;
/// If this is a pointer or reference to a RecordType, return the
/// CXXRecordDecl that the type refers to.
///
/// If this is not a pointer or reference, or the type being pointed to does
/// not refer to a CXXRecordDecl, returns NULL.
const CXXRecordDecl *getPointeeCXXRecordDecl() const;
/// Get the DeducedType whose type will be deduced for a variable with
/// an initializer of this type. This looks through declarators like pointer
/// types, but not through decltype or typedefs.
DeducedType *getContainedDeducedType() const;
/// Get the AutoType whose type will be deduced for a variable with
/// an initializer of this type. This looks through declarators like pointer
/// types, but not through decltype or typedefs.
AutoType *getContainedAutoType() const {
return dyn_cast_or_null<AutoType>(getContainedDeducedType());
}
/// Determine whether this type was written with a leading 'auto'
/// corresponding to a trailing return type (possibly for a nested
/// function type within a pointer to function type or similar).
bool hasAutoForTrailingReturnType() const;
/// Member-template getAs<specific type>'. Look through sugar for
/// an instance of \<specific type>. This scheme will eventually
/// replace the specific getAsXXXX methods above.
///
/// There are some specializations of this member template listed
/// immediately following this class.
template <typename T> const T *getAs() const;
/// Member-template getAsAdjusted<specific type>. Look through specific kinds
/// of sugar (parens, attributes, etc) for an instance of \<specific type>.
/// This is used when you need to walk over sugar nodes that represent some
/// kind of type adjustment from a type that was written as a \<specific type>
/// to another type that is still canonically a \<specific type>.
template <typename T> const T *getAsAdjusted() const;
/// A variant of getAs<> for array types which silently discards
/// qualifiers from the outermost type.
const ArrayType *getAsArrayTypeUnsafe() const;
/// Member-template castAs<specific type>. Look through sugar for
/// the underlying instance of \<specific type>.
///
/// This method has the same relationship to getAs<T> as cast<T> has
/// to dyn_cast<T>; which is to say, the underlying type *must*
/// have the intended type, and this method will never return null.
template <typename T> const T *castAs() const;
/// A variant of castAs<> for array type which silently discards
/// qualifiers from the outermost type.
const ArrayType *castAsArrayTypeUnsafe() const;
- /// Determine whether this type had the specified attribute applied to it
- /// (looking through top-level type sugar).
- bool hasAttr(attr::Kind AK) const;
-
/// Get the base element type of this type, potentially discarding type
/// qualifiers. This should never be used when type qualifiers
/// are meaningful.
const Type *getBaseElementTypeUnsafe() const;
/// If this is an array type, return the element type of the array,
/// potentially with type qualifiers missing.
/// This should never be used when type qualifiers are meaningful.
const Type *getArrayElementTypeNoTypeQual() const;
/// If this is a pointer type, return the pointee type.
/// If this is an array type, return the array element type.
/// This should never be used when type qualifiers are meaningful.
const Type *getPointeeOrArrayElementType() const;
/// If this is a pointer, ObjC object pointer, or block
/// pointer, this returns the respective pointee.
QualType getPointeeType() const;
/// Return the specified type with any "sugar" removed from the type,
/// removing any typedefs, typeofs, etc., as well as any qualifiers.
const Type *getUnqualifiedDesugaredType() const;
/// More type predicates useful for type checking/promotion
bool isPromotableIntegerType() const; // C99 6.3.1.1p2
/// Return true if this is an integer type that is
/// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
/// or an enum decl which has a signed representation.
bool isSignedIntegerType() const;
/// Return true if this is an integer type that is
/// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
/// or an enum decl which has an unsigned representation.
bool isUnsignedIntegerType() const;
/// Determines whether this is an integer type that is signed or an
/// enumeration types whose underlying type is a signed integer type.
bool isSignedIntegerOrEnumerationType() const;
/// Determines whether this is an integer type that is unsigned or an
/// enumeration types whose underlying type is a unsigned integer type.
bool isUnsignedIntegerOrEnumerationType() const;
/// Return true if this is a fixed point type according to
/// ISO/IEC JTC1 SC22 WG14 N1169.
bool isFixedPointType() const;
/// Return true if this is a saturated fixed point type according to
/// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
bool isSaturatedFixedPointType() const;
/// Return true if this is a saturated fixed point type according to
/// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
bool isUnsaturatedFixedPointType() const;
/// Return true if this is a fixed point type that is signed according
/// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
bool isSignedFixedPointType() const;
/// Return true if this is a fixed point type that is unsigned according
/// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
bool isUnsignedFixedPointType() const;
/// Return true if this is not a variable sized type,
/// according to the rules of C99 6.7.5p3. It is not legal to call this on
/// incomplete types.
bool isConstantSizeType() const;
/// Returns true if this type can be represented by some
/// set of type specifiers.
bool isSpecifierType() const;
/// Determine the linkage of this type.
Linkage getLinkage() const;
/// Determine the visibility of this type.
Visibility getVisibility() const {
return getLinkageAndVisibility().getVisibility();
}
/// Return true if the visibility was explicitly set is the code.
bool isVisibilityExplicit() const {
return getLinkageAndVisibility().isVisibilityExplicit();
}
/// Determine the linkage and visibility of this type.
LinkageInfo getLinkageAndVisibility() const;
/// True if the computed linkage is valid. Used for consistency
/// checking. Should always return true.
bool isLinkageValid() const;
/// Determine the nullability of the given type.
///
/// Note that nullability is only captured as sugar within the type
/// system, not as part of the canonical type, so nullability will
/// be lost by canonicalization and desugaring.
Optional<NullabilityKind> getNullability(const ASTContext &context) const;
/// Determine whether the given type can have a nullability
/// specifier applied to it, i.e., if it is any kind of pointer type.
///
/// \param ResultIfUnknown The value to return if we don't yet know whether
/// this type can have nullability because it is dependent.
bool canHaveNullability(bool ResultIfUnknown = true) const;
/// Retrieve the set of substitutions required when accessing a member
/// of the Objective-C receiver type that is declared in the given context.
///
/// \c *this is the type of the object we're operating on, e.g., the
/// receiver for a message send or the base of a property access, and is
/// expected to be of some object or object pointer type.
///
/// \param dc The declaration context for which we are building up a
/// substitution mapping, which should be an Objective-C class, extension,
/// category, or method within.
///
/// \returns an array of type arguments that can be substituted for
/// the type parameters of the given declaration context in any type described
/// within that context, or an empty optional to indicate that no
/// substitution is required.
Optional<ArrayRef<QualType>>
getObjCSubstitutions(const DeclContext *dc) const;
/// Determines if this is an ObjC interface type that may accept type
/// parameters.
bool acceptsObjCTypeParams() const;
const char *getTypeClassName() const;
QualType getCanonicalTypeInternal() const {
return CanonicalType;
}
CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
void dump() const;
void dump(llvm::raw_ostream &OS) const;
};
/// This will check for a TypedefType by removing any existing sugar
/// until it reaches a TypedefType or a non-sugared type.
template <> const TypedefType *Type::getAs() const;
/// This will check for a TemplateSpecializationType by removing any
/// existing sugar until it reaches a TemplateSpecializationType or a
/// non-sugared type.
template <> const TemplateSpecializationType *Type::getAs() const;
/// This will check for an AttributedType by removing any existing sugar
/// until it reaches an AttributedType or a non-sugared type.
template <> const AttributedType *Type::getAs() const;
// We can do canonical leaf types faster, because we don't have to
// worry about preserving child type decoration.
#define TYPE(Class, Base)
#define LEAF_TYPE(Class) \
template <> inline const Class##Type *Type::getAs() const { \
return dyn_cast<Class##Type>(CanonicalType); \
} \
template <> inline const Class##Type *Type::castAs() const { \
return cast<Class##Type>(CanonicalType); \
}
#include "clang/AST/TypeNodes.def"
/// This class is used for builtin types like 'int'. Builtin
/// types are always canonical and have a literal name field.
class BuiltinType : public Type {
public:
enum Kind {
// OpenCL image types
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
#include "clang/Basic/OpenCLImageTypes.def"
// All other builtin types
#define BUILTIN_TYPE(Id, SingletonId) Id,
#define LAST_BUILTIN_TYPE(Id) LastKind = Id
#include "clang/AST/BuiltinTypes.def"
};
private:
friend class ASTContext; // ASTContext creates these.
BuiltinType(Kind K)
: Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
/*InstantiationDependent=*/(K == Dependent),
/*VariablyModified=*/false,
/*Unexpanded parameter pack=*/false) {
BuiltinTypeBits.Kind = K;
}
public:
Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
StringRef getName(const PrintingPolicy &Policy) const;
const char *getNameAsCString(const PrintingPolicy &Policy) const {
// The StringRef is null-terminated.
StringRef str = getName(Policy);
assert(!str.empty() && str.data()[str.size()] == '\0');
return str.data();
}
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
bool isInteger() const {
return getKind() >= Bool && getKind() <= Int128;
}
bool isSignedInteger() const {
return getKind() >= Char_S && getKind() <= Int128;
}
bool isUnsignedInteger() const {
return getKind() >= Bool && getKind() <= UInt128;
}
bool isFloatingPoint() const {
return getKind() >= Half && getKind() <= Float128;
}
/// Determines whether the given kind corresponds to a placeholder type.
static bool isPlaceholderTypeKind(Kind K) {
return K >= Overload;
}
/// Determines whether this type is a placeholder type, i.e. a type
/// which cannot appear in arbitrary positions in a fully-formed
/// expression.
bool isPlaceholderType() const {
return isPlaceholderTypeKind(getKind());
}
/// Determines whether this type is a placeholder type other than
/// Overload. Most placeholder types require only syntactic
/// information about their context in order to be resolved (e.g.
/// whether it is a call expression), which means they can (and
/// should) be resolved in an earlier "phase" of analysis.
/// Overload expressions sometimes pick up further information
/// from their context, like whether the context expects a
/// specific function-pointer type, and so frequently need
/// special treatment.
bool isNonOverloadPlaceholderType() const {
return getKind() > Overload;
}
static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
};
/// Complex values, per C99 6.2.5p11. This supports the C99 complex
/// types (_Complex float etc) as well as the GCC integer complex extensions.
class ComplexType : public Type, public llvm::FoldingSetNode {
friend class ASTContext; // ASTContext creates these.
QualType ElementType;
ComplexType(QualType Element, QualType CanonicalPtr)
: Type(Complex, CanonicalPtr, Element->isDependentType(),
Element->isInstantiationDependentType(),
Element->isVariablyModifiedType(),
Element->containsUnexpandedParameterPack()),
ElementType(Element) {}
public:
QualType getElementType() const { return ElementType; }
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, getElementType());
}
static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
ID.AddPointer(Element.getAsOpaquePtr());
}
static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
};
/// Sugar for parentheses used when specifying types.
class ParenType : public Type, public llvm::FoldingSetNode {
friend class ASTContext; // ASTContext creates these.
QualType Inner;
ParenType(QualType InnerType, QualType CanonType)
: Type(Paren, CanonType, InnerType->isDependentType(),
InnerType->isInstantiationDependentType(),
InnerType->isVariablyModifiedType(),
InnerType->containsUnexpandedParameterPack()),
Inner(InnerType) {}
public:
QualType getInnerType() const { return Inner; }
bool isSugared() const { return true; }
QualType desugar() const { return getInnerType(); }
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, getInnerType());
}
static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
Inner.Profile(ID);
}
static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
};
/// PointerType - C99 6.7.5.1 - Pointer Declarators.
class PointerType : public Type, public llvm::FoldingSetNode {
friend class ASTContext; // ASTContext creates these.
QualType PointeeType;
PointerType(QualType Pointee, QualType CanonicalPtr)
: Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
Pointee->isInstantiationDependentType(),
Pointee->isVariablyModifiedType(),
Pointee->containsUnexpandedParameterPack()),
PointeeType(Pointee) {}
public:
QualType getPointeeType() const { return PointeeType; }
/// Returns true if address spaces of pointers overlap.
/// OpenCL v2.0 defines conversion rules for pointers to different
/// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
/// address spaces.
/// CL1.1 or CL1.2:
/// address spaces overlap iff they are they same.
/// CL2.0 adds:
/// __generic overlaps with any address space except for __constant.
bool isAddressSpaceOverlapping(const PointerType &other) const {
Qualifiers thisQuals = PointeeType.getQualifiers();
Qualifiers otherQuals = other.getPointeeType().getQualifiers();
// Address spaces overlap if at least one of them is a superset of another
return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
otherQuals.isAddressSpaceSupersetOf(thisQuals);
}
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, getPointeeType());
}
static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
ID.AddPointer(Pointee.getAsOpaquePtr());
}
static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
};
/// Represents a type which was implicitly adjusted by the semantic
/// engine for arbitrary reasons. For example, array and function types can
/// decay, and function types can have their calling conventions adjusted.
class AdjustedType : public Type, public llvm::FoldingSetNode {
QualType OriginalTy;
QualType AdjustedTy;
protected:
friend class ASTContext; // ASTContext creates these.
AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
QualType CanonicalPtr)
: Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
OriginalTy->isInstantiationDependentType(),
OriginalTy->isVariablyModifiedType(),
OriginalTy->containsUnexpandedParameterPack()),
OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
public:
QualType getOriginalType() const { return OriginalTy; }
QualType getAdjustedType() const { return AdjustedTy; }
bool isSugared() const { return true; }
QualType desugar() const { return AdjustedTy; }
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, OriginalTy, AdjustedTy);
}
static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
ID.AddPointer(Orig.getAsOpaquePtr());
ID.AddPointer(New.getAsOpaquePtr());
}
static bool classof(const Type *T) {
return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
}
};
/// Represents a pointer type decayed from an array or function type.
class DecayedType : public AdjustedType {
friend class ASTContext; // ASTContext creates these.
inline
DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
public:
QualType getDecayedType() const { return getAdjustedType(); }
inline QualType getPointeeType() const;
static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
};
/// Pointer to a block type.
/// This type is to represent types syntactically represented as
/// "void (^)(int)", etc. Pointee is required to always be a function type.
class BlockPointerType : public Type, public llvm::FoldingSetNode {
friend class ASTContext; // ASTContext creates these.
// Block is some kind of pointer type
QualType PointeeType;
BlockPointerType(QualType Pointee, QualType CanonicalCls)
: Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
Pointee->isInstantiationDependentType(),
Pointee->isVariablyModifiedType(),
Pointee->containsUnexpandedParameterPack()),
PointeeType(Pointee) {}
public:
// Get the pointee type. Pointee is required to always be a function type.
QualType getPointeeType() const { return PointeeType; }
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, getPointeeType());
}
static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
ID.AddPointer(Pointee.getAsOpaquePtr());
}
static bool classof(const Type *T) {
return T->getTypeClass() == BlockPointer;
}
};
/// Base for LValueReferenceType and RValueReferenceType
class ReferenceType : public Type, public llvm::FoldingSetNode {
QualType PointeeType;
protected:
ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
bool SpelledAsLValue)
: Type(tc, CanonicalRef, Referencee->isDependentType(),
Referencee->isInstantiationDependentType(),
Referencee->isVariablyModifiedType(),
Referencee->containsUnexpandedParameterPack()),
PointeeType(Referencee) {
ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
}
public:
bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
QualType getPointeeTypeAsWritten() const { return PointeeType; }
QualType getPointeeType() const {
// FIXME: this might strip inner qualifiers; okay?
const ReferenceType *T = this;
while (T->isInnerRef())
T = T->PointeeType->castAs<ReferenceType>();
return T->PointeeType;
}
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, PointeeType, isSpelledAsLValue());
}
static void Profile(llvm::FoldingSetNodeID &ID,
QualType Referencee,
bool SpelledAsLValue) {
ID.AddPointer(Referencee.getAsOpaquePtr());
ID.AddBoolean(SpelledAsLValue);
}
static bool classof(const Type *T) {
return T->getTypeClass() == LValueReference ||
T->getTypeClass() == RValueReference;
}
};
/// An lvalue reference type, per C++11 [dcl.ref].
class LValueReferenceType : public ReferenceType {
friend class ASTContext; // ASTContext creates these
LValueReferenceType(QualType Referencee, QualType CanonicalRef,
bool SpelledAsLValue)
: ReferenceType(LValueReference, Referencee, CanonicalRef,
SpelledAsLValue) {}
public:
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
static bool classof(const Type *T) {
return T->getTypeClass() == LValueReference;
}
};
/// An rvalue reference type, per C++11 [dcl.ref].
class RValueReferenceType : public ReferenceType {
friend class ASTContext; // ASTContext creates these
RValueReferenceType(QualType Referencee, QualType CanonicalRef)
: ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
public:
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
static bool classof(const Type *T) {
return T->getTypeClass() == RValueReference;
}
};
/// A pointer to member type per C++ 8.3.3 - Pointers to members.
///
/// This includes both pointers to data members and pointer to member functions.
class MemberPointerType : public Type, public llvm::FoldingSetNode {
friend class ASTContext; // ASTContext creates these.
QualType PointeeType;
/// The class of which the pointee is a member. Must ultimately be a
/// RecordType, but could be a typedef or a template parameter too.
const Type *Class;
MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
: Type(MemberPointer, CanonicalPtr,
Cls->isDependentType() || Pointee->isDependentType(),
(Cls->isInstantiationDependentType() ||
Pointee->isInstantiationDependentType()),
Pointee->isVariablyModifiedType(),
(Cls->containsUnexpandedParameterPack() ||
Pointee->containsUnexpandedParameterPack())),
PointeeType(Pointee), Class(Cls) {}
public:
QualType getPointeeType() const { return PointeeType; }
/// Returns true if the member type (i.e. the pointee type) is a
/// function type rather than a data-member type.
bool isMemberFunctionPointer() const {
return PointeeType->isFunctionProtoType();
}
/// Returns true if the member type (i.e. the pointee type) is a
/// data type rather than a function type.
bool isMemberDataPointer() const {
return !PointeeType->isFunctionProtoType();
}
const Type *getClass() const { return Class; }
CXXRecordDecl *getMostRecentCXXRecordDecl() const;
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, getPointeeType(), getClass());
}
static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
const Type *Class) {
ID.AddPointer(Pointee.getAsOpaquePtr());
ID.AddPointer(Class);
}
static bool classof(const Type *T) {
return T->getTypeClass() == MemberPointer;
}
};
/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
class ArrayType : public Type, public llvm::FoldingSetNode {
public:
/// Capture whether this is a normal array (e.g. int X[4])
/// an array with a static size (e.g. int X[static 4]), or an array
/// with a star size (e.g. int X[*]).
/// 'static' is only allowed on function parameters.
enum ArraySizeModifier {
Normal, Static, Star
};
private:
/// The element type of the array.
QualType ElementType;
protected:
friend class ASTContext; // ASTContext creates these.
// C++ [temp.dep.type]p1:
// A type is dependent if it is...
// - an array type constructed from any dependent type or whose
// size is specified by a constant expression that is
// value-dependent,
ArrayType(TypeClass tc, QualType et, QualType can,
ArraySizeModifier sm, unsigned tq,
bool ContainsUnexpandedParameterPack)
: Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
et->isInstantiationDependentType() || tc == DependentSizedArray,
(tc == VariableArray || et->isVariablyModifiedType()),
ContainsUnexpandedParameterPack),
ElementType(et) {
ArrayTypeBits.IndexTypeQuals = tq;
ArrayTypeBits.SizeModifier = sm;
}
public:
QualType getElementType() const { return ElementType; }
ArraySizeModifier getSizeModifier() const {
return ArraySizeModifier(ArrayTypeBits.SizeModifier);
}
Qualifiers getIndexTypeQualifiers() const {
return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
}
unsigned getIndexTypeCVRQualifiers() const {
return ArrayTypeBits.IndexTypeQuals;
}
static bool classof(const Type *T) {
return T->getTypeClass() == ConstantArray ||
T->getTypeClass() == VariableArray ||
T->getTypeClass() == IncompleteArray ||
T->getTypeClass() == DependentSizedArray;
}
};
/// Represents the canonical version of C arrays with a specified constant size.
/// For example, the canonical type for 'int A[4 + 4*100]' is a
/// ConstantArrayType where the element type is 'int' and the size is 404.
class ConstantArrayType : public ArrayType {
llvm::APInt Size; // Allows us to unique the type.
ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
ArraySizeModifier sm, unsigned tq)
: ArrayType(ConstantArray, et, can, sm, tq,
et->containsUnexpandedParameterPack()),
Size(size) {}
protected:
friend class ASTContext; // ASTContext creates these.
ConstantArrayType(TypeClass tc, QualType et, QualType can,
const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
: ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
Size(size) {}
public:
const llvm::APInt &getSize() const { return Size; }
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
/// Determine the number of bits required to address a member of
// an array with the given element type and number of elements.
static unsigned getNumAddressingBits(const ASTContext &Context,
QualType ElementType,
const llvm::APInt &NumElements);
/// Determine the maximum number of active bits that an array's size
/// can require, which limits the maximum size of the array.
static unsigned getMaxSizeBits(const ASTContext &Context);
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, getElementType(), getSize(),
getSizeModifier(), getIndexTypeCVRQualifiers());
}
static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
unsigned TypeQuals) {
ID.AddPointer(ET.getAsOpaquePtr());
ID.AddInteger(ArraySize.getZExtValue());
ID.AddInteger(SizeMod);
ID.AddInteger(TypeQuals);
}
static bool classof(const Type *T) {
return T->getTypeClass() == ConstantArray;
}
};
/// Represents a C array with an unspecified size. For example 'int A[]' has
/// an IncompleteArrayType where the element type is 'int' and the size is
/// unspecified.
class IncompleteArrayType : public ArrayType {
friend class ASTContext; // ASTContext creates these.
IncompleteArrayType(QualType et, QualType can,
ArraySizeModifier sm, unsigned tq)
: ArrayType(IncompleteArray, et, can, sm, tq,
et->containsUnexpandedParameterPack()) {}
public:
friend class StmtIteratorBase;
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
static bool classof(const Type *T) {
return T->getTypeClass() == IncompleteArray;
}
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, getElementType(), getSizeModifier(),
getIndexTypeCVRQualifiers());
}
static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
ArraySizeModifier SizeMod, unsigned TypeQuals) {
ID.AddPointer(ET.getAsOpaquePtr());
ID.AddInteger(SizeMod);
ID.AddInteger(TypeQuals);
}
};
/// Represents a C array with a specified size that is not an
/// integer-constant-expression. For example, 'int s[x+foo()]'.
/// Since the size expression is an arbitrary expression, we store it as such.
///
/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
/// should not be: two lexically equivalent variable array types could mean
/// different things, for example, these variables do not have the same type
/// dynamically:
///
/// void foo(int x) {
/// int Y[x];
/// ++x;
/// int Z[x];
/// }
class VariableArrayType : public ArrayType {
friend class ASTContext; // ASTContext creates these.
/// An assignment-expression. VLA's are only permitted within
/// a function block.
Stmt *SizeExpr;
/// The range spanned by the left and right array brackets.
SourceRange Brackets;
VariableArrayType(QualType et, QualType can, Expr *e,
ArraySizeModifier sm, unsigned tq,
SourceRange brackets)
: ArrayType(VariableArray, et, can, sm, tq,
et->containsUnexpandedParameterPack()),
SizeExpr((Stmt*) e), Brackets(brackets) {}
public:
friend class StmtIteratorBase;
Expr *getSizeExpr() const {
// We use C-style casts instead of cast<> here because we do not wish
// to have a dependency of Type.h on Stmt.h/Expr.h.
return (Expr*) SizeExpr;
}
SourceRange getBracketsRange() const { return Brackets; }
SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
static bool classof(const Type *T) {
return T->getTypeClass() == VariableArray;
}
void Profile(llvm::FoldingSetNodeID &ID) {
llvm_unreachable("Cannot unique VariableArrayTypes.");
}
};
/// Represents an array type in C++ whose size is a value-dependent expression.
///
/// For example:
/// \code
/// template<typename T, int Size>
/// class array {
/// T data[Size];
/// };
/// \endcode
///
/// For these types, we won't actually know what the array bound is
/// until template instantiation occurs, at which point this will
/// become either a ConstantArrayType or a VariableArrayType.
class DependentSizedArrayType : public ArrayType {
friend class ASTContext; // ASTContext creates these.
const ASTContext &Context;
/// An assignment expression that will instantiate to the
/// size of the array.
///
/// The expression itself might be null, in which case the array
/// type will have its size deduced from an initializer.
Stmt *SizeExpr;
/// The range spanned by the left and right array brackets.
SourceRange Brackets;
DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
Expr *e, ArraySizeModifier sm, unsigned tq,
SourceRange brackets);
public:
friend class StmtIteratorBase;
Expr *getSizeExpr() const {
// We use C-style casts instead of cast<> here because we do not wish
// to have a dependency of Type.h on Stmt.h/Expr.h.
return (Expr*) SizeExpr;
}
SourceRange getBracketsRange() const { return Brackets; }
SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
static bool classof(const Type *T) {
return T->getTypeClass() == DependentSizedArray;
}
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, Context, getElementType(),
getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
}
static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
QualType ET, ArraySizeModifier SizeMod,
unsigned TypeQuals, Expr *E);
};
/// Represents an extended address space qualifier where the input address space
/// value is dependent. Non-dependent address spaces are not represented with a
/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
///
/// For example:
/// \code
/// template<typename T, int AddrSpace>
/// class AddressSpace {
/// typedef T __attribute__((address_space(AddrSpace))) type;
/// }
/// \endcode
class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
friend class ASTContext;
const ASTContext &Context;
Expr *AddrSpaceExpr;
QualType PointeeType;
SourceLocation loc;
DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
QualType can, Expr *AddrSpaceExpr,
SourceLocation loc);
public:
Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
QualType getPointeeType() const { return PointeeType; }
SourceLocation getAttributeLoc() const { return loc; }
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
static bool classof(const Type *T) {
return T->getTypeClass() == DependentAddressSpace;
}
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
}
static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
QualType PointeeType, Expr *AddrSpaceExpr);
};
/// Represents an extended vector type where either the type or size is
/// dependent.
///
/// For example:
/// \code
/// template<typename T, int Size>
/// class vector {
/// typedef T __attribute__((ext_vector_type(Size))) type;
/// }
/// \endcode
class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
friend class ASTContext;
const ASTContext &Context;
Expr *SizeExpr;
/// The element type of the array.
QualType ElementType;
SourceLocation loc;
DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
QualType can, Expr *SizeExpr, SourceLocation loc);
public:
Expr *getSizeExpr() const { return SizeExpr; }
QualType getElementType() const { return ElementType; }
SourceLocation getAttributeLoc() const { return loc; }
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
static bool classof(const Type *T) {
return T->getTypeClass() == DependentSizedExtVector;
}
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, Context, getElementType(), getSizeExpr());
}
static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
QualType ElementType, Expr *SizeExpr);
};
/// Represents a GCC generic vector type. This type is created using
/// __attribute__((vector_size(n)), where "n" specifies the vector size in
/// bytes; or from an Altivec __vector or vector declaration.
/// Since the constructor takes the number of vector elements, the
/// client is responsible for converting the size into the number of elements.
class VectorType : public Type, public llvm::FoldingSetNode {
public:
enum VectorKind {
/// not a target-specific vector type
GenericVector,
/// is AltiVec vector
AltiVecVector,
/// is AltiVec 'vector Pixel'
AltiVecPixel,
/// is AltiVec 'vector bool ...'
AltiVecBool,
/// is ARM Neon vector
NeonVector,
/// is ARM Neon polynomial vector
NeonPolyVector
};
protected:
friend class ASTContext; // ASTContext creates these.
/// The element type of the vector.
QualType ElementType;
VectorType(QualType vecType, unsigned nElements, QualType canonType,
VectorKind vecKind);
VectorType(TypeClass tc, QualType vecType, unsigned nElements,
QualType canonType, VectorKind vecKind);
public:
QualType getElementType() const { return ElementType; }
unsigned getNumElements() const { return VectorTypeBits.NumElements; }
static bool isVectorSizeTooLarge(unsigned NumElements) {
return NumElements > VectorTypeBitfields::MaxNumElements;
}
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
VectorKind getVectorKind() const {
return VectorKind(VectorTypeBits.VecKind);
}
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, getElementType(), getNumElements(),
getTypeClass(), getVectorKind());
}
static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
unsigned NumElements, TypeClass TypeClass,
VectorKind VecKind) {
ID.AddPointer(ElementType.getAsOpaquePtr());
ID.AddInteger(NumElements);
ID.AddInteger(TypeClass);
ID.AddInteger(VecKind);
}
static bool classof(const Type *T) {
return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
}
};
/// Represents a vector type where either the type or size is dependent.
////
/// For example:
/// \code
/// template<typename T, int Size>
/// class vector {
/// typedef T __attribute__((vector_size(Size))) type;
/// }
/// \endcode
class DependentVectorType : public Type, public llvm::FoldingSetNode {
friend class ASTContext;
const ASTContext &Context;
QualType ElementType;
Expr *SizeExpr;
SourceLocation Loc;
DependentVectorType(const ASTContext &Context, QualType ElementType,
QualType CanonType, Expr *SizeExpr,
SourceLocation Loc, VectorType::VectorKind vecKind);
public:
Expr *getSizeExpr() const { return SizeExpr; }
QualType getElementType() const { return ElementType; }
SourceLocation getAttributeLoc() const { return Loc; }
VectorType::VectorKind getVectorKind() const {
return VectorType::VectorKind(VectorTypeBits.VecKind);
}
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
static bool classof(const Type *T) {
return T->getTypeClass() == DependentVector;
}
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
}
static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
QualType ElementType, const Expr *SizeExpr,
VectorType::VectorKind VecKind);
};
/// ExtVectorType - Extended vector type. This type is created using
/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
/// class enables syntactic extensions, like Vector Components for accessing
/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
/// Shading Language).
class ExtVectorType : public VectorType {
friend class ASTContext; // ASTContext creates these.
ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
: VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
public:
static int getPointAccessorIdx(char c) {
switch (c) {
default: return -1;
case 'x': case 'r': return 0;
case 'y': case 'g': return 1;
case 'z': case 'b': return 2;
case 'w': case 'a': return 3;
}
}
static int getNumericAccessorIdx(char c) {
switch (c) {
default: return -1;
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'A':
case 'a': return 10;
case 'B':
case 'b': return 11;
case 'C':
case 'c': return 12;
case 'D':
case 'd': return 13;
case 'E':
case 'e': return 14;
case 'F':
case 'f': return 15;
}
}
static int getAccessorIdx(char c, bool isNumericAccessor) {
if (isNumericAccessor)
return getNumericAccessorIdx(c);
else
return getPointAccessorIdx(c);
}
bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
return unsigned(idx-1) < getNumElements();
return false;
}
bool isSugared() const { return false; }
QualType desugar() const { return QualType(this, 0); }
static bool classof(const Type *T) {
return T->getTypeClass() == ExtVector;
}
};
/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
/// class of FunctionNoProtoType and FunctionProtoType.
class FunctionType : public Type {
// The type returned by the function.
QualType ResultType;
public:
/// A class which abstracts out some details necessary for
/// making a call.
///
/// It is not actually used directly for storing this information in
/// a FunctionType, although FunctionType does currently use the
/// same bit-pattern.
///
// If you add a field (say Foo), other than the obvious places (both,
// constructors, compile failures), what you need to update is
// * Operator==
// * getFoo
// * withFoo
// * functionType. Add Foo, getFoo.
// * ASTContext::getFooType
// * ASTContext::mergeFunctionTypes
// * FunctionNoProtoType::Profile
// * FunctionProtoType::Profile
// * TypePrinter::PrintFunctionProto
// * AST read and write
// * Codegen
class ExtInfo {
friend class FunctionType;
// Feel free to rearrange or add bits, but if you go over 12,
// you'll need to adjust both the Bits field below and
// Type::FunctionTypeBitfields.
// | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
// |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
//
// regparm is either 0 (no regparm attribute) or the regparm value+1.
enum { CallConvMask = 0x1F };
enum { NoReturnMask = 0x20 };
enum { ProducesResultMask = 0x40 };
enum { NoCallerSavedRegsMask = 0x80 };
enum { NoCfCheckMask = 0x800 };
enum {
RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
NoCallerSavedRegsMask | NoCfCheckMask),
RegParmOffset = 8
}; // Assumed to be the last field
uint16_t Bits = CC_C;
ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
public:
// Constructor with no defaults. Use this when you know that you
// have all the elements (when reading an AST file for example).
ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
(producesResult ? ProducesResultMask : 0) |
(noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
(hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
(NoCfCheck ? NoCfCheckMask : 0);
}
// Constructor with all defaults. Use when for example creating a
// function known to use defaults.
ExtInfo() = default;
// Constructor with just the calling convention, which is an important part
// of the canonical type.
ExtInfo(CallingConv CC) : Bits(CC) {}
bool getNoReturn() const { return Bits & NoReturnMask; }
bool getProducesResult() const { return Bits & ProducesResultMask; }
bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
unsigned getRegParm() const {
unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
if (RegParm > 0)
--RegParm;
return RegParm;
}
CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
bool operator==(ExtInfo Other) const {
return Bits == Other.Bits;
}
bool operator!=(ExtInfo Other) const {
return Bits != Other.Bits;
}
// Note that we don't have setters. That is by design, use
// the following with methods instead of mutating these objects.
ExtInfo withNoReturn(bool noReturn) const {
if (noReturn)
return ExtInfo(Bits | NoReturnMask);
else
return ExtInfo(Bits & ~NoReturnMask);
}
ExtInfo withProducesResult(bool producesResult) const {
if (producesResult)
return ExtInfo(Bits | ProducesResultMask);
else
return ExtInfo(Bits & ~ProducesResultMask);
}
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
if (noCallerSavedRegs)
return ExtInfo(Bits | NoCallerSavedRegsMask);
else
return ExtInfo(Bits & ~NoCallerSavedRegsMask);
}
ExtInfo withNoCfCheck(bool noCfCheck) const {
if (noCfCheck)
return ExtInfo(Bits | NoCfCheckMask);
else
return ExtInfo(Bits & ~NoCfCheckMask);
}
ExtInfo withRegParm(unsigned RegParm) const {
assert(RegParm < 7 && "Invalid regparm value");
return ExtInfo((Bits & ~RegParmMask) |
((RegParm + 1) << RegParmOffset));
}
ExtInfo withCallingConv(CallingConv cc) const {
return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
}
void Profile(llvm::FoldingSetNodeID &ID) const {
ID.AddInteger(Bits);
}
};
protected:
FunctionType(TypeClass tc, QualType res,
QualType Canonical, bool Dependent,
bool InstantiationDependent,
bool VariablyModified, bool ContainsUnexpandedParameterPack,
ExtInfo Info)
: Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
ContainsUnexpandedParameterPack),
ResultType(res) {
FunctionTypeBits.ExtInfo = Info.Bits;
}
unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
public:
QualType getReturnType() const { return ResultType; }
bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
/// Determine whether this function type includes the GNU noreturn
/// attribute. The C++11 [[noreturn]] attribute does not affect the function
/// type.
bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
CallingConv getCallConv() const { return getExtInfo().getCC(); }
ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
/// Determine the type of an expression that calls a function of
/// this type.
QualType getCallResultType(const ASTContext &Context) const {
return getReturnType().getNonLValueExprType(Context);
}
static StringRef getNameForCallConv(CallingConv CC);
static bool classof(const Type *T) {
return T->getTypeClass() == FunctionNoProto ||
T->getTypeClass() == FunctionProto;
}
};
<