1 //===--- ASTContext.h - Context to hold long-lived AST nodes ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Defines the clang::ASTContext interface.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_AST_ASTCONTEXT_H
16 #define LLVM_CLANG_AST_ASTCONTEXT_H
18 #include "clang/AST/ASTTypeTraits.h"
19 #include "clang/AST/CanonicalType.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclarationName.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/ExternalASTSource.h"
25 #include "clang/AST/NestedNameSpecifier.h"
26 #include "clang/AST/PrettyPrinter.h"
27 #include "clang/AST/RawCommentList.h"
28 #include "clang/AST/TemplateBase.h"
29 #include "clang/AST/TemplateName.h"
30 #include "clang/AST/Type.h"
31 #include "clang/Basic/AddressSpaces.h"
32 #include "clang/Basic/IdentifierTable.h"
33 #include "clang/Basic/LangOptions.h"
34 #include "clang/Basic/Linkage.h"
35 #include "clang/Basic/LLVM.h"
36 #include "clang/Basic/Module.h"
37 #include "clang/Basic/OperatorKinds.h"
38 #include "clang/Basic/PartialDiagnostic.h"
39 #include "clang/Basic/SanitizerBlacklist.h"
40 #include "clang/Basic/SourceLocation.h"
41 #include "clang/Basic/Specifiers.h"
42 #include "clang/Basic/XRayLists.h"
43 #include "llvm/ADT/APSInt.h"
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/FoldingSet.h"
47 #include "llvm/ADT/IntrusiveRefCntPtr.h"
48 #include "llvm/ADT/iterator_range.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/None.h"
51 #include "llvm/ADT/Optional.h"
52 #include "llvm/ADT/PointerIntPair.h"
53 #include "llvm/ADT/PointerUnion.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/TinyPtrVector.h"
57 #include "llvm/ADT/StringMap.h"
58 #include "llvm/ADT/StringRef.h"
59 #include "llvm/Support/AlignOf.h"
60 #include "llvm/Support/Allocator.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/Compiler.h"
70 #include <type_traits>
78 } // end namespace llvm
82 class ASTMutationListener;
83 class ASTRecordLayout;
88 class DiagnosticsEngine;
90 class MangleNumberingContext;
91 class MaterializeTemporaryExpr;
96 class ObjCPropertyDecl;
97 class UnresolvedSetIterator;
99 class UsingShadowDecl;
100 class VTableContextBase;
106 } // end namespace Builtin
108 enum BuiltinTemplateKind : int;
114 } // end namespace comments
119 bool AlignIsRequired : 1;
121 TypeInfo() : Width(0), Align(0), AlignIsRequired(false) {}
122 TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
123 : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
126 /// \brief Holds long-lived AST nodes (such as types and decls) that can be
127 /// referred to throughout the semantic analysis of a file.
128 class ASTContext : public RefCountedBase<ASTContext> {
129 ASTContext &this_() { return *this; }
131 mutable SmallVector<Type *, 0> Types;
132 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
133 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
134 mutable llvm::FoldingSet<PointerType> PointerTypes;
135 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
136 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
137 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
138 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
139 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
140 mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
141 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
142 mutable std::vector<VariableArrayType*> VariableArrayTypes;
143 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
144 mutable llvm::FoldingSet<DependentSizedExtVectorType>
145 DependentSizedExtVectorTypes;
146 mutable llvm::FoldingSet<VectorType> VectorTypes;
147 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
148 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
150 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
151 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
152 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
153 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
154 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
155 SubstTemplateTypeParmTypes;
156 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
157 SubstTemplateTypeParmPackTypes;
158 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
159 TemplateSpecializationTypes;
160 mutable llvm::FoldingSet<ParenType> ParenTypes;
161 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
162 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
163 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
165 DependentTemplateSpecializationTypes;
166 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
167 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
168 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
169 mutable llvm::FoldingSet<DependentUnaryTransformType>
170 DependentUnaryTransformTypes;
171 mutable llvm::FoldingSet<AutoType> AutoTypes;
172 mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
173 DeducedTemplateSpecializationTypes;
174 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
175 llvm::FoldingSet<AttributedType> AttributedTypes;
176 mutable llvm::FoldingSet<PipeType> PipeTypes;
178 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
179 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
180 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
181 SubstTemplateTemplateParms;
182 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
184 SubstTemplateTemplateParmPacks;
186 /// \brief The set of nested name specifiers.
188 /// This set is managed by the NestedNameSpecifier class.
189 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
190 mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
191 friend class NestedNameSpecifier;
193 /// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
195 /// This is lazily created. This is intentionally not serialized.
196 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
198 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
201 /// \brief A cache from types to size and alignment information.
202 typedef llvm::DenseMap<const Type *, struct TypeInfo> TypeInfoMap;
203 mutable TypeInfoMap MemoizedTypeInfo;
205 /// \brief A cache mapping from CXXRecordDecls to key functions.
206 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
208 /// \brief Mapping from ObjCContainers to their ObjCImplementations.
209 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
211 /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
213 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
215 /// \brief Mapping from __block VarDecls to their copy initialization expr.
216 llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
218 /// \brief Mapping from class scope functions specialization to their
219 /// template patterns.
220 llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
221 ClassScopeSpecializationPattern;
223 /// \brief Mapping from materialized temporaries with static storage duration
224 /// that appear in constant initializers to their evaluated values. These are
225 /// allocated in a std::map because their address must be stable.
226 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue *>
227 MaterializedTemporaryValues;
229 /// \brief Representation of a "canonical" template template parameter that
230 /// is used in canonical template names.
231 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
232 TemplateTemplateParmDecl *Parm;
235 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
238 TemplateTemplateParmDecl *getParam() const { return Parm; }
240 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
242 static void Profile(llvm::FoldingSetNodeID &ID,
243 TemplateTemplateParmDecl *Parm);
245 mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
246 CanonTemplateTemplateParms;
248 TemplateTemplateParmDecl *
249 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
251 /// \brief The typedef for the __int128_t type.
252 mutable TypedefDecl *Int128Decl;
254 /// \brief The typedef for the __uint128_t type.
255 mutable TypedefDecl *UInt128Decl;
257 /// \brief The typedef for the target specific predefined
258 /// __builtin_va_list type.
259 mutable TypedefDecl *BuiltinVaListDecl;
261 /// The typedef for the predefined \c __builtin_ms_va_list type.
262 mutable TypedefDecl *BuiltinMSVaListDecl;
264 /// \brief The typedef for the predefined \c id type.
265 mutable TypedefDecl *ObjCIdDecl;
267 /// \brief The typedef for the predefined \c SEL type.
268 mutable TypedefDecl *ObjCSelDecl;
270 /// \brief The typedef for the predefined \c Class type.
271 mutable TypedefDecl *ObjCClassDecl;
273 /// \brief The typedef for the predefined \c Protocol class in Objective-C.
274 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
276 /// \brief The typedef for the predefined 'BOOL' type.
277 mutable TypedefDecl *BOOLDecl;
279 // Typedefs which may be provided defining the structure of Objective-C
281 QualType ObjCIdRedefinitionType;
282 QualType ObjCClassRedefinitionType;
283 QualType ObjCSelRedefinitionType;
285 /// The identifier 'bool'.
286 mutable IdentifierInfo *BoolName = nullptr;
288 /// The identifier 'NSObject'.
289 IdentifierInfo *NSObjectName = nullptr;
291 /// The identifier 'NSCopying'.
292 IdentifierInfo *NSCopyingName = nullptr;
294 /// The identifier '__make_integer_seq'.
295 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
297 /// The identifier '__type_pack_element'.
298 mutable IdentifierInfo *TypePackElementName = nullptr;
300 QualType ObjCConstantStringType;
301 mutable RecordDecl *CFConstantStringTagDecl;
302 mutable TypedefDecl *CFConstantStringTypeDecl;
304 mutable QualType ObjCSuperType;
306 QualType ObjCNSStringType;
308 /// \brief The typedef declaration for the Objective-C "instancetype" type.
309 TypedefDecl *ObjCInstanceTypeDecl;
311 /// \brief The type for the C FILE type.
314 /// \brief The type for the C jmp_buf type.
315 TypeDecl *jmp_bufDecl;
317 /// \brief The type for the C sigjmp_buf type.
318 TypeDecl *sigjmp_bufDecl;
320 /// \brief The type for the C ucontext_t type.
321 TypeDecl *ucontext_tDecl;
323 /// \brief Type for the Block descriptor for Blocks CodeGen.
325 /// Since this is only used for generation of debug info, it is not
327 mutable RecordDecl *BlockDescriptorType;
329 /// \brief Type for the Block descriptor for Blocks CodeGen.
331 /// Since this is only used for generation of debug info, it is not
333 mutable RecordDecl *BlockDescriptorExtendedType;
335 /// \brief Declaration for the CUDA cudaConfigureCall function.
336 FunctionDecl *cudaConfigureCallDecl;
338 /// \brief Keeps track of all declaration attributes.
340 /// Since so few decls have attrs, we keep them in a hash map instead of
341 /// wasting space in the Decl class.
342 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
344 /// \brief A mapping from non-redeclarable declarations in modules that were
345 /// merged with other declarations to the canonical declaration that they were
347 llvm::DenseMap<Decl*, Decl*> MergedDecls;
349 /// \brief A mapping from a defining declaration to a list of modules (other
350 /// than the owning module of the declaration) that contain merged
351 /// definitions of that entity.
352 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
354 /// \brief Initializers for a module, in order. Each Decl will be either
355 /// something that has a semantic effect on startup (such as a variable with
356 /// a non-constant initializer), or an ImportDecl (which recursively triggers
357 /// initialization of another module).
358 struct PerModuleInitializers {
359 llvm::SmallVector<Decl*, 4> Initializers;
360 llvm::SmallVector<uint32_t, 4> LazyInitializers;
362 void resolve(ASTContext &Ctx);
364 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
367 /// \brief A type synonym for the TemplateOrInstantiation mapping.
368 typedef llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>
369 TemplateOrSpecializationInfo;
372 /// \brief A mapping to contain the template or declaration that
373 /// a variable declaration describes or was instantiated from,
376 /// For non-templates, this value will be NULL. For variable
377 /// declarations that describe a variable template, this will be a
378 /// pointer to a VarTemplateDecl. For static data members
379 /// of class template specializations, this will be the
380 /// MemberSpecializationInfo referring to the member variable that was
381 /// instantiated or specialized. Thus, the mapping will keep track of
382 /// the static data member templates from which static data members of
383 /// class template specializations were instantiated.
385 /// Given the following example:
388 /// template<typename T>
393 /// template<typename T>
394 /// T X<T>::value = T(17);
396 /// int *x = &X<int>::value;
399 /// This mapping will contain an entry that maps from the VarDecl for
400 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
401 /// class template X) and will be marked TSK_ImplicitInstantiation.
402 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
403 TemplateOrInstantiation;
405 /// \brief Keeps track of the declaration from which a using declaration was
406 /// created during instantiation.
408 /// The source and target declarations are always a UsingDecl, an
409 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
413 /// template<typename T>
418 /// template<typename T>
419 /// struct B : A<T> {
423 /// template struct B<int>;
426 /// This mapping will contain an entry that maps from the UsingDecl in
427 /// B<int> to the UnresolvedUsingDecl in B<T>.
428 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
430 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
431 InstantiatedFromUsingShadowDecl;
433 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
435 /// \brief Mapping that stores the methods overridden by a given C++
438 /// Since most C++ member functions aren't virtual and therefore
439 /// don't override anything, we store the overridden functions in
440 /// this map on the side rather than within the CXXMethodDecl structure.
441 typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
442 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
444 /// \brief Mapping from each declaration context to its corresponding
445 /// mangling numbering context (used for constructs like lambdas which
446 /// need to be consistently numbered for the mangler).
447 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
448 MangleNumberingContexts;
450 /// \brief Side-table of mangling numbers for declarations which rarely
451 /// need them (like static local vars).
452 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
453 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
455 /// \brief Mapping that stores parameterIndex values for ParmVarDecls when
456 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
457 typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
458 ParameterIndexTable ParamIndices;
460 ImportDecl *FirstLocalImport;
461 ImportDecl *LastLocalImport;
463 TranslationUnitDecl *TUDecl;
464 mutable ExternCContextDecl *ExternCContext;
465 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl;
466 mutable BuiltinTemplateDecl *TypePackElementDecl;
468 /// \brief The associated SourceManager object.a
469 SourceManager &SourceMgr;
471 /// \brief The language options used to create the AST associated with
472 /// this ASTContext object.
473 LangOptions &LangOpts;
475 /// \brief Blacklist object that is used by sanitizers to decide which
476 /// entities should not be instrumented.
477 std::unique_ptr<SanitizerBlacklist> SanitizerBL;
479 /// \brief Function filtering mechanism to determine whether a given function
480 /// should be imbued with the XRay "always" or "never" attributes.
481 std::unique_ptr<XRayFunctionFilter> XRayFilter;
483 /// \brief The allocator used to create AST objects.
485 /// AST objects are never destructed; rather, all memory associated with the
486 /// AST objects will be released when the ASTContext itself is destroyed.
487 mutable llvm::BumpPtrAllocator BumpAlloc;
489 /// \brief Allocator for partial diagnostics.
490 PartialDiagnostic::StorageAllocator DiagAllocator;
492 /// \brief The current C++ ABI.
493 std::unique_ptr<CXXABI> ABI;
494 CXXABI *createCXXABI(const TargetInfo &T);
496 /// \brief The logical -> physical address space map.
497 const LangAS::Map *AddrSpaceMap;
499 /// \brief Address space map mangling must be used with language specific
500 /// address spaces (e.g. OpenCL/CUDA)
501 bool AddrSpaceMapMangling;
503 friend class ASTDeclReader;
504 friend class ASTReader;
505 friend class ASTWriter;
506 friend class CXXRecordDecl;
508 const TargetInfo *Target;
509 const TargetInfo *AuxTarget;
510 clang::PrintingPolicy PrintingPolicy;
513 IdentifierTable &Idents;
514 SelectorTable &Selectors;
515 Builtin::Context &BuiltinInfo;
516 mutable DeclarationNameTable DeclarationNames;
517 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
518 ASTMutationListener *Listener;
520 /// \brief Contains parents of a node.
521 typedef llvm::SmallVector<ast_type_traits::DynTypedNode, 2> ParentVector;
523 /// \brief Maps from a node to its parents. This is used for nodes that have
524 /// pointer identity only, which are more common and we can save space by
525 /// only storing a unique pointer to them.
526 typedef llvm::DenseMap<const void *,
527 llvm::PointerUnion4<const Decl *, const Stmt *,
528 ast_type_traits::DynTypedNode *,
529 ParentVector *>> ParentMapPointers;
531 /// Parent map for nodes without pointer identity. We store a full
532 /// DynTypedNode for all keys.
533 typedef llvm::DenseMap<
534 ast_type_traits::DynTypedNode,
535 llvm::PointerUnion4<const Decl *, const Stmt *,
536 ast_type_traits::DynTypedNode *, ParentVector *>>
539 /// Container for either a single DynTypedNode or for an ArrayRef to
540 /// DynTypedNode. For use with ParentMap.
541 class DynTypedNodeList {
542 typedef ast_type_traits::DynTypedNode DynTypedNode;
543 llvm::AlignedCharArrayUnion<ast_type_traits::DynTypedNode,
544 ArrayRef<DynTypedNode>> Storage;
548 DynTypedNodeList(const DynTypedNode &N) : IsSingleNode(true) {
549 new (Storage.buffer) DynTypedNode(N);
551 DynTypedNodeList(ArrayRef<DynTypedNode> A) : IsSingleNode(false) {
552 new (Storage.buffer) ArrayRef<DynTypedNode>(A);
555 const ast_type_traits::DynTypedNode *begin() const {
557 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
559 return reinterpret_cast<const DynTypedNode *>(Storage.buffer);
562 const ast_type_traits::DynTypedNode *end() const {
564 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
566 return reinterpret_cast<const DynTypedNode *>(Storage.buffer) + 1;
569 size_t size() const { return end() - begin(); }
570 bool empty() const { return begin() == end(); }
572 const DynTypedNode &operator[](size_t N) const {
573 assert(N < size() && "Out of bounds!");
574 return *(begin() + N);
578 /// \brief Returns the parents of the given node.
580 /// Note that this will lazily compute the parents of all nodes
581 /// and store them for later retrieval. Thus, the first call is O(n)
582 /// in the number of AST nodes.
584 /// Caveats and FIXMEs:
585 /// Calculating the parent map over all AST nodes will need to load the
586 /// full AST. This can be undesirable in the case where the full AST is
587 /// expensive to create (for example, when using precompiled header
588 /// preambles). Thus, there are good opportunities for optimization here.
589 /// One idea is to walk the given node downwards, looking for references
590 /// to declaration contexts - once a declaration context is found, compute
591 /// the parent map for the declaration context; if that can satisfy the
592 /// request, loading the whole AST can be avoided. Note that this is made
593 /// more complex by statements in templates having multiple parents - those
594 /// problems can be solved by building closure over the templated parts of
595 /// the AST, which also avoids touching large parts of the AST.
596 /// Additionally, we will want to add an interface to already give a hint
597 /// where to search for the parents, for example when looking at a statement
598 /// inside a certain function.
600 /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
601 /// NestedNameSpecifier or NestedNameSpecifierLoc.
602 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node) {
603 return getParents(ast_type_traits::DynTypedNode::create(Node));
606 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node);
608 const clang::PrintingPolicy &getPrintingPolicy() const {
609 return PrintingPolicy;
612 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
613 PrintingPolicy = Policy;
616 SourceManager& getSourceManager() { return SourceMgr; }
617 const SourceManager& getSourceManager() const { return SourceMgr; }
619 llvm::BumpPtrAllocator &getAllocator() const {
623 void *Allocate(size_t Size, unsigned Align = 8) const {
624 return BumpAlloc.Allocate(Size, Align);
626 template <typename T> T *Allocate(size_t Num = 1) const {
627 return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
629 void Deallocate(void *Ptr) const { }
631 /// Return the total amount of physical memory allocated for representing
632 /// AST nodes and type information.
633 size_t getASTAllocatedMemory() const {
634 return BumpAlloc.getTotalMemory();
636 /// Return the total memory used for various side tables.
637 size_t getSideTableAllocatedMemory() const;
639 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
640 return DiagAllocator;
643 const TargetInfo &getTargetInfo() const { return *Target; }
644 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
646 /// getIntTypeForBitwidth -
647 /// sets integer QualTy according to specified details:
648 /// bitwidth, signed/unsigned.
649 /// Returns empty type if there is no appropriate target types.
650 QualType getIntTypeForBitwidth(unsigned DestWidth,
651 unsigned Signed) const;
652 /// getRealTypeForBitwidth -
653 /// sets floating point QualTy according to specified bitwidth.
654 /// Returns empty type if there is no appropriate target types.
655 QualType getRealTypeForBitwidth(unsigned DestWidth) const;
657 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
659 const LangOptions& getLangOpts() const { return LangOpts; }
661 const SanitizerBlacklist &getSanitizerBlacklist() const {
665 const XRayFunctionFilter &getXRayFilter() const {
669 DiagnosticsEngine &getDiagnostics() const;
671 FullSourceLoc getFullLoc(SourceLocation Loc) const {
672 return FullSourceLoc(Loc,SourceMgr);
675 /// \brief All comments in this translation unit.
676 RawCommentList Comments;
678 /// \brief True if comments are already loaded from ExternalASTSource.
679 mutable bool CommentsLoaded;
681 class RawCommentAndCacheFlags {
684 /// We searched for a comment attached to the particular declaration, but
690 /// We have found a comment attached to this particular declaration.
695 /// This declaration does not have an attached comment, and we have
696 /// searched the redeclaration chain.
698 /// If getRaw() == 0, the whole redeclaration chain does not have any
701 /// If getRaw() != 0, it is a comment propagated from other
706 Kind getKind() const LLVM_READONLY {
707 return Data.getInt();
710 void setKind(Kind K) {
714 const RawComment *getRaw() const LLVM_READONLY {
715 return Data.getPointer();
718 void setRaw(const RawComment *RC) {
722 const Decl *getOriginalDecl() const LLVM_READONLY {
726 void setOriginalDecl(const Decl *Orig) {
731 llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
732 const Decl *OriginalDecl;
735 /// \brief Mapping from declarations to comments attached to any
738 /// Raw comments are owned by Comments list. This mapping is populated
740 mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
742 /// \brief Mapping from declarations to parsed comments attached to any
744 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
746 /// \brief Return the documentation comment attached to a given declaration,
747 /// without looking into cache.
748 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
751 RawCommentList &getRawCommentList() {
755 void addComment(const RawComment &RC) {
756 assert(LangOpts.RetainCommentsFromSystemHeaders ||
757 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
758 Comments.addComment(RC, BumpAlloc);
761 /// \brief Return the documentation comment attached to a given declaration.
762 /// Returns NULL if no comment is attached.
764 /// \param OriginalDecl if not NULL, is set to declaration AST node that had
765 /// the comment, if the comment we found comes from a redeclaration.
767 getRawCommentForAnyRedecl(const Decl *D,
768 const Decl **OriginalDecl = nullptr) const;
770 /// Return parsed documentation comment attached to a given declaration.
771 /// Returns NULL if no comment is attached.
773 /// \param PP the Preprocessor used with this TU. Could be NULL if
774 /// preprocessor is not available.
775 comments::FullComment *getCommentForDecl(const Decl *D,
776 const Preprocessor *PP) const;
778 /// Return parsed documentation comment attached to a given declaration.
779 /// Returns NULL if no comment is attached. Does not look at any
780 /// redeclarations of the declaration.
781 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
783 comments::FullComment *cloneFullComment(comments::FullComment *FC,
784 const Decl *D) const;
787 mutable comments::CommandTraits CommentCommandTraits;
789 /// \brief Iterator that visits import declarations.
790 class import_iterator {
794 typedef ImportDecl *value_type;
795 typedef ImportDecl *reference;
796 typedef ImportDecl *pointer;
797 typedef int difference_type;
798 typedef std::forward_iterator_tag iterator_category;
800 import_iterator() : Import() {}
801 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
803 reference operator*() const { return Import; }
804 pointer operator->() const { return Import; }
806 import_iterator &operator++() {
807 Import = ASTContext::getNextLocalImport(Import);
811 import_iterator operator++(int) {
812 import_iterator Other(*this);
817 friend bool operator==(import_iterator X, import_iterator Y) {
818 return X.Import == Y.Import;
821 friend bool operator!=(import_iterator X, import_iterator Y) {
822 return X.Import != Y.Import;
827 comments::CommandTraits &getCommentCommandTraits() const {
828 return CommentCommandTraits;
831 /// \brief Retrieve the attributes for the given declaration.
832 AttrVec& getDeclAttrs(const Decl *D);
834 /// \brief Erase the attributes corresponding to the given declaration.
835 void eraseDeclAttrs(const Decl *D);
837 /// \brief If this variable is an instantiated static data member of a
838 /// class template specialization, returns the templated static data member
839 /// from which it was instantiated.
841 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
844 TemplateOrSpecializationInfo
845 getTemplateOrSpecializationInfo(const VarDecl *Var);
847 FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
849 void setClassScopeSpecializationPattern(FunctionDecl *FD,
850 FunctionDecl *Pattern);
852 /// \brief Note that the static data member \p Inst is an instantiation of
853 /// the static data member template \p Tmpl of a class template.
854 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
855 TemplateSpecializationKind TSK,
856 SourceLocation PointOfInstantiation = SourceLocation());
858 void setTemplateOrSpecializationInfo(VarDecl *Inst,
859 TemplateOrSpecializationInfo TSI);
861 /// \brief If the given using decl \p Inst is an instantiation of a
862 /// (possibly unresolved) using decl from a template instantiation,
864 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
866 /// \brief Remember that the using decl \p Inst is an instantiation
867 /// of the using decl \p Pattern of a class template.
868 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
870 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
871 UsingShadowDecl *Pattern);
872 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
874 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
876 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
878 // Access to the set of methods overridden by the given C++ method.
879 typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
880 overridden_cxx_method_iterator
881 overridden_methods_begin(const CXXMethodDecl *Method) const;
883 overridden_cxx_method_iterator
884 overridden_methods_end(const CXXMethodDecl *Method) const;
886 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
887 typedef llvm::iterator_range<overridden_cxx_method_iterator>
888 overridden_method_range;
889 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
891 /// \brief Note that the given C++ \p Method overrides the given \p
892 /// Overridden method.
893 void addOverriddenMethod(const CXXMethodDecl *Method,
894 const CXXMethodDecl *Overridden);
896 /// \brief Return C++ or ObjC overridden methods for the given \p Method.
898 /// An ObjC method is considered to override any method in the class's
899 /// base classes, its protocols, or its categories' protocols, that has
900 /// the same selector and is of the same kind (class or instance).
901 /// A method in an implementation is not considered as overriding the same
902 /// method in the interface or its categories.
903 void getOverriddenMethods(
904 const NamedDecl *Method,
905 SmallVectorImpl<const NamedDecl *> &Overridden) const;
907 /// \brief Notify the AST context that a new import declaration has been
908 /// parsed or implicitly created within this translation unit.
909 void addedLocalImportDecl(ImportDecl *Import);
911 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
912 return Import->NextLocalImport;
915 typedef llvm::iterator_range<import_iterator> import_range;
916 import_range local_imports() const {
917 return import_range(import_iterator(FirstLocalImport), import_iterator());
920 Decl *getPrimaryMergedDecl(Decl *D) {
921 Decl *Result = MergedDecls.lookup(D);
922 return Result ? Result : D;
924 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
925 MergedDecls[D] = Primary;
928 /// \brief Note that the definition \p ND has been merged into module \p M,
929 /// and should be visible whenever \p M is visible.
930 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
931 bool NotifyListeners = true);
932 /// \brief Clean up the merged definition list. Call this if you might have
933 /// added duplicates into the list.
934 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
936 /// \brief Get the additional modules in which the definition \p Def has
938 ArrayRef<Module*> getModulesWithMergedDefinition(NamedDecl *Def) {
939 auto MergedIt = MergedDefModules.find(Def);
940 if (MergedIt == MergedDefModules.end())
942 return MergedIt->second;
945 /// Add a declaration to the list of declarations that are initialized
946 /// for a module. This will typically be a global variable (with internal
947 /// linkage) that runs module initializers, such as the iostream initializer,
948 /// or an ImportDecl nominating another module that has initializers.
949 void addModuleInitializer(Module *M, Decl *Init);
951 void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs);
953 /// Get the initializations to perform when importing a module, if any.
954 ArrayRef<Decl*> getModuleInitializers(Module *M);
956 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
958 ExternCContextDecl *getExternCContextDecl() const;
959 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
960 BuiltinTemplateDecl *getTypePackElementDecl() const;
966 CanQualType WCharTy; // [C++ 3.9.1p5].
967 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
968 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
969 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
970 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
971 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
972 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
973 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
974 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty;
975 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
976 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
977 CanQualType Float128ComplexTy;
978 CanQualType VoidPtrTy, NullPtrTy;
979 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
980 CanQualType BuiltinFnTy;
981 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
982 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
983 CanQualType ObjCBuiltinBoolTy;
984 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
985 CanQualType SingletonId;
986 #include "clang/Basic/OpenCLImageTypes.def"
987 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
988 CanQualType OCLQueueTy, OCLReserveIDTy;
989 CanQualType OMPArraySectionTy;
991 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
992 mutable QualType AutoDeductTy; // Deduction against 'auto'.
993 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
995 // Decl used to help define __builtin_va_list for some targets.
996 // The decl is built when constructing 'BuiltinVaListDecl'.
997 mutable Decl *VaListTagDecl;
999 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1000 SelectorTable &sels, Builtin::Context &builtins);
1001 ASTContext(const ASTContext &) = delete;
1002 ASTContext &operator=(const ASTContext &) = delete;
1005 /// \brief Attach an external AST source to the AST context.
1007 /// The external AST source provides the ability to load parts of
1008 /// the abstract syntax tree as needed from some external storage,
1009 /// e.g., a precompiled header.
1010 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1012 /// \brief Retrieve a pointer to the external AST source associated
1013 /// with this AST context, if any.
1014 ExternalASTSource *getExternalSource() const {
1015 return ExternalSource.get();
1018 /// \brief Attach an AST mutation listener to the AST context.
1020 /// The AST mutation listener provides the ability to track modifications to
1021 /// the abstract syntax tree entities committed after they were initially
1023 void setASTMutationListener(ASTMutationListener *Listener) {
1024 this->Listener = Listener;
1027 /// \brief Retrieve a pointer to the AST mutation listener associated
1028 /// with this AST context, if any.
1029 ASTMutationListener *getASTMutationListener() const { return Listener; }
1031 void PrintStats() const;
1032 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1034 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1035 const IdentifierInfo *II) const;
1037 /// \brief Create a new implicit TU-level CXXRecordDecl or RecordDecl
1039 RecordDecl *buildImplicitRecord(StringRef Name,
1040 RecordDecl::TagKind TK = TTK_Struct) const;
1042 /// \brief Create a new implicit TU-level typedef declaration.
1043 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1045 /// \brief Retrieve the declaration for the 128-bit signed integer type.
1046 TypedefDecl *getInt128Decl() const;
1048 /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
1049 TypedefDecl *getUInt128Decl() const;
1051 //===--------------------------------------------------------------------===//
1052 // Type Constructors
1053 //===--------------------------------------------------------------------===//
1056 /// \brief Return a type with extended qualifiers.
1057 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1059 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1061 QualType getPipeType(QualType T, bool ReadOnly) const;
1064 /// \brief Return the uniqued reference to the type for an address space
1065 /// qualified type with the specified type and address space.
1067 /// The resulting type has a union of the qualifiers from T and the address
1068 /// space. If T already has an address space specifier, it is silently
1070 QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
1072 /// \brief Apply Objective-C protocol qualifiers to the given type.
1073 /// \param allowOnPointerType specifies if we can apply protocol
1074 /// qualifiers on ObjCObjectPointerType. It can be set to true when
1075 /// contructing the canonical type of a Objective-C type parameter.
1076 QualType applyObjCProtocolQualifiers(QualType type,
1077 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1078 bool allowOnPointerType = false) const;
1080 /// \brief Return the uniqued reference to the type for an Objective-C
1081 /// gc-qualified type.
1083 /// The retulting type has a union of the qualifiers from T and the gc
1085 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1087 /// \brief Return the uniqued reference to the type for a \c restrict
1090 /// The resulting type has a union of the qualifiers from \p T and
1092 QualType getRestrictType(QualType T) const {
1093 return T.withFastQualifiers(Qualifiers::Restrict);
1096 /// \brief Return the uniqued reference to the type for a \c volatile
1099 /// The resulting type has a union of the qualifiers from \p T and
1101 QualType getVolatileType(QualType T) const {
1102 return T.withFastQualifiers(Qualifiers::Volatile);
1105 /// \brief Return the uniqued reference to the type for a \c const
1108 /// The resulting type has a union of the qualifiers from \p T and \c const.
1110 /// It can be reasonably expected that this will always be equivalent to
1111 /// calling T.withConst().
1112 QualType getConstType(QualType T) const { return T.withConst(); }
1114 /// \brief Change the ExtInfo on a function type.
1115 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1116 FunctionType::ExtInfo EInfo);
1118 /// Adjust the given function result type.
1119 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1121 /// \brief Change the result type of a function type once it is deduced.
1122 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1124 /// \brief Determine whether two function types are the same, ignoring
1125 /// exception specifications in cases where they're part of the type.
1126 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U);
1128 /// \brief Change the exception specification on a function once it is
1129 /// delay-parsed, instantiated, or computed.
1130 void adjustExceptionSpec(FunctionDecl *FD,
1131 const FunctionProtoType::ExceptionSpecInfo &ESI,
1132 bool AsWritten = false);
1134 /// \brief Return the uniqued reference to the type for a complex
1135 /// number with the specified element type.
1136 QualType getComplexType(QualType T) const;
1137 CanQualType getComplexType(CanQualType T) const {
1138 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1141 /// \brief Return the uniqued reference to the type for a pointer to
1142 /// the specified type.
1143 QualType getPointerType(QualType T) const;
1144 CanQualType getPointerType(CanQualType T) const {
1145 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1148 /// \brief Return the uniqued reference to a type adjusted from the original
1149 /// type to a new type.
1150 QualType getAdjustedType(QualType Orig, QualType New) const;
1151 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1152 return CanQualType::CreateUnsafe(
1153 getAdjustedType((QualType)Orig, (QualType)New));
1156 /// \brief Return the uniqued reference to the decayed version of the given
1157 /// type. Can only be called on array and function types which decay to
1159 QualType getDecayedType(QualType T) const;
1160 CanQualType getDecayedType(CanQualType T) const {
1161 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1164 /// \brief Return the uniqued reference to the atomic type for the specified
1166 QualType getAtomicType(QualType T) const;
1168 /// \brief Return the uniqued reference to the type for a block of the
1170 QualType getBlockPointerType(QualType T) const;
1172 /// Gets the struct used to keep track of the descriptor for pointer to
1174 QualType getBlockDescriptorType() const;
1176 /// \brief Return a read_only pipe type for the specified type.
1177 QualType getReadPipeType(QualType T) const;
1178 /// \brief Return a write_only pipe type for the specified type.
1179 QualType getWritePipeType(QualType T) const;
1181 /// Gets the struct used to keep track of the extended descriptor for
1182 /// pointer to blocks.
1183 QualType getBlockDescriptorExtendedType() const;
1185 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1186 cudaConfigureCallDecl = FD;
1188 FunctionDecl *getcudaConfigureCallDecl() {
1189 return cudaConfigureCallDecl;
1192 /// Returns true iff we need copy/dispose helpers for the given type.
1193 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1196 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set
1197 /// to false in this case. If HasByrefExtendedLayout returns true, byref variable
1198 /// has extended lifetime.
1199 bool getByrefLifetime(QualType Ty,
1200 Qualifiers::ObjCLifetime &Lifetime,
1201 bool &HasByrefExtendedLayout) const;
1203 /// \brief Return the uniqued reference to the type for an lvalue reference
1204 /// to the specified type.
1205 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1208 /// \brief Return the uniqued reference to the type for an rvalue reference
1209 /// to the specified type.
1210 QualType getRValueReferenceType(QualType T) const;
1212 /// \brief Return the uniqued reference to the type for a member pointer to
1213 /// the specified type in the specified class.
1215 /// The class \p Cls is a \c Type because it could be a dependent name.
1216 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1218 /// \brief Return a non-unique reference to the type for a variable array of
1219 /// the specified element type.
1220 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1221 ArrayType::ArraySizeModifier ASM,
1222 unsigned IndexTypeQuals,
1223 SourceRange Brackets) const;
1225 /// \brief Return a non-unique reference to the type for a dependently-sized
1226 /// array of the specified element type.
1228 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1230 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1231 ArrayType::ArraySizeModifier ASM,
1232 unsigned IndexTypeQuals,
1233 SourceRange Brackets) const;
1235 /// \brief Return a unique reference to the type for an incomplete array of
1236 /// the specified element type.
1237 QualType getIncompleteArrayType(QualType EltTy,
1238 ArrayType::ArraySizeModifier ASM,
1239 unsigned IndexTypeQuals) const;
1241 /// \brief Return the unique reference to the type for a constant array of
1242 /// the specified element type.
1243 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1244 ArrayType::ArraySizeModifier ASM,
1245 unsigned IndexTypeQuals) const;
1247 /// \brief Returns a vla type where known sizes are replaced with [*].
1248 QualType getVariableArrayDecayedType(QualType Ty) const;
1250 /// \brief Return the unique reference to a vector type of the specified
1251 /// element type and size.
1253 /// \pre \p VectorType must be a built-in type.
1254 QualType getVectorType(QualType VectorType, unsigned NumElts,
1255 VectorType::VectorKind VecKind) const;
1257 /// \brief Return the unique reference to an extended vector type
1258 /// of the specified element type and size.
1260 /// \pre \p VectorType must be a built-in type.
1261 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1263 /// \pre Return a non-unique reference to the type for a dependently-sized
1264 /// vector of the specified element type.
1266 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1268 QualType getDependentSizedExtVectorType(QualType VectorType,
1270 SourceLocation AttrLoc) const;
1272 /// \brief Return a K&R style C function type like 'int()'.
1273 QualType getFunctionNoProtoType(QualType ResultTy,
1274 const FunctionType::ExtInfo &Info) const;
1276 QualType getFunctionNoProtoType(QualType ResultTy) const {
1277 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1280 /// \brief Return a normal function type with a typed argument list.
1281 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1282 const FunctionProtoType::ExtProtoInfo &EPI) const {
1283 return getFunctionTypeInternal(ResultTy, Args, EPI, false);
1287 /// \brief Return a normal function type with a typed argument list.
1288 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1289 const FunctionProtoType::ExtProtoInfo &EPI,
1290 bool OnlyWantCanonical) const;
1293 /// \brief Return the unique reference to the type for the specified type
1295 QualType getTypeDeclType(const TypeDecl *Decl,
1296 const TypeDecl *PrevDecl = nullptr) const {
1297 assert(Decl && "Passed null for Decl param");
1298 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1301 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1302 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1303 return QualType(PrevDecl->TypeForDecl, 0);
1306 return getTypeDeclTypeSlow(Decl);
1309 /// \brief Return the unique reference to the type for the specified
1310 /// typedef-name decl.
1311 QualType getTypedefType(const TypedefNameDecl *Decl,
1312 QualType Canon = QualType()) const;
1314 QualType getRecordType(const RecordDecl *Decl) const;
1316 QualType getEnumType(const EnumDecl *Decl) const;
1318 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1320 QualType getAttributedType(AttributedType::Kind attrKind,
1321 QualType modifiedType,
1322 QualType equivalentType);
1324 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1325 QualType Replacement) const;
1326 QualType getSubstTemplateTypeParmPackType(
1327 const TemplateTypeParmType *Replaced,
1328 const TemplateArgument &ArgPack);
1331 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1333 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1335 QualType getTemplateSpecializationType(TemplateName T,
1336 ArrayRef<TemplateArgument> Args,
1337 QualType Canon = QualType()) const;
1340 getCanonicalTemplateSpecializationType(TemplateName T,
1341 ArrayRef<TemplateArgument> Args) const;
1343 QualType getTemplateSpecializationType(TemplateName T,
1344 const TemplateArgumentListInfo &Args,
1345 QualType Canon = QualType()) const;
1348 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1349 const TemplateArgumentListInfo &Args,
1350 QualType Canon = QualType()) const;
1352 QualType getParenType(QualType NamedType) const;
1354 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1355 NestedNameSpecifier *NNS,
1356 QualType NamedType) const;
1357 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1358 NestedNameSpecifier *NNS,
1359 const IdentifierInfo *Name,
1360 QualType Canon = QualType()) const;
1362 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1363 NestedNameSpecifier *NNS,
1364 const IdentifierInfo *Name,
1365 const TemplateArgumentListInfo &Args) const;
1366 QualType getDependentTemplateSpecializationType(
1367 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1368 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1370 TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
1372 /// Get a template argument list with one argument per template parameter
1373 /// in a template parameter list, such as for the injected class name of
1374 /// a class template.
1375 void getInjectedTemplateArgs(const TemplateParameterList *Params,
1376 SmallVectorImpl<TemplateArgument> &Args);
1378 QualType getPackExpansionType(QualType Pattern,
1379 Optional<unsigned> NumExpansions);
1381 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1382 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1384 /// Legacy interface: cannot provide type arguments or __kindof.
1385 QualType getObjCObjectType(QualType Base,
1386 ObjCProtocolDecl * const *Protocols,
1387 unsigned NumProtocols) const;
1389 QualType getObjCObjectType(QualType Base,
1390 ArrayRef<QualType> typeArgs,
1391 ArrayRef<ObjCProtocolDecl *> protocols,
1392 bool isKindOf) const;
1394 QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1395 ArrayRef<ObjCProtocolDecl *> protocols,
1396 QualType Canonical = QualType()) const;
1398 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1399 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1400 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1402 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1403 ObjCInterfaceDecl *IDecl);
1405 /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1406 QualType getObjCObjectPointerType(QualType OIT) const;
1408 /// \brief GCC extension.
1409 QualType getTypeOfExprType(Expr *e) const;
1410 QualType getTypeOfType(QualType t) const;
1412 /// \brief C++11 decltype.
1413 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1415 /// \brief Unary type transforms
1416 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1417 UnaryTransformType::UTTKind UKind) const;
1419 /// \brief C++11 deduced auto type.
1420 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1421 bool IsDependent) const;
1423 /// \brief C++11 deduction pattern for 'auto' type.
1424 QualType getAutoDeductType() const;
1426 /// \brief C++11 deduction pattern for 'auto &&' type.
1427 QualType getAutoRRefDeductType() const;
1429 /// \brief C++1z deduced class template specialization type.
1430 QualType getDeducedTemplateSpecializationType(TemplateName Template,
1431 QualType DeducedType,
1432 bool IsDependent) const;
1434 /// \brief Return the unique reference to the type for the specified TagDecl
1435 /// (struct/union/class/enum) decl.
1436 QualType getTagDeclType(const TagDecl *Decl) const;
1438 /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1441 /// The sizeof operator requires this (C99 6.5.3.4p4).
1442 CanQualType getSizeType() const;
1444 /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1446 CanQualType getIntMaxType() const;
1448 /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1450 CanQualType getUIntMaxType() const;
1452 /// \brief Return the unique wchar_t type available in C++ (and available as
1453 /// __wchar_t as a Microsoft extension).
1454 QualType getWCharType() const { return WCharTy; }
1456 /// \brief Return the type of wide characters. In C++, this returns the
1457 /// unique wchar_t type. In C99, this returns a type compatible with the type
1458 /// defined in <stddef.h> as defined by the target.
1459 QualType getWideCharType() const { return WideCharTy; }
1461 /// \brief Return the type of "signed wchar_t".
1463 /// Used when in C++, as a GCC extension.
1464 QualType getSignedWCharType() const;
1466 /// \brief Return the type of "unsigned wchar_t".
1468 /// Used when in C++, as a GCC extension.
1469 QualType getUnsignedWCharType() const;
1471 /// \brief In C99, this returns a type compatible with the type
1472 /// defined in <stddef.h> as defined by the target.
1473 QualType getWIntType() const { return WIntTy; }
1475 /// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4),
1476 /// as defined by the target.
1477 QualType getIntPtrType() const;
1479 /// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1480 /// as defined by the target.
1481 QualType getUIntPtrType() const;
1483 /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1484 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1485 QualType getPointerDiffType() const;
1487 /// \brief Return the unique type for "pid_t" defined in
1488 /// <sys/types.h>. We need this to compute the correct type for vfork().
1489 QualType getProcessIDType() const;
1491 /// \brief Return the C structure type used to represent constant CFStrings.
1492 QualType getCFConstantStringType() const;
1494 /// \brief Returns the C struct type for objc_super
1495 QualType getObjCSuperType() const;
1496 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1498 /// Get the structure type used to representation CFStrings, or NULL
1499 /// if it hasn't yet been built.
1500 QualType getRawCFConstantStringType() const {
1501 if (CFConstantStringTypeDecl)
1502 return getTypedefType(CFConstantStringTypeDecl);
1505 void setCFConstantStringType(QualType T);
1506 TypedefDecl *getCFConstantStringDecl() const;
1507 RecordDecl *getCFConstantStringTagDecl() const;
1509 // This setter/getter represents the ObjC type for an NSConstantString.
1510 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1511 QualType getObjCConstantStringInterface() const {
1512 return ObjCConstantStringType;
1515 QualType getObjCNSStringType() const {
1516 return ObjCNSStringType;
1519 void setObjCNSStringType(QualType T) {
1520 ObjCNSStringType = T;
1523 /// \brief Retrieve the type that \c id has been defined to, which may be
1524 /// different from the built-in \c id if \c id has been typedef'd.
1525 QualType getObjCIdRedefinitionType() const {
1526 if (ObjCIdRedefinitionType.isNull())
1527 return getObjCIdType();
1528 return ObjCIdRedefinitionType;
1531 /// \brief Set the user-written type that redefines \c id.
1532 void setObjCIdRedefinitionType(QualType RedefType) {
1533 ObjCIdRedefinitionType = RedefType;
1536 /// \brief Retrieve the type that \c Class has been defined to, which may be
1537 /// different from the built-in \c Class if \c Class has been typedef'd.
1538 QualType getObjCClassRedefinitionType() const {
1539 if (ObjCClassRedefinitionType.isNull())
1540 return getObjCClassType();
1541 return ObjCClassRedefinitionType;
1544 /// \brief Set the user-written type that redefines 'SEL'.
1545 void setObjCClassRedefinitionType(QualType RedefType) {
1546 ObjCClassRedefinitionType = RedefType;
1549 /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1550 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1551 QualType getObjCSelRedefinitionType() const {
1552 if (ObjCSelRedefinitionType.isNull())
1553 return getObjCSelType();
1554 return ObjCSelRedefinitionType;
1557 /// \brief Set the user-written type that redefines 'SEL'.
1558 void setObjCSelRedefinitionType(QualType RedefType) {
1559 ObjCSelRedefinitionType = RedefType;
1562 /// Retrieve the identifier 'NSObject'.
1563 IdentifierInfo *getNSObjectName() {
1564 if (!NSObjectName) {
1565 NSObjectName = &Idents.get("NSObject");
1568 return NSObjectName;
1571 /// Retrieve the identifier 'NSCopying'.
1572 IdentifierInfo *getNSCopyingName() {
1573 if (!NSCopyingName) {
1574 NSCopyingName = &Idents.get("NSCopying");
1577 return NSCopyingName;
1580 /// Retrieve the identifier 'bool'.
1581 IdentifierInfo *getBoolName() const {
1583 BoolName = &Idents.get("bool");
1587 IdentifierInfo *getMakeIntegerSeqName() const {
1588 if (!MakeIntegerSeqName)
1589 MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1590 return MakeIntegerSeqName;
1593 IdentifierInfo *getTypePackElementName() const {
1594 if (!TypePackElementName)
1595 TypePackElementName = &Idents.get("__type_pack_element");
1596 return TypePackElementName;
1599 /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1600 /// otherwise, returns a NULL type;
1601 QualType getObjCInstanceType() {
1602 return getTypeDeclType(getObjCInstanceTypeDecl());
1605 /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1606 /// "instancetype" type.
1607 TypedefDecl *getObjCInstanceTypeDecl();
1609 /// \brief Set the type for the C FILE type.
1610 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1612 /// \brief Retrieve the C FILE type.
1613 QualType getFILEType() const {
1615 return getTypeDeclType(FILEDecl);
1619 /// \brief Set the type for the C jmp_buf type.
1620 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1621 this->jmp_bufDecl = jmp_bufDecl;
1624 /// \brief Retrieve the C jmp_buf type.
1625 QualType getjmp_bufType() const {
1627 return getTypeDeclType(jmp_bufDecl);
1631 /// \brief Set the type for the C sigjmp_buf type.
1632 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1633 this->sigjmp_bufDecl = sigjmp_bufDecl;
1636 /// \brief Retrieve the C sigjmp_buf type.
1637 QualType getsigjmp_bufType() const {
1639 return getTypeDeclType(sigjmp_bufDecl);
1643 /// \brief Set the type for the C ucontext_t type.
1644 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1645 this->ucontext_tDecl = ucontext_tDecl;
1648 /// \brief Retrieve the C ucontext_t type.
1649 QualType getucontext_tType() const {
1651 return getTypeDeclType(ucontext_tDecl);
1655 /// \brief The result type of logical operations, '<', '>', '!=', etc.
1656 QualType getLogicalOperationType() const {
1657 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1660 /// \brief Emit the Objective-CC type encoding for the given type \p T into
1663 /// If \p Field is specified then record field names are also encoded.
1664 void getObjCEncodingForType(QualType T, std::string &S,
1665 const FieldDecl *Field=nullptr,
1666 QualType *NotEncodedT=nullptr) const;
1668 /// \brief Emit the Objective-C property type encoding for the given
1669 /// type \p T into \p S.
1670 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1672 void getLegacyIntegralTypeEncoding(QualType &t) const;
1674 /// \brief Put the string version of the type qualifiers \p QT into \p S.
1675 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1676 std::string &S) const;
1678 /// \brief Emit the encoded type for the function \p Decl into \p S.
1680 /// This is in the same format as Objective-C method encodings.
1682 /// \returns true if an error occurred (e.g., because one of the parameter
1683 /// types is incomplete), false otherwise.
1684 std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
1686 /// \brief Emit the encoded type for the method declaration \p Decl into
1688 std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1689 bool Extended = false) const;
1691 /// \brief Return the encoded type for this block declaration.
1692 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1694 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1695 /// this method declaration. If non-NULL, Container must be either
1696 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1697 /// only be NULL when getting encodings for protocol properties.
1698 std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1699 const Decl *Container) const;
1701 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1702 ObjCProtocolDecl *rProto) const;
1704 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1705 const ObjCPropertyDecl *PD,
1706 const Decl *Container) const;
1708 /// \brief Return the size of type \p T for Objective-C encoding purpose,
1710 CharUnits getObjCEncodingTypeSize(QualType T) const;
1712 /// \brief Retrieve the typedef corresponding to the predefined \c id type
1714 TypedefDecl *getObjCIdDecl() const;
1716 /// \brief Represents the Objective-CC \c id type.
1718 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1719 /// pointer type, a pointer to a struct.
1720 QualType getObjCIdType() const {
1721 return getTypeDeclType(getObjCIdDecl());
1724 /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1726 TypedefDecl *getObjCSelDecl() const;
1728 /// \brief Retrieve the type that corresponds to the predefined Objective-C
1730 QualType getObjCSelType() const {
1731 return getTypeDeclType(getObjCSelDecl());
1734 /// \brief Retrieve the typedef declaration corresponding to the predefined
1735 /// Objective-C 'Class' type.
1736 TypedefDecl *getObjCClassDecl() const;
1738 /// \brief Represents the Objective-C \c Class type.
1740 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1741 /// pointer type, a pointer to a struct.
1742 QualType getObjCClassType() const {
1743 return getTypeDeclType(getObjCClassDecl());
1746 /// \brief Retrieve the Objective-C class declaration corresponding to
1747 /// the predefined \c Protocol class.
1748 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1750 /// \brief Retrieve declaration of 'BOOL' typedef
1751 TypedefDecl *getBOOLDecl() const {
1755 /// \brief Save declaration of 'BOOL' typedef
1756 void setBOOLDecl(TypedefDecl *TD) {
1760 /// \brief type of 'BOOL' type.
1761 QualType getBOOLType() const {
1762 return getTypeDeclType(getBOOLDecl());
1765 /// \brief Retrieve the type of the Objective-C \c Protocol class.
1766 QualType getObjCProtoType() const {
1767 return getObjCInterfaceType(getObjCProtocolDecl());
1770 /// \brief Retrieve the C type declaration corresponding to the predefined
1771 /// \c __builtin_va_list type.
1772 TypedefDecl *getBuiltinVaListDecl() const;
1774 /// \brief Retrieve the type of the \c __builtin_va_list type.
1775 QualType getBuiltinVaListType() const {
1776 return getTypeDeclType(getBuiltinVaListDecl());
1779 /// \brief Retrieve the C type declaration corresponding to the predefined
1780 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1781 /// for some targets.
1782 Decl *getVaListTagDecl() const;
1784 /// Retrieve the C type declaration corresponding to the predefined
1785 /// \c __builtin_ms_va_list type.
1786 TypedefDecl *getBuiltinMSVaListDecl() const;
1788 /// Retrieve the type of the \c __builtin_ms_va_list type.
1789 QualType getBuiltinMSVaListType() const {
1790 return getTypeDeclType(getBuiltinMSVaListDecl());
1793 /// \brief Return a type with additional \c const, \c volatile, or
1794 /// \c restrict qualifiers.
1795 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1796 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1799 /// \brief Un-split a SplitQualType.
1800 QualType getQualifiedType(SplitQualType split) const {
1801 return getQualifiedType(split.Ty, split.Quals);
1804 /// \brief Return a type with additional qualifiers.
1805 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1806 if (!Qs.hasNonFastQualifiers())
1807 return T.withFastQualifiers(Qs.getFastQualifiers());
1808 QualifierCollector Qc(Qs);
1809 const Type *Ptr = Qc.strip(T);
1810 return getExtQualType(Ptr, Qc);
1813 /// \brief Return a type with additional qualifiers.
1814 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1815 if (!Qs.hasNonFastQualifiers())
1816 return QualType(T, Qs.getFastQualifiers());
1817 return getExtQualType(T, Qs);
1820 /// \brief Return a type with the given lifetime qualifier.
1822 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1823 QualType getLifetimeQualifiedType(QualType type,
1824 Qualifiers::ObjCLifetime lifetime) {
1825 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1826 assert(lifetime != Qualifiers::OCL_None);
1829 qs.addObjCLifetime(lifetime);
1830 return getQualifiedType(type, qs);
1833 /// getUnqualifiedObjCPointerType - Returns version of
1834 /// Objective-C pointer type with lifetime qualifier removed.
1835 QualType getUnqualifiedObjCPointerType(QualType type) const {
1836 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1837 !type.getQualifiers().hasObjCLifetime())
1839 Qualifiers Qs = type.getQualifiers();
1840 Qs.removeObjCLifetime();
1841 return getQualifiedType(type.getUnqualifiedType(), Qs);
1844 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1845 SourceLocation NameLoc) const;
1847 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1848 UnresolvedSetIterator End) const;
1850 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1851 bool TemplateKeyword,
1852 TemplateDecl *Template) const;
1854 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1855 const IdentifierInfo *Name) const;
1856 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1857 OverloadedOperatorKind Operator) const;
1858 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1859 TemplateName replacement) const;
1860 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1861 const TemplateArgument &ArgPack) const;
1863 enum GetBuiltinTypeError {
1864 GE_None, ///< No error
1865 GE_Missing_stdio, ///< Missing a type from <stdio.h>
1866 GE_Missing_setjmp, ///< Missing a type from <setjmp.h>
1867 GE_Missing_ucontext ///< Missing a type from <ucontext.h>
1870 /// \brief Return the type for the specified builtin.
1872 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1873 /// arguments to the builtin that are required to be integer constant
1875 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1876 unsigned *IntegerConstantArgs = nullptr) const;
1879 CanQualType getFromTargetType(unsigned Type) const;
1880 TypeInfo getTypeInfoImpl(const Type *T) const;
1882 //===--------------------------------------------------------------------===//
1884 //===--------------------------------------------------------------------===//
1887 /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1888 /// collection attributes.
1889 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1891 /// \brief Return true if the given vector types are of the same unqualified
1892 /// type or if they are equivalent to the same GCC vector type.
1894 /// \note This ignores whether they are target-specific (AltiVec or Neon)
1896 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1898 /// \brief Return true if this is an \c NSObject object with its \c NSObject
1900 static bool isObjCNSObjectType(QualType Ty) {
1901 return Ty->isObjCNSObjectType();
1904 //===--------------------------------------------------------------------===//
1905 // Type Sizing and Analysis
1906 //===--------------------------------------------------------------------===//
1908 /// \brief Return the APFloat 'semantics' for the specified scalar floating
1910 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1912 /// \brief Get the size and alignment of the specified complete type in bits.
1913 TypeInfo getTypeInfo(const Type *T) const;
1914 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
1916 /// \brief Get default simd alignment of the specified complete type in bits.
1917 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
1919 /// \brief Return the size of the specified (complete) type \p T, in bits.
1920 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
1921 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
1923 /// \brief Return the size of the character type, in bits.
1924 uint64_t getCharWidth() const {
1925 return getTypeSize(CharTy);
1928 /// \brief Convert a size in bits to a size in characters.
1929 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1931 /// \brief Convert a size in characters to a size in bits.
1932 int64_t toBits(CharUnits CharSize) const;
1934 /// \brief Return the size of the specified (complete) type \p T, in
1936 CharUnits getTypeSizeInChars(QualType T) const;
1937 CharUnits getTypeSizeInChars(const Type *T) const;
1939 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1941 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
1942 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
1944 /// \brief Return the ABI-specified alignment of a type, in bits, or 0 if
1945 /// the type is incomplete and we cannot determine the alignment (for
1946 /// example, from alignment attributes).
1947 unsigned getTypeAlignIfKnown(QualType T) const;
1949 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1951 CharUnits getTypeAlignInChars(QualType T) const;
1952 CharUnits getTypeAlignInChars(const Type *T) const;
1954 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1955 // type is a record, its data size is returned.
1956 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1958 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1959 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1961 /// \brief Determine if the alignment the type has was required using an
1962 /// alignment attribute.
1963 bool isAlignmentRequired(const Type *T) const;
1964 bool isAlignmentRequired(QualType T) const;
1966 /// \brief Return the "preferred" alignment of the specified type \p T for
1967 /// the current target, in bits.
1969 /// This can be different than the ABI alignment in cases where it is
1970 /// beneficial for performance to overalign a data type.
1971 unsigned getPreferredTypeAlign(const Type *T) const;
1973 /// \brief Return the default alignment for __attribute__((aligned)) on
1974 /// this target, to be used if no alignment value is specified.
1975 unsigned getTargetDefaultAlignForAttributeAligned() const;
1977 /// \brief Return the alignment in bits that should be given to a
1978 /// global variable with type \p T.
1979 unsigned getAlignOfGlobalVar(QualType T) const;
1981 /// \brief Return the alignment in characters that should be given to a
1982 /// global variable with type \p T.
1983 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
1985 /// \brief Return a conservative estimate of the alignment of the specified
1988 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
1991 /// If \p ForAlignof, references are treated like their underlying type
1992 /// and large arrays don't get any special treatment. If not \p ForAlignof
1993 /// it computes the value expected by CodeGen: references are treated like
1994 /// pointers and large arrays get extra alignment.
1995 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
1997 /// \brief Get or compute information about the layout of the specified
1998 /// record (struct/union/class) \p D, which indicates its size and field
1999 /// position information.
2000 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2002 /// \brief Get or compute information about the layout of the specified
2003 /// Objective-C interface.
2004 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2007 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2008 bool Simple = false) const;
2010 /// \brief Get or compute information about the layout of the specified
2011 /// Objective-C implementation.
2013 /// This may differ from the interface if synthesized ivars are present.
2014 const ASTRecordLayout &
2015 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2017 /// \brief Get our current best idea for the key function of the
2018 /// given record decl, or NULL if there isn't one.
2020 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2021 /// ...the first non-pure virtual function that is not inline at the
2022 /// point of class definition.
2024 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
2025 /// virtual functions that are defined 'inline', which means that
2026 /// the result of this computation can change.
2027 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2029 /// \brief Observe that the given method cannot be a key function.
2030 /// Checks the key-function cache for the method's class and clears it
2031 /// if matches the given declaration.
2033 /// This is used in ABIs where out-of-line definitions marked
2034 /// inline are not considered to be key functions.
2036 /// \param method should be the declaration from the class definition
2037 void setNonKeyFunction(const CXXMethodDecl *method);
2039 /// Loading virtual member pointers using the virtual inheritance model
2040 /// always results in an adjustment using the vbtable even if the index is
2043 /// This is usually OK because the first slot in the vbtable points
2044 /// backwards to the top of the MDC. However, the MDC might be reusing a
2045 /// vbptr from an nv-base. In this case, the first slot in the vbtable
2046 /// points to the start of the nv-base which introduced the vbptr and *not*
2047 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
2048 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2050 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2051 uint64_t getFieldOffset(const ValueDecl *FD) const;
2053 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2055 VTableContextBase *getVTableContext();
2057 MangleContext *createMangleContext();
2059 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2060 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2062 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2063 void CollectInheritedProtocols(const Decl *CDecl,
2064 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2066 //===--------------------------------------------------------------------===//
2068 //===--------------------------------------------------------------------===//
2070 /// \brief Return the canonical (structural) type corresponding to the
2071 /// specified potentially non-canonical type \p T.
2073 /// The non-canonical version of a type may have many "decorated" versions of
2074 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
2075 /// returned type is guaranteed to be free of any of these, allowing two
2076 /// canonical types to be compared for exact equality with a simple pointer
2078 CanQualType getCanonicalType(QualType T) const {
2079 return CanQualType::CreateUnsafe(T.getCanonicalType());
2082 const Type *getCanonicalType(const Type *T) const {
2083 return T->getCanonicalTypeInternal().getTypePtr();
2086 /// \brief Return the canonical parameter type corresponding to the specific
2087 /// potentially non-canonical one.
2089 /// Qualifiers are stripped off, functions are turned into function
2090 /// pointers, and arrays decay one level into pointers.
2091 CanQualType getCanonicalParamType(QualType T) const;
2093 /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
2094 bool hasSameType(QualType T1, QualType T2) const {
2095 return getCanonicalType(T1) == getCanonicalType(T2);
2098 bool hasSameType(const Type *T1, const Type *T2) const {
2099 return getCanonicalType(T1) == getCanonicalType(T2);
2102 /// \brief Return this type as a completely-unqualified array type,
2103 /// capturing the qualifiers in \p Quals.
2105 /// This will remove the minimal amount of sugaring from the types, similar
2106 /// to the behavior of QualType::getUnqualifiedType().
2108 /// \param T is the qualified type, which may be an ArrayType
2110 /// \param Quals will receive the full set of qualifiers that were
2111 /// applied to the array.
2113 /// \returns if this is an array type, the completely unqualified array type
2114 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2115 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2117 /// \brief Determine whether the given types are equivalent after
2118 /// cvr-qualifiers have been removed.
2119 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2120 return getCanonicalType(T1).getTypePtr() ==
2121 getCanonicalType(T2).getTypePtr();
2124 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2125 bool IsParam) const {
2126 auto SubTnullability = SubT->getNullability(*this);
2127 auto SuperTnullability = SuperT->getNullability(*this);
2128 if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
2129 // Neither has nullability; return true
2130 if (!SubTnullability)
2132 // Both have nullability qualifier.
2133 if (*SubTnullability == *SuperTnullability ||
2134 *SubTnullability == NullabilityKind::Unspecified ||
2135 *SuperTnullability == NullabilityKind::Unspecified)
2139 // Ok for the superclass method parameter to be "nonnull" and the subclass
2140 // method parameter to be "nullable"
2141 return (*SuperTnullability == NullabilityKind::NonNull &&
2142 *SubTnullability == NullabilityKind::Nullable);
2145 // For the return type, it's okay for the superclass method to specify
2146 // "nullable" and the subclass method specify "nonnull"
2147 return (*SuperTnullability == NullabilityKind::Nullable &&
2148 *SubTnullability == NullabilityKind::NonNull);
2154 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2155 const ObjCMethodDecl *MethodImp);
2157 bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
2159 /// \brief Retrieves the "canonical" nested name specifier for a
2160 /// given nested name specifier.
2162 /// The canonical nested name specifier is a nested name specifier
2163 /// that uniquely identifies a type or namespace within the type
2164 /// system. For example, given:
2169 /// template<typename T> struct X { typename T* type; };
2173 /// template<typename T> struct Y {
2174 /// typename N::S::X<T>::type member;
2178 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2179 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2180 /// by declarations in the type system and the canonical type for
2181 /// the template type parameter 'T' is template-param-0-0.
2182 NestedNameSpecifier *
2183 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2185 /// \brief Retrieves the default calling convention for the current target.
2186 CallingConv getDefaultCallingConvention(bool isVariadic,
2187 bool IsCXXMethod) const;
2189 /// \brief Retrieves the "canonical" template name that refers to a
2192 /// The canonical template name is the simplest expression that can
2193 /// be used to refer to a given template. For most templates, this
2194 /// expression is just the template declaration itself. For example,
2195 /// the template std::vector can be referred to via a variety of
2196 /// names---std::vector, \::std::vector, vector (if vector is in
2197 /// scope), etc.---but all of these names map down to the same
2198 /// TemplateDecl, which is used to form the canonical template name.
2200 /// Dependent template names are more interesting. Here, the
2201 /// template name could be something like T::template apply or
2202 /// std::allocator<T>::template rebind, where the nested name
2203 /// specifier itself is dependent. In this case, the canonical
2204 /// template name uses the shortest form of the dependent
2205 /// nested-name-specifier, which itself contains all canonical
2206 /// types, values, and templates.
2207 TemplateName getCanonicalTemplateName(TemplateName Name) const;
2209 /// \brief Determine whether the given template names refer to the same
2211 bool hasSameTemplateName(TemplateName X, TemplateName Y);
2213 /// \brief Retrieve the "canonical" template argument.
2215 /// The canonical template argument is the simplest template argument
2216 /// (which may be a type, value, expression, or declaration) that
2217 /// expresses the value of the argument.
2218 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2221 /// Type Query functions. If the type is an instance of the specified class,
2222 /// return the Type pointer for the underlying maximally pretty type. This
2223 /// is a member of ASTContext because this may need to do some amount of
2224 /// canonicalization, e.g. to move type qualifiers into the element type.
2225 const ArrayType *getAsArrayType(QualType T) const;
2226 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2227 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2229 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2230 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2232 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2233 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2235 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2237 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2240 /// \brief Return the innermost element type of an array type.
2242 /// For example, will return "int" for int[m][n]
2243 QualType getBaseElementType(const ArrayType *VAT) const;
2245 /// \brief Return the innermost element type of a type (which needn't
2246 /// actually be an array type).
2247 QualType getBaseElementType(QualType QT) const;
2249 /// \brief Return number of constant array elements.
2250 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2252 /// \brief Perform adjustment on the parameter type of a function.
2254 /// This routine adjusts the given parameter type @p T to the actual
2255 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2256 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2257 QualType getAdjustedParameterType(QualType T) const;
2259 /// \brief Retrieve the parameter type as adjusted for use in the signature
2260 /// of a function, decaying array and function types and removing top-level
2262 QualType getSignatureParameterType(QualType T) const;
2264 QualType getExceptionObjectType(QualType T) const;
2266 /// \brief Return the properly qualified result of decaying the specified
2267 /// array type to a pointer.
2269 /// This operation is non-trivial when handling typedefs etc. The canonical
2270 /// type of \p T must be an array type, this returns a pointer to a properly
2271 /// qualified element of the array.
2273 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2274 QualType getArrayDecayedType(QualType T) const;
2276 /// \brief Return the type that \p PromotableType will promote to: C99
2277 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2278 QualType getPromotedIntegerType(QualType PromotableType) const;
2280 /// \brief Recurses in pointer/array types until it finds an Objective-C
2281 /// retainable type and returns its ownership.
2282 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2284 /// \brief Whether this is a promotable bitfield reference according
2285 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2287 /// \returns the type this bit-field will promote to, or NULL if no
2288 /// promotion occurs.
2289 QualType isPromotableBitField(Expr *E) const;
2291 /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
2293 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2294 /// \p LHS < \p RHS, return -1.
2295 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2297 /// \brief Compare the rank of the two specified floating point types,
2298 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2300 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2301 /// \p LHS < \p RHS, return -1.
2302 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2304 /// \brief Return a real floating point or a complex type (based on
2305 /// \p typeDomain/\p typeSize).
2307 /// \param typeDomain a real floating point or complex type.
2308 /// \param typeSize a real floating point or complex type.
2309 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2310 QualType typeDomain) const;
2312 unsigned getTargetAddressSpace(QualType T) const {
2313 return getTargetAddressSpace(T.getQualifiers());
2316 unsigned getTargetAddressSpace(Qualifiers Q) const {
2317 return getTargetAddressSpace(Q.getAddressSpace());
2320 unsigned getTargetAddressSpace(unsigned AS) const;
2322 /// Get target-dependent integer value for null pointer which is used for
2323 /// constant folding.
2324 uint64_t getTargetNullPointerValue(QualType QT) const;
2326 bool addressSpaceMapManglingFor(unsigned AS) const {
2327 return AddrSpaceMapMangling ||
2328 AS >= LangAS::Count;
2332 // Helper for integer ordering
2333 unsigned getIntegerRank(const Type *T) const;
2336 //===--------------------------------------------------------------------===//
2337 // Type Compatibility Predicates
2338 //===--------------------------------------------------------------------===//
2340 /// Compatibility predicates used to check assignment expressions.
2341 bool typesAreCompatible(QualType T1, QualType T2,
2342 bool CompareUnqualified = false); // C99 6.2.7p1
2344 bool propertyTypesAreCompatible(QualType, QualType);
2345 bool typesAreBlockPointerCompatible(QualType, QualType);
2347 bool isObjCIdType(QualType T) const {
2348 return T == getObjCIdType();
2350 bool isObjCClassType(QualType T) const {
2351 return T == getObjCClassType();
2353 bool isObjCSelType(QualType T) const {
2354 return T == getObjCSelType();
2356 bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
2359 bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
2361 // Check the safety of assignment from LHS to RHS
2362 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2363 const ObjCObjectPointerType *RHSOPT);
2364 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2365 const ObjCObjectType *RHS);
2366 bool canAssignObjCInterfacesInBlockPointer(
2367 const ObjCObjectPointerType *LHSOPT,
2368 const ObjCObjectPointerType *RHSOPT,
2369 bool BlockReturnType);
2370 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2371 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2372 const ObjCObjectPointerType *RHSOPT);
2373 bool canBindObjCObjectType(QualType To, QualType From);
2375 // Functions for calculating composite types
2376 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2377 bool Unqualified = false, bool BlockReturnType = false);
2378 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2379 bool Unqualified = false);
2380 QualType mergeFunctionParameterTypes(QualType, QualType,
2381 bool OfBlockPointer = false,
2382 bool Unqualified = false);
2383 QualType mergeTransparentUnionType(QualType, QualType,
2384 bool OfBlockPointer=false,
2385 bool Unqualified = false);
2387 QualType mergeObjCGCQualifiers(QualType, QualType);
2389 bool doFunctionTypesMatchOnExtParameterInfos(
2390 const FunctionProtoType *FromFunctionType,
2391 const FunctionProtoType *ToFunctionType);
2393 void ResetObjCLayout(const ObjCContainerDecl *CD);
2395 //===--------------------------------------------------------------------===//
2396 // Integer Predicates
2397 //===--------------------------------------------------------------------===//
2399 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2400 // of bits in an integer type excluding any padding bits.
2401 unsigned getIntWidth(QualType T) const;
2403 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2404 // unsigned integer type. This method takes a signed type, and returns the
2405 // corresponding unsigned integer type.
2406 QualType getCorrespondingUnsignedType(QualType T) const;
2408 //===--------------------------------------------------------------------===//
2410 //===--------------------------------------------------------------------===//
2412 /// \brief Make an APSInt of the appropriate width and signedness for the
2413 /// given \p Value and integer \p Type.
2414 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2415 // If Type is a signed integer type larger than 64 bits, we need to be sure
2416 // to sign extend Res appropriately.
2417 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2419 unsigned Width = getIntWidth(Type);
2420 if (Width != Res.getBitWidth())
2421 return Res.extOrTrunc(Width);
2425 bool isSentinelNullExpr(const Expr *E);
2427 /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
2429 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2430 /// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
2432 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2434 /// \brief Return true if there is at least one \@implementation in the TU.
2435 bool AnyObjCImplementation() {
2436 return !ObjCImpls.empty();
2439 /// \brief Set the implementation of ObjCInterfaceDecl.
2440 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2441 ObjCImplementationDecl *ImplD);
2442 /// \brief Set the implementation of ObjCCategoryDecl.
2443 void setObjCImplementation(ObjCCategoryDecl *CatD,
2444 ObjCCategoryImplDecl *ImplD);
2446 /// \brief Get the duplicate declaration of a ObjCMethod in the same
2447 /// interface, or null if none exists.
2448 const ObjCMethodDecl *
2449 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2451 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2452 const ObjCMethodDecl *Redecl);
2454 /// \brief Returns the Objective-C interface that \p ND belongs to if it is
2455 /// an Objective-C method/property/ivar etc. that is part of an interface,
2456 /// otherwise returns null.
2457 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2459 /// \brief Set the copy inialization expression of a block var decl.
2460 void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2461 /// \brief Get the copy initialization expression of the VarDecl \p VD, or
2462 /// NULL if none exists.
2463 Expr *getBlockVarCopyInits(const VarDecl* VD);
2465 /// \brief Allocate an uninitialized TypeSourceInfo.
2467 /// The caller should initialize the memory held by TypeSourceInfo using
2468 /// the TypeLoc wrappers.
2470 /// \param T the type that will be the basis for type source info. This type
2471 /// should refer to how the declarator was written in source code, not to
2472 /// what type semantic analysis resolved the declarator to.
2474 /// \param Size the size of the type info to create, or 0 if the size
2475 /// should be calculated based on the type.
2476 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2478 /// \brief Allocate a TypeSourceInfo where all locations have been
2479 /// initialized to a given location, which defaults to the empty
2482 getTrivialTypeSourceInfo(QualType T,
2483 SourceLocation Loc = SourceLocation()) const;
2485 /// \brief Add a deallocation callback that will be invoked when the
2486 /// ASTContext is destroyed.
2488 /// \param Callback A callback function that will be invoked on destruction.
2490 /// \param Data Pointer data that will be provided to the callback function
2491 /// when it is called.
2492 void AddDeallocation(void (*Callback)(void*), void *Data);
2494 /// If T isn't trivially destructible, calls AddDeallocation to register it
2495 /// for destruction.
2496 template <typename T>
2497 void addDestruction(T *Ptr) {
2498 if (!std::is_trivially_destructible<T>::value) {
2499 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
2500 AddDeallocation(DestroyPtr, Ptr);
2504 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2505 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2507 /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
2508 /// lazily, only when used; this is only relevant for function or file scoped
2509 /// var definitions.
2511 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2513 bool DeclMustBeEmitted(const Decl *D);
2515 const CXXConstructorDecl *
2516 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2518 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2519 CXXConstructorDecl *CD);
2521 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2523 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2525 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2527 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2529 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2530 unsigned getManglingNumber(const NamedDecl *ND) const;
2532 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2533 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2535 /// \brief Retrieve the context for computing mangling numbers in the given
2537 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2539 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
2541 /// \brief Used by ParmVarDecl to store on the side the
2542 /// index of the parameter when it exceeds the size of the normal bitfield.
2543 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2545 /// \brief Used by ParmVarDecl to retrieve on the side the
2546 /// index of the parameter when it exceeds the size of the normal bitfield.
2547 unsigned getParameterIndex(const ParmVarDecl *D) const;
2549 /// \brief Get the storage for the constant value of a materialized temporary
2550 /// of static storage duration.
2551 APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
2554 //===--------------------------------------------------------------------===//
2556 //===--------------------------------------------------------------------===//
2558 /// \brief The number of implicitly-declared default constructors.
2559 static unsigned NumImplicitDefaultConstructors;
2561 /// \brief The number of implicitly-declared default constructors for
2562 /// which declarations were built.
2563 static unsigned NumImplicitDefaultConstructorsDeclared;
2565 /// \brief The number of implicitly-declared copy constructors.
2566 static unsigned NumImplicitCopyConstructors;
2568 /// \brief The number of implicitly-declared copy constructors for
2569 /// which declarations were built.
2570 static unsigned NumImplicitCopyConstructorsDeclared;
2572 /// \brief The number of implicitly-declared move constructors.
2573 static unsigned NumImplicitMoveConstructors;
2575 /// \brief The number of implicitly-declared move constructors for
2576 /// which declarations were built.
2577 static unsigned NumImplicitMoveConstructorsDeclared;
2579 /// \brief The number of implicitly-declared copy assignment operators.
2580 static unsigned NumImplicitCopyAssignmentOperators;
2582 /// \brief The number of implicitly-declared copy assignment operators for
2583 /// which declarations were built.
2584 static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2586 /// \brief The number of implicitly-declared move assignment operators.
2587 static unsigned NumImplicitMoveAssignmentOperators;
2589 /// \brief The number of implicitly-declared move assignment operators for
2590 /// which declarations were built.
2591 static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2593 /// \brief The number of implicitly-declared destructors.
2594 static unsigned NumImplicitDestructors;
2596 /// \brief The number of implicitly-declared destructors for which
2597 /// declarations were built.
2598 static unsigned NumImplicitDestructorsDeclared;
2601 /// \brief Initialize built-in types.
2603 /// This routine may only be invoked once for a given ASTContext object.
2604 /// It is normally invoked after ASTContext construction.
2606 /// \param Target The target
2607 void InitBuiltinTypes(const TargetInfo &Target,
2608 const TargetInfo *AuxTarget = nullptr);
2611 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2613 // Return the Objective-C type encoding for a given type.
2614 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2615 bool ExpandPointedToStructures,
2616 bool ExpandStructures,
2617 const FieldDecl *Field,
2618 bool OutermostType = false,
2619 bool EncodingProperty = false,
2620 bool StructField = false,
2621 bool EncodeBlockParameters = false,
2622 bool EncodeClassNames = false,
2623 bool EncodePointerToObjCTypedef = false,
2624 QualType *NotEncodedT=nullptr) const;
2626 // Adds the encoding of the structure's members.
2627 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2628 const FieldDecl *Field,
2629 bool includeVBases = true,
2630 QualType *NotEncodedT=nullptr) const;
2632 // Adds the encoding of a method parameter or return type.
2633 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2634 QualType T, std::string& S,
2635 bool Extended) const;
2637 /// \brief Returns true if this is an inline-initialized static data member
2638 /// which is treated as a definition for MSVC compatibility.
2639 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2641 enum class InlineVariableDefinitionKind {
2642 None, ///< Not an inline variable.
2643 Weak, ///< Weak definition of inline variable.
2644 WeakUnknown, ///< Weak for now, might become strong later in this TU.
2645 Strong ///< Strong definition.
2647 /// \brief Determine whether a definition of this inline variable should
2648 /// be treated as a weak or strong definition. For compatibility with
2649 /// C++14 and before, for a constexpr static data member, if there is an
2650 /// out-of-line declaration of the member, we may promote it from weak to
2652 InlineVariableDefinitionKind
2653 getInlineVariableDefinitionKind(const VarDecl *VD) const;
2656 const ASTRecordLayout &
2657 getObjCLayout(const ObjCInterfaceDecl *D,
2658 const ObjCImplementationDecl *Impl) const;
2660 /// \brief A set of deallocations that should be performed when the
2661 /// ASTContext is destroyed.
2662 // FIXME: We really should have a better mechanism in the ASTContext to
2663 // manage running destructors for types which do variable sized allocation
2664 // within the AST. In some places we thread the AST bump pointer allocator
2665 // into the datastructures which avoids this mess during deallocation but is
2666 // wasteful of memory, and here we require a lot of error prone book keeping
2667 // in order to track and run destructors while we're tearing things down.
2668 typedef llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>
2669 DeallocationFunctionsAndArguments;
2670 DeallocationFunctionsAndArguments Deallocations;
2672 // FIXME: This currently contains the set of StoredDeclMaps used
2673 // by DeclContext objects. This probably should not be in ASTContext,
2674 // but we include it here so that ASTContext can quickly deallocate them.
2675 llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2677 friend class DeclContext;
2678 friend class DeclarationNameTable;
2680 void ReleaseDeclContextMaps();
2681 void ReleaseParentMapEntries();
2683 std::unique_ptr<ParentMapPointers> PointerParents;
2684 std::unique_ptr<ParentMapOtherNodes> OtherParents;
2686 std::unique_ptr<VTableContextBase> VTContext;
2689 enum PragmaSectionFlag : unsigned {
2695 PSF_Invalid = 0x80000000U,
2698 struct SectionInfo {
2699 DeclaratorDecl *Decl;
2700 SourceLocation PragmaSectionLocation;
2703 SectionInfo() = default;
2704 SectionInfo(DeclaratorDecl *Decl,
2705 SourceLocation PragmaSectionLocation,
2708 PragmaSectionLocation(PragmaSectionLocation),
2709 SectionFlags(SectionFlags) {}
2712 llvm::StringMap<SectionInfo> SectionInfos;
2715 /// \brief Utility function for constructing a nullary selector.
2716 static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2717 IdentifierInfo* II = &Ctx.Idents.get(name);
2718 return Ctx.Selectors.getSelector(0, &II);
2721 /// \brief Utility function for constructing an unary selector.
2722 static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2723 IdentifierInfo* II = &Ctx.Idents.get(name);
2724 return Ctx.Selectors.getSelector(1, &II);
2727 } // end namespace clang
2729 // operator new and delete aren't allowed inside namespaces.
2731 /// @brief Placement new for using the ASTContext's allocator.
2733 /// This placement form of operator new uses the ASTContext's allocator for
2734 /// obtaining memory.
2736 /// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2737 /// here need to also be made there.
2739 /// We intentionally avoid using a nothrow specification here so that the calls
2740 /// to this operator will not perform a null check on the result -- the
2741 /// underlying allocator never returns null pointers.
2743 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2745 /// // Default alignment (8)
2746 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2747 /// // Specific alignment
2748 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2750 /// Memory allocated through this placement new operator does not need to be
2751 /// explicitly freed, as ASTContext will free all of this memory when it gets
2752 /// destroyed. Please note that you cannot use delete on the pointer.
2754 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2755 /// @param C The ASTContext that provides the allocator.
2756 /// @param Alignment The alignment of the allocated memory (if the underlying
2757 /// allocator supports it).
2758 /// @return The allocated memory. Could be NULL.
2759 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2761 return C.Allocate(Bytes, Alignment);
2763 /// @brief Placement delete companion to the new above.
2765 /// This operator is just a companion to the new above. There is no way of
2766 /// invoking it directly; see the new operator for more details. This operator
2767 /// is called implicitly by the compiler if a placement new expression using
2768 /// the ASTContext throws in the object constructor.
2769 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2773 /// This placement form of operator new[] uses the ASTContext's allocator for
2774 /// obtaining memory.
2776 /// We intentionally avoid using a nothrow specification here so that the calls
2777 /// to this operator will not perform a null check on the result -- the
2778 /// underlying allocator never returns null pointers.
2780 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2782 /// // Default alignment (8)
2783 /// char *data = new (Context) char[10];
2784 /// // Specific alignment
2785 /// char *data = new (Context, 4) char[10];
2787 /// Memory allocated through this placement new[] operator does not need to be
2788 /// explicitly freed, as ASTContext will free all of this memory when it gets
2789 /// destroyed. Please note that you cannot use delete on the pointer.
2791 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2792 /// @param C The ASTContext that provides the allocator.
2793 /// @param Alignment The alignment of the allocated memory (if the underlying
2794 /// allocator supports it).
2795 /// @return The allocated memory. Could be NULL.
2796 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2797 size_t Alignment = 8) {
2798 return C.Allocate(Bytes, Alignment);
2801 /// @brief Placement delete[] companion to the new[] above.
2803 /// This operator is just a companion to the new[] above. There is no way of
2804 /// invoking it directly; see the new[] operator for more details. This operator
2805 /// is called implicitly by the compiler if a placement new[] expression using
2806 /// the ASTContext throws in the object constructor.
2807 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2811 /// \brief Create the representation of a LazyGenerationalUpdatePtr.
2812 template <typename Owner, typename T,
2813 void (clang::ExternalASTSource::*Update)(Owner)>
2814 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
2815 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
2816 const clang::ASTContext &Ctx, T Value) {
2817 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
2818 // include ASTContext.h. We explicitly instantiate it for all relevant types
2819 // in ASTContext.cpp.
2820 if (auto *Source = Ctx.getExternalSource())
2821 return new (Ctx) LazyData(Source, Value);
2825 #endif // LLVM_CLANG_AST_ASTCONTEXT_H