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/ExternalASTSource.h"
23 #include "clang/AST/NestedNameSpecifier.h"
24 #include "clang/AST/PrettyPrinter.h"
25 #include "clang/AST/RawCommentList.h"
26 #include "clang/AST/TemplateName.h"
27 #include "clang/AST/Type.h"
28 #include "clang/Basic/AddressSpaces.h"
29 #include "clang/Basic/IdentifierTable.h"
30 #include "clang/Basic/LangOptions.h"
31 #include "clang/Basic/Module.h"
32 #include "clang/Basic/OperatorKinds.h"
33 #include "clang/Basic/PartialDiagnostic.h"
34 #include "clang/Basic/SanitizerBlacklist.h"
35 #include "clang/Basic/VersionTuple.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/FoldingSet.h"
38 #include "llvm/ADT/IntrusiveRefCntPtr.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/TinyPtrVector.h"
41 #include "llvm/Support/Allocator.h"
52 class ASTRecordLayout;
55 class DiagnosticsEngine;
57 class ASTMutationListener;
58 class IdentifierTable;
59 class MaterializeTemporaryExpr;
63 class MangleNumberingContext;
67 class ObjCPropertyDecl;
68 class UnresolvedSetIterator;
70 class UsingShadowDecl;
71 class VTableContextBase;
73 namespace Builtin { class Context; }
74 enum BuiltinTemplateKind : int;
83 bool AlignIsRequired : 1;
84 TypeInfo() : Width(0), Align(0), AlignIsRequired(false) {}
85 TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
86 : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
89 /// \brief Holds long-lived AST nodes (such as types and decls) that can be
90 /// referred to throughout the semantic analysis of a file.
91 class ASTContext : public RefCountedBase<ASTContext> {
92 ASTContext &this_() { return *this; }
94 mutable SmallVector<Type *, 0> Types;
95 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
96 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
97 mutable llvm::FoldingSet<PointerType> PointerTypes;
98 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
99 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
100 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
101 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
102 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
103 mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
104 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
105 mutable std::vector<VariableArrayType*> VariableArrayTypes;
106 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
107 mutable llvm::FoldingSet<DependentSizedExtVectorType>
108 DependentSizedExtVectorTypes;
109 mutable llvm::FoldingSet<VectorType> VectorTypes;
110 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
111 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
113 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
114 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
115 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
116 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
117 SubstTemplateTypeParmTypes;
118 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
119 SubstTemplateTypeParmPackTypes;
120 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
121 TemplateSpecializationTypes;
122 mutable llvm::FoldingSet<ParenType> ParenTypes;
123 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
124 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
125 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
127 DependentTemplateSpecializationTypes;
128 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
129 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
130 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
131 mutable llvm::FoldingSet<AutoType> AutoTypes;
132 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
133 llvm::FoldingSet<AttributedType> AttributedTypes;
134 mutable llvm::FoldingSet<PipeType> PipeTypes;
136 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
137 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
138 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
139 SubstTemplateTemplateParms;
140 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
142 SubstTemplateTemplateParmPacks;
144 /// \brief The set of nested name specifiers.
146 /// This set is managed by the NestedNameSpecifier class.
147 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
148 mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
149 friend class NestedNameSpecifier;
151 /// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
153 /// This is lazily created. This is intentionally not serialized.
154 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
156 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
159 /// \brief A cache from types to size and alignment information.
160 typedef llvm::DenseMap<const Type *, struct TypeInfo> TypeInfoMap;
161 mutable TypeInfoMap MemoizedTypeInfo;
163 /// \brief A cache mapping from CXXRecordDecls to key functions.
164 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
166 /// \brief Mapping from ObjCContainers to their ObjCImplementations.
167 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
169 /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
171 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
173 /// \brief Mapping from __block VarDecls to their copy initialization expr.
174 llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
176 /// \brief Mapping from class scope functions specialization to their
177 /// template patterns.
178 llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
179 ClassScopeSpecializationPattern;
181 /// \brief Mapping from materialized temporaries with static storage duration
182 /// that appear in constant initializers to their evaluated values. These are
183 /// allocated in a std::map because their address must be stable.
184 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue *>
185 MaterializedTemporaryValues;
187 /// \brief Representation of a "canonical" template template parameter that
188 /// is used in canonical template names.
189 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
190 TemplateTemplateParmDecl *Parm;
193 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
196 TemplateTemplateParmDecl *getParam() const { return Parm; }
198 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
200 static void Profile(llvm::FoldingSetNodeID &ID,
201 TemplateTemplateParmDecl *Parm);
203 mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
204 CanonTemplateTemplateParms;
206 TemplateTemplateParmDecl *
207 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
209 /// \brief The typedef for the __int128_t type.
210 mutable TypedefDecl *Int128Decl;
212 /// \brief The typedef for the __uint128_t type.
213 mutable TypedefDecl *UInt128Decl;
215 /// \brief The typedef for the __float128 stub type.
216 mutable TypeDecl *Float128StubDecl;
218 /// \brief The typedef for the target specific predefined
219 /// __builtin_va_list type.
220 mutable TypedefDecl *BuiltinVaListDecl;
222 /// The typedef for the predefined \c __builtin_ms_va_list type.
223 mutable TypedefDecl *BuiltinMSVaListDecl;
225 /// \brief The typedef for the predefined \c id type.
226 mutable TypedefDecl *ObjCIdDecl;
228 /// \brief The typedef for the predefined \c SEL type.
229 mutable TypedefDecl *ObjCSelDecl;
231 /// \brief The typedef for the predefined \c Class type.
232 mutable TypedefDecl *ObjCClassDecl;
234 /// \brief The typedef for the predefined \c Protocol class in Objective-C.
235 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
237 /// \brief The typedef for the predefined 'BOOL' type.
238 mutable TypedefDecl *BOOLDecl;
240 // Typedefs which may be provided defining the structure of Objective-C
242 QualType ObjCIdRedefinitionType;
243 QualType ObjCClassRedefinitionType;
244 QualType ObjCSelRedefinitionType;
246 /// The identifier 'NSObject'.
247 IdentifierInfo *NSObjectName = nullptr;
249 /// The identifier 'NSCopying'.
250 IdentifierInfo *NSCopyingName = nullptr;
252 /// The identifier '__make_integer_seq'.
253 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
255 QualType ObjCConstantStringType;
256 mutable RecordDecl *CFConstantStringTypeDecl;
258 mutable QualType ObjCSuperType;
260 QualType ObjCNSStringType;
262 /// \brief The typedef declaration for the Objective-C "instancetype" type.
263 TypedefDecl *ObjCInstanceTypeDecl;
265 /// \brief The type for the C FILE type.
268 /// \brief The type for the C jmp_buf type.
269 TypeDecl *jmp_bufDecl;
271 /// \brief The type for the C sigjmp_buf type.
272 TypeDecl *sigjmp_bufDecl;
274 /// \brief The type for the C ucontext_t type.
275 TypeDecl *ucontext_tDecl;
277 /// \brief Type for the Block descriptor for Blocks CodeGen.
279 /// Since this is only used for generation of debug info, it is not
281 mutable RecordDecl *BlockDescriptorType;
283 /// \brief Type for the Block descriptor for Blocks CodeGen.
285 /// Since this is only used for generation of debug info, it is not
287 mutable RecordDecl *BlockDescriptorExtendedType;
289 /// \brief Declaration for the CUDA cudaConfigureCall function.
290 FunctionDecl *cudaConfigureCallDecl;
292 /// \brief Keeps track of all declaration attributes.
294 /// Since so few decls have attrs, we keep them in a hash map instead of
295 /// wasting space in the Decl class.
296 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
298 /// \brief A mapping from non-redeclarable declarations in modules that were
299 /// merged with other declarations to the canonical declaration that they were
301 llvm::DenseMap<Decl*, Decl*> MergedDecls;
303 /// \brief A mapping from a defining declaration to a list of modules (other
304 /// than the owning module of the declaration) that contain merged
305 /// definitions of that entity.
306 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
309 /// \brief A type synonym for the TemplateOrInstantiation mapping.
310 typedef llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>
311 TemplateOrSpecializationInfo;
315 /// \brief A mapping to contain the template or declaration that
316 /// a variable declaration describes or was instantiated from,
319 /// For non-templates, this value will be NULL. For variable
320 /// declarations that describe a variable template, this will be a
321 /// pointer to a VarTemplateDecl. For static data members
322 /// of class template specializations, this will be the
323 /// MemberSpecializationInfo referring to the member variable that was
324 /// instantiated or specialized. Thus, the mapping will keep track of
325 /// the static data member templates from which static data members of
326 /// class template specializations were instantiated.
328 /// Given the following example:
331 /// template<typename T>
336 /// template<typename T>
337 /// T X<T>::value = T(17);
339 /// int *x = &X<int>::value;
342 /// This mapping will contain an entry that maps from the VarDecl for
343 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
344 /// class template X) and will be marked TSK_ImplicitInstantiation.
345 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
346 TemplateOrInstantiation;
348 /// \brief Keeps track of the declaration from which a UsingDecl was
349 /// created during instantiation.
351 /// The source declaration is always a UsingDecl, an UnresolvedUsingValueDecl,
352 /// or an UnresolvedUsingTypenameDecl.
356 /// template<typename T>
361 /// template<typename T>
362 /// struct B : A<T> {
366 /// template struct B<int>;
369 /// This mapping will contain an entry that maps from the UsingDecl in
370 /// B<int> to the UnresolvedUsingDecl in B<T>.
371 llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
373 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
374 InstantiatedFromUsingShadowDecl;
376 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
378 /// \brief Mapping that stores the methods overridden by a given C++
381 /// Since most C++ member functions aren't virtual and therefore
382 /// don't override anything, we store the overridden functions in
383 /// this map on the side rather than within the CXXMethodDecl structure.
384 typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
385 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
387 /// \brief Mapping from each declaration context to its corresponding
388 /// mangling numbering context (used for constructs like lambdas which
389 /// need to be consistently numbered for the mangler).
390 llvm::DenseMap<const DeclContext *, MangleNumberingContext *>
391 MangleNumberingContexts;
393 /// \brief Side-table of mangling numbers for declarations which rarely
394 /// need them (like static local vars).
395 llvm::DenseMap<const NamedDecl *, unsigned> MangleNumbers;
396 llvm::DenseMap<const VarDecl *, unsigned> StaticLocalNumbers;
398 /// \brief Mapping that stores parameterIndex values for ParmVarDecls when
399 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
400 typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
401 ParameterIndexTable ParamIndices;
403 ImportDecl *FirstLocalImport;
404 ImportDecl *LastLocalImport;
406 TranslationUnitDecl *TUDecl;
407 mutable ExternCContextDecl *ExternCContext;
408 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl;
410 /// \brief The associated SourceManager object.a
411 SourceManager &SourceMgr;
413 /// \brief The language options used to create the AST associated with
414 /// this ASTContext object.
415 LangOptions &LangOpts;
417 /// \brief Blacklist object that is used by sanitizers to decide which
418 /// entities should not be instrumented.
419 std::unique_ptr<SanitizerBlacklist> SanitizerBL;
421 /// \brief The allocator used to create AST objects.
423 /// AST objects are never destructed; rather, all memory associated with the
424 /// AST objects will be released when the ASTContext itself is destroyed.
425 mutable llvm::BumpPtrAllocator BumpAlloc;
427 /// \brief Allocator for partial diagnostics.
428 PartialDiagnostic::StorageAllocator DiagAllocator;
430 /// \brief The current C++ ABI.
431 std::unique_ptr<CXXABI> ABI;
432 CXXABI *createCXXABI(const TargetInfo &T);
434 /// \brief The logical -> physical address space map.
435 const LangAS::Map *AddrSpaceMap;
437 /// \brief Address space map mangling must be used with language specific
438 /// address spaces (e.g. OpenCL/CUDA)
439 bool AddrSpaceMapMangling;
441 friend class ASTDeclReader;
442 friend class ASTReader;
443 friend class ASTWriter;
444 friend class CXXRecordDecl;
446 const TargetInfo *Target;
447 const TargetInfo *AuxTarget;
448 clang::PrintingPolicy PrintingPolicy;
451 IdentifierTable &Idents;
452 SelectorTable &Selectors;
453 Builtin::Context &BuiltinInfo;
454 mutable DeclarationNameTable DeclarationNames;
455 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
456 ASTMutationListener *Listener;
458 /// \brief Contains parents of a node.
459 typedef llvm::SmallVector<ast_type_traits::DynTypedNode, 2> ParentVector;
461 /// \brief Maps from a node to its parents. This is used for nodes that have
462 /// pointer identity only, which are more common and we can save space by
463 /// only storing a unique pointer to them.
464 typedef llvm::DenseMap<const void *,
465 llvm::PointerUnion4<const Decl *, const Stmt *,
466 ast_type_traits::DynTypedNode *,
467 ParentVector *>> ParentMapPointers;
469 /// Parent map for nodes without pointer identity. We store a full
470 /// DynTypedNode for all keys.
471 typedef llvm::DenseMap<
472 ast_type_traits::DynTypedNode,
473 llvm::PointerUnion4<const Decl *, const Stmt *,
474 ast_type_traits::DynTypedNode *, ParentVector *>>
477 /// Container for either a single DynTypedNode or for an ArrayRef to
478 /// DynTypedNode. For use with ParentMap.
479 class DynTypedNodeList {
480 typedef ast_type_traits::DynTypedNode DynTypedNode;
481 llvm::AlignedCharArrayUnion<ast_type_traits::DynTypedNode,
482 ArrayRef<DynTypedNode>> Storage;
486 DynTypedNodeList(const DynTypedNode &N) : IsSingleNode(true) {
487 new (Storage.buffer) DynTypedNode(N);
489 DynTypedNodeList(ArrayRef<DynTypedNode> A) : IsSingleNode(false) {
490 new (Storage.buffer) ArrayRef<DynTypedNode>(A);
493 const ast_type_traits::DynTypedNode *begin() const {
495 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
497 return reinterpret_cast<const DynTypedNode *>(Storage.buffer);
500 const ast_type_traits::DynTypedNode *end() const {
502 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
504 return reinterpret_cast<const DynTypedNode *>(Storage.buffer) + 1;
507 size_t size() const { return end() - begin(); }
508 bool empty() const { return begin() == end(); }
509 const DynTypedNode &operator[](size_t N) const {
510 assert(N < size() && "Out of bounds!");
511 return *(begin() + N);
515 /// \brief Returns the parents of the given node.
517 /// Note that this will lazily compute the parents of all nodes
518 /// and store them for later retrieval. Thus, the first call is O(n)
519 /// in the number of AST nodes.
521 /// Caveats and FIXMEs:
522 /// Calculating the parent map over all AST nodes will need to load the
523 /// full AST. This can be undesirable in the case where the full AST is
524 /// expensive to create (for example, when using precompiled header
525 /// preambles). Thus, there are good opportunities for optimization here.
526 /// One idea is to walk the given node downwards, looking for references
527 /// to declaration contexts - once a declaration context is found, compute
528 /// the parent map for the declaration context; if that can satisfy the
529 /// request, loading the whole AST can be avoided. Note that this is made
530 /// more complex by statements in templates having multiple parents - those
531 /// problems can be solved by building closure over the templated parts of
532 /// the AST, which also avoids touching large parts of the AST.
533 /// Additionally, we will want to add an interface to already give a hint
534 /// where to search for the parents, for example when looking at a statement
535 /// inside a certain function.
537 /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
538 /// NestedNameSpecifier or NestedNameSpecifierLoc.
539 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node) {
540 return getParents(ast_type_traits::DynTypedNode::create(Node));
543 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node);
545 const clang::PrintingPolicy &getPrintingPolicy() const {
546 return PrintingPolicy;
549 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
550 PrintingPolicy = Policy;
553 SourceManager& getSourceManager() { return SourceMgr; }
554 const SourceManager& getSourceManager() const { return SourceMgr; }
556 llvm::BumpPtrAllocator &getAllocator() const {
560 void *Allocate(size_t Size, unsigned Align = 8) const {
561 return BumpAlloc.Allocate(Size, Align);
563 template <typename T> T *Allocate(size_t Num = 1) const {
564 return static_cast<T *>(Allocate(Num * sizeof(T), llvm::alignOf<T>()));
566 void Deallocate(void *Ptr) const { }
568 /// Return the total amount of physical memory allocated for representing
569 /// AST nodes and type information.
570 size_t getASTAllocatedMemory() const {
571 return BumpAlloc.getTotalMemory();
573 /// Return the total memory used for various side tables.
574 size_t getSideTableAllocatedMemory() const;
576 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
577 return DiagAllocator;
580 const TargetInfo &getTargetInfo() const { return *Target; }
581 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
583 /// getIntTypeForBitwidth -
584 /// sets integer QualTy according to specified details:
585 /// bitwidth, signed/unsigned.
586 /// Returns empty type if there is no appropriate target types.
587 QualType getIntTypeForBitwidth(unsigned DestWidth,
588 unsigned Signed) const;
589 /// getRealTypeForBitwidth -
590 /// sets floating point QualTy according to specified bitwidth.
591 /// Returns empty type if there is no appropriate target types.
592 QualType getRealTypeForBitwidth(unsigned DestWidth) const;
594 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
596 const LangOptions& getLangOpts() const { return LangOpts; }
598 const SanitizerBlacklist &getSanitizerBlacklist() const {
602 DiagnosticsEngine &getDiagnostics() const;
604 FullSourceLoc getFullLoc(SourceLocation Loc) const {
605 return FullSourceLoc(Loc,SourceMgr);
608 /// \brief All comments in this translation unit.
609 RawCommentList Comments;
611 /// \brief True if comments are already loaded from ExternalASTSource.
612 mutable bool CommentsLoaded;
614 class RawCommentAndCacheFlags {
617 /// We searched for a comment attached to the particular declaration, but
623 /// We have found a comment attached to this particular declaration.
628 /// This declaration does not have an attached comment, and we have
629 /// searched the redeclaration chain.
631 /// If getRaw() == 0, the whole redeclaration chain does not have any
634 /// If getRaw() != 0, it is a comment propagated from other
639 Kind getKind() const LLVM_READONLY {
640 return Data.getInt();
643 void setKind(Kind K) {
647 const RawComment *getRaw() const LLVM_READONLY {
648 return Data.getPointer();
651 void setRaw(const RawComment *RC) {
655 const Decl *getOriginalDecl() const LLVM_READONLY {
659 void setOriginalDecl(const Decl *Orig) {
664 llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
665 const Decl *OriginalDecl;
668 /// \brief Mapping from declarations to comments attached to any
671 /// Raw comments are owned by Comments list. This mapping is populated
673 mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
675 /// \brief Mapping from declarations to parsed comments attached to any
677 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
679 /// \brief Return the documentation comment attached to a given declaration,
680 /// without looking into cache.
681 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
684 RawCommentList &getRawCommentList() {
688 void addComment(const RawComment &RC) {
689 assert(LangOpts.RetainCommentsFromSystemHeaders ||
690 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
691 Comments.addComment(RC, BumpAlloc);
694 /// \brief Return the documentation comment attached to a given declaration.
695 /// Returns NULL if no comment is attached.
697 /// \param OriginalDecl if not NULL, is set to declaration AST node that had
698 /// the comment, if the comment we found comes from a redeclaration.
700 getRawCommentForAnyRedecl(const Decl *D,
701 const Decl **OriginalDecl = nullptr) const;
703 /// Return parsed documentation comment attached to a given declaration.
704 /// Returns NULL if no comment is attached.
706 /// \param PP the Preprocessor used with this TU. Could be NULL if
707 /// preprocessor is not available.
708 comments::FullComment *getCommentForDecl(const Decl *D,
709 const Preprocessor *PP) const;
711 /// Return parsed documentation comment attached to a given declaration.
712 /// Returns NULL if no comment is attached. Does not look at any
713 /// redeclarations of the declaration.
714 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
716 comments::FullComment *cloneFullComment(comments::FullComment *FC,
717 const Decl *D) const;
720 mutable comments::CommandTraits CommentCommandTraits;
722 /// \brief Iterator that visits import declarations.
723 class import_iterator {
727 typedef ImportDecl *value_type;
728 typedef ImportDecl *reference;
729 typedef ImportDecl *pointer;
730 typedef int difference_type;
731 typedef std::forward_iterator_tag iterator_category;
733 import_iterator() : Import() {}
734 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
736 reference operator*() const { return Import; }
737 pointer operator->() const { return Import; }
739 import_iterator &operator++() {
740 Import = ASTContext::getNextLocalImport(Import);
744 import_iterator operator++(int) {
745 import_iterator Other(*this);
750 friend bool operator==(import_iterator X, import_iterator Y) {
751 return X.Import == Y.Import;
754 friend bool operator!=(import_iterator X, import_iterator Y) {
755 return X.Import != Y.Import;
760 comments::CommandTraits &getCommentCommandTraits() const {
761 return CommentCommandTraits;
764 /// \brief Retrieve the attributes for the given declaration.
765 AttrVec& getDeclAttrs(const Decl *D);
767 /// \brief Erase the attributes corresponding to the given declaration.
768 void eraseDeclAttrs(const Decl *D);
770 /// \brief If this variable is an instantiated static data member of a
771 /// class template specialization, returns the templated static data member
772 /// from which it was instantiated.
774 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
777 TemplateOrSpecializationInfo
778 getTemplateOrSpecializationInfo(const VarDecl *Var);
780 FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
782 void setClassScopeSpecializationPattern(FunctionDecl *FD,
783 FunctionDecl *Pattern);
785 /// \brief Note that the static data member \p Inst is an instantiation of
786 /// the static data member template \p Tmpl of a class template.
787 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
788 TemplateSpecializationKind TSK,
789 SourceLocation PointOfInstantiation = SourceLocation());
791 void setTemplateOrSpecializationInfo(VarDecl *Inst,
792 TemplateOrSpecializationInfo TSI);
794 /// \brief If the given using decl \p Inst is an instantiation of a
795 /// (possibly unresolved) using decl from a template instantiation,
797 NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
799 /// \brief Remember that the using decl \p Inst is an instantiation
800 /// of the using decl \p Pattern of a class template.
801 void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
803 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
804 UsingShadowDecl *Pattern);
805 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
807 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
809 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
811 // Access to the set of methods overridden by the given C++ method.
812 typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
813 overridden_cxx_method_iterator
814 overridden_methods_begin(const CXXMethodDecl *Method) const;
816 overridden_cxx_method_iterator
817 overridden_methods_end(const CXXMethodDecl *Method) const;
819 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
821 /// \brief Note that the given C++ \p Method overrides the given \p
822 /// Overridden method.
823 void addOverriddenMethod(const CXXMethodDecl *Method,
824 const CXXMethodDecl *Overridden);
826 /// \brief Return C++ or ObjC overridden methods for the given \p Method.
828 /// An ObjC method is considered to override any method in the class's
829 /// base classes, its protocols, or its categories' protocols, that has
830 /// the same selector and is of the same kind (class or instance).
831 /// A method in an implementation is not considered as overriding the same
832 /// method in the interface or its categories.
833 void getOverriddenMethods(
834 const NamedDecl *Method,
835 SmallVectorImpl<const NamedDecl *> &Overridden) const;
837 /// \brief Notify the AST context that a new import declaration has been
838 /// parsed or implicitly created within this translation unit.
839 void addedLocalImportDecl(ImportDecl *Import);
841 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
842 return Import->NextLocalImport;
845 typedef llvm::iterator_range<import_iterator> import_range;
846 import_range local_imports() const {
847 return import_range(import_iterator(FirstLocalImport), import_iterator());
850 Decl *getPrimaryMergedDecl(Decl *D) {
851 Decl *Result = MergedDecls.lookup(D);
852 return Result ? Result : D;
854 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
855 MergedDecls[D] = Primary;
858 /// \brief Note that the definition \p ND has been merged into module \p M,
859 /// and should be visible whenever \p M is visible.
860 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
861 bool NotifyListeners = true);
862 /// \brief Clean up the merged definition list. Call this if you might have
863 /// added duplicates into the list.
864 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
866 /// \brief Get the additional modules in which the definition \p Def has
868 ArrayRef<Module*> getModulesWithMergedDefinition(NamedDecl *Def) {
869 auto MergedIt = MergedDefModules.find(Def);
870 if (MergedIt == MergedDefModules.end())
872 return MergedIt->second;
875 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
877 ExternCContextDecl *getExternCContextDecl() const;
878 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
884 CanQualType WCharTy; // [C++ 3.9.1p5].
885 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
886 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
887 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
888 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
889 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
890 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
891 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
892 CanQualType FloatTy, DoubleTy, LongDoubleTy;
893 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
894 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
895 CanQualType VoidPtrTy, NullPtrTy;
896 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
897 CanQualType BuiltinFnTy;
898 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
899 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
900 CanQualType ObjCBuiltinBoolTy;
901 CanQualType OCLImage1dTy, OCLImage1dArrayTy, OCLImage1dBufferTy;
902 CanQualType OCLImage2dTy, OCLImage2dArrayTy, OCLImage2dDepthTy;
903 CanQualType OCLImage2dArrayDepthTy, OCLImage2dMSAATy, OCLImage2dArrayMSAATy;
904 CanQualType OCLImage2dMSAADepthTy, OCLImage2dArrayMSAADepthTy;
905 CanQualType OCLImage3dTy;
906 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
907 CanQualType OCLQueueTy, OCLNDRangeTy, OCLReserveIDTy;
908 CanQualType OMPArraySectionTy;
910 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
911 mutable QualType AutoDeductTy; // Deduction against 'auto'.
912 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
914 // Decl used to help define __builtin_va_list for some targets.
915 // The decl is built when constructing 'BuiltinVaListDecl'.
916 mutable Decl *VaListTagDecl;
918 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
919 SelectorTable &sels, Builtin::Context &builtins);
923 /// \brief Attach an external AST source to the AST context.
925 /// The external AST source provides the ability to load parts of
926 /// the abstract syntax tree as needed from some external storage,
927 /// e.g., a precompiled header.
928 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
930 /// \brief Retrieve a pointer to the external AST source associated
931 /// with this AST context, if any.
932 ExternalASTSource *getExternalSource() const {
933 return ExternalSource.get();
936 /// \brief Attach an AST mutation listener to the AST context.
938 /// The AST mutation listener provides the ability to track modifications to
939 /// the abstract syntax tree entities committed after they were initially
941 void setASTMutationListener(ASTMutationListener *Listener) {
942 this->Listener = Listener;
945 /// \brief Retrieve a pointer to the AST mutation listener associated
946 /// with this AST context, if any.
947 ASTMutationListener *getASTMutationListener() const { return Listener; }
949 void PrintStats() const;
950 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
952 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
953 const IdentifierInfo *II) const;
955 /// \brief Create a new implicit TU-level CXXRecordDecl or RecordDecl
957 RecordDecl *buildImplicitRecord(StringRef Name,
958 RecordDecl::TagKind TK = TTK_Struct) const;
960 /// \brief Create a new implicit TU-level typedef declaration.
961 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
963 /// \brief Retrieve the declaration for the 128-bit signed integer type.
964 TypedefDecl *getInt128Decl() const;
966 /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
967 TypedefDecl *getUInt128Decl() const;
969 /// \brief Retrieve the declaration for a 128-bit float stub type.
970 TypeDecl *getFloat128StubType() const;
972 //===--------------------------------------------------------------------===//
974 //===--------------------------------------------------------------------===//
977 /// \brief Return a type with extended qualifiers.
978 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
980 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
983 /// \brief Return the uniqued reference to the type for an address space
984 /// qualified type with the specified type and address space.
986 /// The resulting type has a union of the qualifiers from T and the address
987 /// space. If T already has an address space specifier, it is silently
989 QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
991 /// \brief Return the uniqued reference to the type for an Objective-C
992 /// gc-qualified type.
994 /// The retulting type has a union of the qualifiers from T and the gc
996 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
998 /// \brief Return the uniqued reference to the type for a \c restrict
1001 /// The resulting type has a union of the qualifiers from \p T and
1003 QualType getRestrictType(QualType T) const {
1004 return T.withFastQualifiers(Qualifiers::Restrict);
1007 /// \brief Return the uniqued reference to the type for a \c volatile
1010 /// The resulting type has a union of the qualifiers from \p T and
1012 QualType getVolatileType(QualType T) const {
1013 return T.withFastQualifiers(Qualifiers::Volatile);
1016 /// \brief Return the uniqued reference to the type for a \c const
1019 /// The resulting type has a union of the qualifiers from \p T and \c const.
1021 /// It can be reasonably expected that this will always be equivalent to
1022 /// calling T.withConst().
1023 QualType getConstType(QualType T) const { return T.withConst(); }
1025 /// \brief Change the ExtInfo on a function type.
1026 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1027 FunctionType::ExtInfo EInfo);
1029 /// Adjust the given function result type.
1030 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1032 /// \brief Change the result type of a function type once it is deduced.
1033 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1035 /// \brief Change the exception specification on a function once it is
1036 /// delay-parsed, instantiated, or computed.
1037 void adjustExceptionSpec(FunctionDecl *FD,
1038 const FunctionProtoType::ExceptionSpecInfo &ESI,
1039 bool AsWritten = false);
1041 /// \brief Return the uniqued reference to the type for a complex
1042 /// number with the specified element type.
1043 QualType getComplexType(QualType T) const;
1044 CanQualType getComplexType(CanQualType T) const {
1045 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1048 /// \brief Return the uniqued reference to the type for a pointer to
1049 /// the specified type.
1050 QualType getPointerType(QualType T) const;
1051 CanQualType getPointerType(CanQualType T) const {
1052 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1055 /// \brief Return the uniqued reference to a type adjusted from the original
1056 /// type to a new type.
1057 QualType getAdjustedType(QualType Orig, QualType New) const;
1058 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1059 return CanQualType::CreateUnsafe(
1060 getAdjustedType((QualType)Orig, (QualType)New));
1063 /// \brief Return the uniqued reference to the decayed version of the given
1064 /// type. Can only be called on array and function types which decay to
1066 QualType getDecayedType(QualType T) const;
1067 CanQualType getDecayedType(CanQualType T) const {
1068 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1071 /// \brief Return the uniqued reference to the atomic type for the specified
1073 QualType getAtomicType(QualType T) const;
1075 /// \brief Return the uniqued reference to the type for a block of the
1077 QualType getBlockPointerType(QualType T) const;
1079 /// Gets the struct used to keep track of the descriptor for pointer to
1081 QualType getBlockDescriptorType() const;
1083 /// \brief Return pipe type for the specified type.
1084 QualType getPipeType(QualType T) const;
1086 /// Gets the struct used to keep track of the extended descriptor for
1087 /// pointer to blocks.
1088 QualType getBlockDescriptorExtendedType() const;
1090 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1091 cudaConfigureCallDecl = FD;
1093 FunctionDecl *getcudaConfigureCallDecl() {
1094 return cudaConfigureCallDecl;
1097 /// Returns true iff we need copy/dispose helpers for the given type.
1098 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1101 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set
1102 /// to false in this case. If HasByrefExtendedLayout returns true, byref variable
1103 /// has extended lifetime.
1104 bool getByrefLifetime(QualType Ty,
1105 Qualifiers::ObjCLifetime &Lifetime,
1106 bool &HasByrefExtendedLayout) const;
1108 /// \brief Return the uniqued reference to the type for an lvalue reference
1109 /// to the specified type.
1110 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1113 /// \brief Return the uniqued reference to the type for an rvalue reference
1114 /// to the specified type.
1115 QualType getRValueReferenceType(QualType T) const;
1117 /// \brief Return the uniqued reference to the type for a member pointer to
1118 /// the specified type in the specified class.
1120 /// The class \p Cls is a \c Type because it could be a dependent name.
1121 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1123 /// \brief Return a non-unique reference to the type for a variable array of
1124 /// the specified element type.
1125 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1126 ArrayType::ArraySizeModifier ASM,
1127 unsigned IndexTypeQuals,
1128 SourceRange Brackets) const;
1130 /// \brief Return a non-unique reference to the type for a dependently-sized
1131 /// array of the specified element type.
1133 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1135 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1136 ArrayType::ArraySizeModifier ASM,
1137 unsigned IndexTypeQuals,
1138 SourceRange Brackets) const;
1140 /// \brief Return a unique reference to the type for an incomplete array of
1141 /// the specified element type.
1142 QualType getIncompleteArrayType(QualType EltTy,
1143 ArrayType::ArraySizeModifier ASM,
1144 unsigned IndexTypeQuals) const;
1146 /// \brief Return the unique reference to the type for a constant array of
1147 /// the specified element type.
1148 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1149 ArrayType::ArraySizeModifier ASM,
1150 unsigned IndexTypeQuals) const;
1152 /// \brief Returns a vla type where known sizes are replaced with [*].
1153 QualType getVariableArrayDecayedType(QualType Ty) const;
1155 /// \brief Return the unique reference to a vector type of the specified
1156 /// element type and size.
1158 /// \pre \p VectorType must be a built-in type.
1159 QualType getVectorType(QualType VectorType, unsigned NumElts,
1160 VectorType::VectorKind VecKind) const;
1162 /// \brief Return the unique reference to an extended vector type
1163 /// of the specified element type and size.
1165 /// \pre \p VectorType must be a built-in type.
1166 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1168 /// \pre Return a non-unique reference to the type for a dependently-sized
1169 /// vector of the specified element type.
1171 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1173 QualType getDependentSizedExtVectorType(QualType VectorType,
1175 SourceLocation AttrLoc) const;
1177 /// \brief Return a K&R style C function type like 'int()'.
1178 QualType getFunctionNoProtoType(QualType ResultTy,
1179 const FunctionType::ExtInfo &Info) const;
1181 QualType getFunctionNoProtoType(QualType ResultTy) const {
1182 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1185 /// \brief Return a normal function type with a typed argument list.
1186 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1187 const FunctionProtoType::ExtProtoInfo &EPI) const;
1189 /// \brief Return the unique reference to the type for the specified type
1191 QualType getTypeDeclType(const TypeDecl *Decl,
1192 const TypeDecl *PrevDecl = nullptr) const {
1193 assert(Decl && "Passed null for Decl param");
1194 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1197 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1198 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1199 return QualType(PrevDecl->TypeForDecl, 0);
1202 return getTypeDeclTypeSlow(Decl);
1205 /// \brief Return the unique reference to the type for the specified
1206 /// typedef-name decl.
1207 QualType getTypedefType(const TypedefNameDecl *Decl,
1208 QualType Canon = QualType()) const;
1210 QualType getRecordType(const RecordDecl *Decl) const;
1212 QualType getEnumType(const EnumDecl *Decl) const;
1214 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1216 QualType getAttributedType(AttributedType::Kind attrKind,
1217 QualType modifiedType,
1218 QualType equivalentType);
1220 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1221 QualType Replacement) const;
1222 QualType getSubstTemplateTypeParmPackType(
1223 const TemplateTypeParmType *Replaced,
1224 const TemplateArgument &ArgPack);
1227 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1229 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1231 QualType getTemplateSpecializationType(TemplateName T,
1232 const TemplateArgument *Args,
1234 QualType Canon = QualType()) const;
1236 QualType getCanonicalTemplateSpecializationType(TemplateName T,
1237 const TemplateArgument *Args,
1238 unsigned NumArgs) const;
1240 QualType getTemplateSpecializationType(TemplateName T,
1241 const TemplateArgumentListInfo &Args,
1242 QualType Canon = QualType()) const;
1245 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1246 const TemplateArgumentListInfo &Args,
1247 QualType Canon = QualType()) const;
1249 QualType getParenType(QualType NamedType) const;
1251 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1252 NestedNameSpecifier *NNS,
1253 QualType NamedType) const;
1254 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1255 NestedNameSpecifier *NNS,
1256 const IdentifierInfo *Name,
1257 QualType Canon = QualType()) const;
1259 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1260 NestedNameSpecifier *NNS,
1261 const IdentifierInfo *Name,
1262 const TemplateArgumentListInfo &Args) const;
1263 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1264 NestedNameSpecifier *NNS,
1265 const IdentifierInfo *Name,
1267 const TemplateArgument *Args) const;
1269 QualType getPackExpansionType(QualType Pattern,
1270 Optional<unsigned> NumExpansions);
1272 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1273 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1275 /// Legacy interface: cannot provide type arguments or __kindof.
1276 QualType getObjCObjectType(QualType Base,
1277 ObjCProtocolDecl * const *Protocols,
1278 unsigned NumProtocols) const;
1280 QualType getObjCObjectType(QualType Base,
1281 ArrayRef<QualType> typeArgs,
1282 ArrayRef<ObjCProtocolDecl *> protocols,
1283 bool isKindOf) const;
1285 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1286 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1287 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1289 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1290 ObjCInterfaceDecl *IDecl);
1292 /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1293 QualType getObjCObjectPointerType(QualType OIT) const;
1295 /// \brief GCC extension.
1296 QualType getTypeOfExprType(Expr *e) const;
1297 QualType getTypeOfType(QualType t) const;
1299 /// \brief C++11 decltype.
1300 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1302 /// \brief Unary type transforms
1303 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1304 UnaryTransformType::UTTKind UKind) const;
1306 /// \brief C++11 deduced auto type.
1307 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1308 bool IsDependent) const;
1310 /// \brief C++11 deduction pattern for 'auto' type.
1311 QualType getAutoDeductType() const;
1313 /// \brief C++11 deduction pattern for 'auto &&' type.
1314 QualType getAutoRRefDeductType() const;
1316 /// \brief Return the unique reference to the type for the specified TagDecl
1317 /// (struct/union/class/enum) decl.
1318 QualType getTagDeclType(const TagDecl *Decl) const;
1320 /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1323 /// The sizeof operator requires this (C99 6.5.3.4p4).
1324 CanQualType getSizeType() const;
1326 /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1328 CanQualType getIntMaxType() const;
1330 /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1332 CanQualType getUIntMaxType() const;
1334 /// \brief Return the unique wchar_t type available in C++ (and available as
1335 /// __wchar_t as a Microsoft extension).
1336 QualType getWCharType() const { return WCharTy; }
1338 /// \brief Return the type of wide characters. In C++, this returns the
1339 /// unique wchar_t type. In C99, this returns a type compatible with the type
1340 /// defined in <stddef.h> as defined by the target.
1341 QualType getWideCharType() const { return WideCharTy; }
1343 /// \brief Return the type of "signed wchar_t".
1345 /// Used when in C++, as a GCC extension.
1346 QualType getSignedWCharType() const;
1348 /// \brief Return the type of "unsigned wchar_t".
1350 /// Used when in C++, as a GCC extension.
1351 QualType getUnsignedWCharType() const;
1353 /// \brief In C99, this returns a type compatible with the type
1354 /// defined in <stddef.h> as defined by the target.
1355 QualType getWIntType() const { return WIntTy; }
1357 /// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4),
1358 /// as defined by the target.
1359 QualType getIntPtrType() const;
1361 /// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1362 /// as defined by the target.
1363 QualType getUIntPtrType() const;
1365 /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1366 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1367 QualType getPointerDiffType() const;
1369 /// \brief Return the unique type for "pid_t" defined in
1370 /// <sys/types.h>. We need this to compute the correct type for vfork().
1371 QualType getProcessIDType() const;
1373 /// \brief Return the C structure type used to represent constant CFStrings.
1374 QualType getCFConstantStringType() const;
1376 /// \brief Returns the C struct type for objc_super
1377 QualType getObjCSuperType() const;
1378 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1380 /// Get the structure type used to representation CFStrings, or NULL
1381 /// if it hasn't yet been built.
1382 QualType getRawCFConstantStringType() const {
1383 if (CFConstantStringTypeDecl)
1384 return getTagDeclType(CFConstantStringTypeDecl);
1387 void setCFConstantStringType(QualType T);
1389 // This setter/getter represents the ObjC type for an NSConstantString.
1390 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1391 QualType getObjCConstantStringInterface() const {
1392 return ObjCConstantStringType;
1395 QualType getObjCNSStringType() const {
1396 return ObjCNSStringType;
1399 void setObjCNSStringType(QualType T) {
1400 ObjCNSStringType = T;
1403 /// \brief Retrieve the type that \c id has been defined to, which may be
1404 /// different from the built-in \c id if \c id has been typedef'd.
1405 QualType getObjCIdRedefinitionType() const {
1406 if (ObjCIdRedefinitionType.isNull())
1407 return getObjCIdType();
1408 return ObjCIdRedefinitionType;
1411 /// \brief Set the user-written type that redefines \c id.
1412 void setObjCIdRedefinitionType(QualType RedefType) {
1413 ObjCIdRedefinitionType = RedefType;
1416 /// \brief Retrieve the type that \c Class has been defined to, which may be
1417 /// different from the built-in \c Class if \c Class has been typedef'd.
1418 QualType getObjCClassRedefinitionType() const {
1419 if (ObjCClassRedefinitionType.isNull())
1420 return getObjCClassType();
1421 return ObjCClassRedefinitionType;
1424 /// \brief Set the user-written type that redefines 'SEL'.
1425 void setObjCClassRedefinitionType(QualType RedefType) {
1426 ObjCClassRedefinitionType = RedefType;
1429 /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1430 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1431 QualType getObjCSelRedefinitionType() const {
1432 if (ObjCSelRedefinitionType.isNull())
1433 return getObjCSelType();
1434 return ObjCSelRedefinitionType;
1438 /// \brief Set the user-written type that redefines 'SEL'.
1439 void setObjCSelRedefinitionType(QualType RedefType) {
1440 ObjCSelRedefinitionType = RedefType;
1443 /// Retrieve the identifier 'NSObject'.
1444 IdentifierInfo *getNSObjectName() {
1445 if (!NSObjectName) {
1446 NSObjectName = &Idents.get("NSObject");
1449 return NSObjectName;
1452 /// Retrieve the identifier 'NSCopying'.
1453 IdentifierInfo *getNSCopyingName() {
1454 if (!NSCopyingName) {
1455 NSCopyingName = &Idents.get("NSCopying");
1458 return NSCopyingName;
1461 IdentifierInfo *getMakeIntegerSeqName() const {
1462 if (!MakeIntegerSeqName)
1463 MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1464 return MakeIntegerSeqName;
1467 /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1468 /// otherwise, returns a NULL type;
1469 QualType getObjCInstanceType() {
1470 return getTypeDeclType(getObjCInstanceTypeDecl());
1473 /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1474 /// "instancetype" type.
1475 TypedefDecl *getObjCInstanceTypeDecl();
1477 /// \brief Set the type for the C FILE type.
1478 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1480 /// \brief Retrieve the C FILE type.
1481 QualType getFILEType() const {
1483 return getTypeDeclType(FILEDecl);
1487 /// \brief Set the type for the C jmp_buf type.
1488 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1489 this->jmp_bufDecl = jmp_bufDecl;
1492 /// \brief Retrieve the C jmp_buf type.
1493 QualType getjmp_bufType() const {
1495 return getTypeDeclType(jmp_bufDecl);
1499 /// \brief Set the type for the C sigjmp_buf type.
1500 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1501 this->sigjmp_bufDecl = sigjmp_bufDecl;
1504 /// \brief Retrieve the C sigjmp_buf type.
1505 QualType getsigjmp_bufType() const {
1507 return getTypeDeclType(sigjmp_bufDecl);
1511 /// \brief Set the type for the C ucontext_t type.
1512 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1513 this->ucontext_tDecl = ucontext_tDecl;
1516 /// \brief Retrieve the C ucontext_t type.
1517 QualType getucontext_tType() const {
1519 return getTypeDeclType(ucontext_tDecl);
1523 /// \brief The result type of logical operations, '<', '>', '!=', etc.
1524 QualType getLogicalOperationType() const {
1525 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1528 /// \brief Emit the Objective-CC type encoding for the given type \p T into
1531 /// If \p Field is specified then record field names are also encoded.
1532 void getObjCEncodingForType(QualType T, std::string &S,
1533 const FieldDecl *Field=nullptr,
1534 QualType *NotEncodedT=nullptr) const;
1536 /// \brief Emit the Objective-C property type encoding for the given
1537 /// type \p T into \p S.
1538 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1540 void getLegacyIntegralTypeEncoding(QualType &t) const;
1542 /// \brief Put the string version of the type qualifiers \p QT into \p S.
1543 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1544 std::string &S) const;
1546 /// \brief Emit the encoded type for the function \p Decl into \p S.
1548 /// This is in the same format as Objective-C method encodings.
1550 /// \returns true if an error occurred (e.g., because one of the parameter
1551 /// types is incomplete), false otherwise.
1552 bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1554 /// \brief Emit the encoded type for the method declaration \p Decl into
1557 /// \returns true if an error occurred (e.g., because one of the parameter
1558 /// types is incomplete), false otherwise.
1559 bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1560 bool Extended = false)
1563 /// \brief Return the encoded type for this block declaration.
1564 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1566 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1567 /// this method declaration. If non-NULL, Container must be either
1568 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1569 /// only be NULL when getting encodings for protocol properties.
1570 void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1571 const Decl *Container,
1572 std::string &S) const;
1574 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1575 ObjCProtocolDecl *rProto) const;
1577 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1578 const ObjCPropertyDecl *PD,
1579 const Decl *Container) const;
1581 /// \brief Return the size of type \p T for Objective-C encoding purpose,
1583 CharUnits getObjCEncodingTypeSize(QualType T) const;
1585 /// \brief Retrieve the typedef corresponding to the predefined \c id type
1587 TypedefDecl *getObjCIdDecl() const;
1589 /// \brief Represents the Objective-CC \c id type.
1591 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1592 /// pointer type, a pointer to a struct.
1593 QualType getObjCIdType() const {
1594 return getTypeDeclType(getObjCIdDecl());
1597 /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1599 TypedefDecl *getObjCSelDecl() const;
1601 /// \brief Retrieve the type that corresponds to the predefined Objective-C
1603 QualType getObjCSelType() const {
1604 return getTypeDeclType(getObjCSelDecl());
1607 /// \brief Retrieve the typedef declaration corresponding to the predefined
1608 /// Objective-C 'Class' type.
1609 TypedefDecl *getObjCClassDecl() const;
1611 /// \brief Represents the Objective-C \c Class type.
1613 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1614 /// pointer type, a pointer to a struct.
1615 QualType getObjCClassType() const {
1616 return getTypeDeclType(getObjCClassDecl());
1619 /// \brief Retrieve the Objective-C class declaration corresponding to
1620 /// the predefined \c Protocol class.
1621 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1623 /// \brief Retrieve declaration of 'BOOL' typedef
1624 TypedefDecl *getBOOLDecl() const {
1628 /// \brief Save declaration of 'BOOL' typedef
1629 void setBOOLDecl(TypedefDecl *TD) {
1633 /// \brief type of 'BOOL' type.
1634 QualType getBOOLType() const {
1635 return getTypeDeclType(getBOOLDecl());
1638 /// \brief Retrieve the type of the Objective-C \c Protocol class.
1639 QualType getObjCProtoType() const {
1640 return getObjCInterfaceType(getObjCProtocolDecl());
1643 /// \brief Retrieve the C type declaration corresponding to the predefined
1644 /// \c __builtin_va_list type.
1645 TypedefDecl *getBuiltinVaListDecl() const;
1647 /// \brief Retrieve the type of the \c __builtin_va_list type.
1648 QualType getBuiltinVaListType() const {
1649 return getTypeDeclType(getBuiltinVaListDecl());
1652 /// \brief Retrieve the C type declaration corresponding to the predefined
1653 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1654 /// for some targets.
1655 Decl *getVaListTagDecl() const;
1657 /// Retrieve the C type declaration corresponding to the predefined
1658 /// \c __builtin_ms_va_list type.
1659 TypedefDecl *getBuiltinMSVaListDecl() const;
1661 /// Retrieve the type of the \c __builtin_ms_va_list type.
1662 QualType getBuiltinMSVaListType() const {
1663 return getTypeDeclType(getBuiltinMSVaListDecl());
1666 /// \brief Return a type with additional \c const, \c volatile, or
1667 /// \c restrict qualifiers.
1668 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1669 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1672 /// \brief Un-split a SplitQualType.
1673 QualType getQualifiedType(SplitQualType split) const {
1674 return getQualifiedType(split.Ty, split.Quals);
1677 /// \brief Return a type with additional qualifiers.
1678 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1679 if (!Qs.hasNonFastQualifiers())
1680 return T.withFastQualifiers(Qs.getFastQualifiers());
1681 QualifierCollector Qc(Qs);
1682 const Type *Ptr = Qc.strip(T);
1683 return getExtQualType(Ptr, Qc);
1686 /// \brief Return a type with additional qualifiers.
1687 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1688 if (!Qs.hasNonFastQualifiers())
1689 return QualType(T, Qs.getFastQualifiers());
1690 return getExtQualType(T, Qs);
1693 /// \brief Return a type with the given lifetime qualifier.
1695 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1696 QualType getLifetimeQualifiedType(QualType type,
1697 Qualifiers::ObjCLifetime lifetime) {
1698 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1699 assert(lifetime != Qualifiers::OCL_None);
1702 qs.addObjCLifetime(lifetime);
1703 return getQualifiedType(type, qs);
1706 /// getUnqualifiedObjCPointerType - Returns version of
1707 /// Objective-C pointer type with lifetime qualifier removed.
1708 QualType getUnqualifiedObjCPointerType(QualType type) const {
1709 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1710 !type.getQualifiers().hasObjCLifetime())
1712 Qualifiers Qs = type.getQualifiers();
1713 Qs.removeObjCLifetime();
1714 return getQualifiedType(type.getUnqualifiedType(), Qs);
1717 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1718 SourceLocation NameLoc) const;
1720 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1721 UnresolvedSetIterator End) const;
1723 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1724 bool TemplateKeyword,
1725 TemplateDecl *Template) const;
1727 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1728 const IdentifierInfo *Name) const;
1729 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1730 OverloadedOperatorKind Operator) const;
1731 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1732 TemplateName replacement) const;
1733 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1734 const TemplateArgument &ArgPack) const;
1736 enum GetBuiltinTypeError {
1737 GE_None, ///< No error
1738 GE_Missing_stdio, ///< Missing a type from <stdio.h>
1739 GE_Missing_setjmp, ///< Missing a type from <setjmp.h>
1740 GE_Missing_ucontext ///< Missing a type from <ucontext.h>
1743 /// \brief Return the type for the specified builtin.
1745 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1746 /// arguments to the builtin that are required to be integer constant
1748 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1749 unsigned *IntegerConstantArgs = nullptr) const;
1752 CanQualType getFromTargetType(unsigned Type) const;
1753 TypeInfo getTypeInfoImpl(const Type *T) const;
1755 //===--------------------------------------------------------------------===//
1757 //===--------------------------------------------------------------------===//
1760 /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1761 /// collection attributes.
1762 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1764 /// \brief Return true if the given vector types are of the same unqualified
1765 /// type or if they are equivalent to the same GCC vector type.
1767 /// \note This ignores whether they are target-specific (AltiVec or Neon)
1769 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1771 /// \brief Return true if this is an \c NSObject object with its \c NSObject
1773 static bool isObjCNSObjectType(QualType Ty) {
1774 return Ty->isObjCNSObjectType();
1777 //===--------------------------------------------------------------------===//
1778 // Type Sizing and Analysis
1779 //===--------------------------------------------------------------------===//
1781 /// \brief Return the APFloat 'semantics' for the specified scalar floating
1783 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1785 /// \brief Get the size and alignment of the specified complete type in bits.
1786 TypeInfo getTypeInfo(const Type *T) const;
1787 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
1789 /// \brief Get default simd alignment of the specified complete type in bits.
1790 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
1792 /// \brief Return the size of the specified (complete) type \p T, in bits.
1793 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
1794 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
1796 /// \brief Return the size of the character type, in bits.
1797 uint64_t getCharWidth() const {
1798 return getTypeSize(CharTy);
1801 /// \brief Convert a size in bits to a size in characters.
1802 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1804 /// \brief Convert a size in characters to a size in bits.
1805 int64_t toBits(CharUnits CharSize) const;
1807 /// \brief Return the size of the specified (complete) type \p T, in
1809 CharUnits getTypeSizeInChars(QualType T) const;
1810 CharUnits getTypeSizeInChars(const Type *T) const;
1812 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1814 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
1815 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
1817 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1819 CharUnits getTypeAlignInChars(QualType T) const;
1820 CharUnits getTypeAlignInChars(const Type *T) const;
1822 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1823 // type is a record, its data size is returned.
1824 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1826 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1827 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1829 /// \brief Determine if the alignment the type has was required using an
1830 /// alignment attribute.
1831 bool isAlignmentRequired(const Type *T) const;
1832 bool isAlignmentRequired(QualType T) const;
1834 /// \brief Return the "preferred" alignment of the specified type \p T for
1835 /// the current target, in bits.
1837 /// This can be different than the ABI alignment in cases where it is
1838 /// beneficial for performance to overalign a data type.
1839 unsigned getPreferredTypeAlign(const Type *T) const;
1841 /// \brief Return the default alignment for __attribute__((aligned)) on
1842 /// this target, to be used if no alignment value is specified.
1843 unsigned getTargetDefaultAlignForAttributeAligned(void) const;
1845 /// \brief Return the alignment in bits that should be given to a
1846 /// global variable with type \p T.
1847 unsigned getAlignOfGlobalVar(QualType T) const;
1849 /// \brief Return the alignment in characters that should be given to a
1850 /// global variable with type \p T.
1851 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
1853 /// \brief Return a conservative estimate of the alignment of the specified
1856 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
1859 /// If \p ForAlignof, references are treated like their underlying type
1860 /// and large arrays don't get any special treatment. If not \p ForAlignof
1861 /// it computes the value expected by CodeGen: references are treated like
1862 /// pointers and large arrays get extra alignment.
1863 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
1865 /// \brief Get or compute information about the layout of the specified
1866 /// record (struct/union/class) \p D, which indicates its size and field
1867 /// position information.
1868 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1870 /// \brief Get or compute information about the layout of the specified
1871 /// Objective-C interface.
1872 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1875 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
1876 bool Simple = false) const;
1878 /// \brief Get or compute information about the layout of the specified
1879 /// Objective-C implementation.
1881 /// This may differ from the interface if synthesized ivars are present.
1882 const ASTRecordLayout &
1883 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1885 /// \brief Get our current best idea for the key function of the
1886 /// given record decl, or NULL if there isn't one.
1888 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
1889 /// ...the first non-pure virtual function that is not inline at the
1890 /// point of class definition.
1892 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
1893 /// virtual functions that are defined 'inline', which means that
1894 /// the result of this computation can change.
1895 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
1897 /// \brief Observe that the given method cannot be a key function.
1898 /// Checks the key-function cache for the method's class and clears it
1899 /// if matches the given declaration.
1901 /// This is used in ABIs where out-of-line definitions marked
1902 /// inline are not considered to be key functions.
1904 /// \param method should be the declaration from the class definition
1905 void setNonKeyFunction(const CXXMethodDecl *method);
1907 /// Loading virtual member pointers using the virtual inheritance model
1908 /// always results in an adjustment using the vbtable even if the index is
1911 /// This is usually OK because the first slot in the vbtable points
1912 /// backwards to the top of the MDC. However, the MDC might be reusing a
1913 /// vbptr from an nv-base. In this case, the first slot in the vbtable
1914 /// points to the start of the nv-base which introduced the vbptr and *not*
1915 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
1916 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
1918 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1919 uint64_t getFieldOffset(const ValueDecl *FD) const;
1921 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1923 VTableContextBase *getVTableContext();
1925 MangleContext *createMangleContext();
1927 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1928 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1930 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1931 void CollectInheritedProtocols(const Decl *CDecl,
1932 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1934 //===--------------------------------------------------------------------===//
1936 //===--------------------------------------------------------------------===//
1938 /// \brief Return the canonical (structural) type corresponding to the
1939 /// specified potentially non-canonical type \p T.
1941 /// The non-canonical version of a type may have many "decorated" versions of
1942 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
1943 /// returned type is guaranteed to be free of any of these, allowing two
1944 /// canonical types to be compared for exact equality with a simple pointer
1946 CanQualType getCanonicalType(QualType T) const {
1947 return CanQualType::CreateUnsafe(T.getCanonicalType());
1950 const Type *getCanonicalType(const Type *T) const {
1951 return T->getCanonicalTypeInternal().getTypePtr();
1954 /// \brief Return the canonical parameter type corresponding to the specific
1955 /// potentially non-canonical one.
1957 /// Qualifiers are stripped off, functions are turned into function
1958 /// pointers, and arrays decay one level into pointers.
1959 CanQualType getCanonicalParamType(QualType T) const;
1961 /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
1962 bool hasSameType(QualType T1, QualType T2) const {
1963 return getCanonicalType(T1) == getCanonicalType(T2);
1966 bool hasSameType(const Type *T1, const Type *T2) const {
1967 return getCanonicalType(T1) == getCanonicalType(T2);
1970 /// \brief Return this type as a completely-unqualified array type,
1971 /// capturing the qualifiers in \p Quals.
1973 /// This will remove the minimal amount of sugaring from the types, similar
1974 /// to the behavior of QualType::getUnqualifiedType().
1976 /// \param T is the qualified type, which may be an ArrayType
1978 /// \param Quals will receive the full set of qualifiers that were
1979 /// applied to the array.
1981 /// \returns if this is an array type, the completely unqualified array type
1982 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1983 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1985 /// \brief Determine whether the given types are equivalent after
1986 /// cvr-qualifiers have been removed.
1987 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
1988 return getCanonicalType(T1).getTypePtr() ==
1989 getCanonicalType(T2).getTypePtr();
1992 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
1993 bool IsParam) const {
1994 auto SubTnullability = SubT->getNullability(*this);
1995 auto SuperTnullability = SuperT->getNullability(*this);
1996 if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
1997 // Neither has nullability; return true
1998 if (!SubTnullability)
2000 // Both have nullability qualifier.
2001 if (*SubTnullability == *SuperTnullability ||
2002 *SubTnullability == NullabilityKind::Unspecified ||
2003 *SuperTnullability == NullabilityKind::Unspecified)
2007 // Ok for the superclass method parameter to be "nonnull" and the subclass
2008 // method parameter to be "nullable"
2009 return (*SuperTnullability == NullabilityKind::NonNull &&
2010 *SubTnullability == NullabilityKind::Nullable);
2013 // For the return type, it's okay for the superclass method to specify
2014 // "nullable" and the subclass method specify "nonnull"
2015 return (*SuperTnullability == NullabilityKind::Nullable &&
2016 *SubTnullability == NullabilityKind::NonNull);
2022 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2023 const ObjCMethodDecl *MethodImp);
2025 bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
2027 /// \brief Retrieves the "canonical" nested name specifier for a
2028 /// given nested name specifier.
2030 /// The canonical nested name specifier is a nested name specifier
2031 /// that uniquely identifies a type or namespace within the type
2032 /// system. For example, given:
2037 /// template<typename T> struct X { typename T* type; };
2041 /// template<typename T> struct Y {
2042 /// typename N::S::X<T>::type member;
2046 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2047 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2048 /// by declarations in the type system and the canonical type for
2049 /// the template type parameter 'T' is template-param-0-0.
2050 NestedNameSpecifier *
2051 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2053 /// \brief Retrieves the default calling convention for the current target.
2054 CallingConv getDefaultCallingConvention(bool isVariadic,
2055 bool IsCXXMethod) const;
2057 /// \brief Retrieves the "canonical" template name that refers to a
2060 /// The canonical template name is the simplest expression that can
2061 /// be used to refer to a given template. For most templates, this
2062 /// expression is just the template declaration itself. For example,
2063 /// the template std::vector can be referred to via a variety of
2064 /// names---std::vector, \::std::vector, vector (if vector is in
2065 /// scope), etc.---but all of these names map down to the same
2066 /// TemplateDecl, which is used to form the canonical template name.
2068 /// Dependent template names are more interesting. Here, the
2069 /// template name could be something like T::template apply or
2070 /// std::allocator<T>::template rebind, where the nested name
2071 /// specifier itself is dependent. In this case, the canonical
2072 /// template name uses the shortest form of the dependent
2073 /// nested-name-specifier, which itself contains all canonical
2074 /// types, values, and templates.
2075 TemplateName getCanonicalTemplateName(TemplateName Name) const;
2077 /// \brief Determine whether the given template names refer to the same
2079 bool hasSameTemplateName(TemplateName X, TemplateName Y);
2081 /// \brief Retrieve the "canonical" template argument.
2083 /// The canonical template argument is the simplest template argument
2084 /// (which may be a type, value, expression, or declaration) that
2085 /// expresses the value of the argument.
2086 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2089 /// Type Query functions. If the type is an instance of the specified class,
2090 /// return the Type pointer for the underlying maximally pretty type. This
2091 /// is a member of ASTContext because this may need to do some amount of
2092 /// canonicalization, e.g. to move type qualifiers into the element type.
2093 const ArrayType *getAsArrayType(QualType T) const;
2094 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2095 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2097 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2098 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2100 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2101 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2103 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2105 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2108 /// \brief Return the innermost element type of an array type.
2110 /// For example, will return "int" for int[m][n]
2111 QualType getBaseElementType(const ArrayType *VAT) const;
2113 /// \brief Return the innermost element type of a type (which needn't
2114 /// actually be an array type).
2115 QualType getBaseElementType(QualType QT) const;
2117 /// \brief Return number of constant array elements.
2118 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2120 /// \brief Perform adjustment on the parameter type of a function.
2122 /// This routine adjusts the given parameter type @p T to the actual
2123 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2124 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2125 QualType getAdjustedParameterType(QualType T) const;
2127 /// \brief Retrieve the parameter type as adjusted for use in the signature
2128 /// of a function, decaying array and function types and removing top-level
2130 QualType getSignatureParameterType(QualType T) const;
2132 QualType getExceptionObjectType(QualType T) const;
2134 /// \brief Return the properly qualified result of decaying the specified
2135 /// array type to a pointer.
2137 /// This operation is non-trivial when handling typedefs etc. The canonical
2138 /// type of \p T must be an array type, this returns a pointer to a properly
2139 /// qualified element of the array.
2141 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2142 QualType getArrayDecayedType(QualType T) const;
2144 /// \brief Return the type that \p PromotableType will promote to: C99
2145 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2146 QualType getPromotedIntegerType(QualType PromotableType) const;
2148 /// \brief Recurses in pointer/array types until it finds an Objective-C
2149 /// retainable type and returns its ownership.
2150 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2152 /// \brief Whether this is a promotable bitfield reference according
2153 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2155 /// \returns the type this bit-field will promote to, or NULL if no
2156 /// promotion occurs.
2157 QualType isPromotableBitField(Expr *E) const;
2159 /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
2161 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2162 /// \p LHS < \p RHS, return -1.
2163 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2165 /// \brief Compare the rank of the two specified floating point types,
2166 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2168 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2169 /// \p LHS < \p RHS, return -1.
2170 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2172 /// \brief Return a real floating point or a complex type (based on
2173 /// \p typeDomain/\p typeSize).
2175 /// \param typeDomain a real floating point or complex type.
2176 /// \param typeSize a real floating point or complex type.
2177 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2178 QualType typeDomain) const;
2180 unsigned getTargetAddressSpace(QualType T) const {
2181 return getTargetAddressSpace(T.getQualifiers());
2184 unsigned getTargetAddressSpace(Qualifiers Q) const {
2185 return getTargetAddressSpace(Q.getAddressSpace());
2188 unsigned getTargetAddressSpace(unsigned AS) const {
2189 if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
2192 return (*AddrSpaceMap)[AS - LangAS::Offset];
2195 bool addressSpaceMapManglingFor(unsigned AS) const {
2196 return AddrSpaceMapMangling ||
2197 AS < LangAS::Offset ||
2198 AS >= LangAS::Offset + LangAS::Count;
2202 // Helper for integer ordering
2203 unsigned getIntegerRank(const Type *T) const;
2207 //===--------------------------------------------------------------------===//
2208 // Type Compatibility Predicates
2209 //===--------------------------------------------------------------------===//
2211 /// Compatibility predicates used to check assignment expressions.
2212 bool typesAreCompatible(QualType T1, QualType T2,
2213 bool CompareUnqualified = false); // C99 6.2.7p1
2215 bool propertyTypesAreCompatible(QualType, QualType);
2216 bool typesAreBlockPointerCompatible(QualType, QualType);
2218 bool isObjCIdType(QualType T) const {
2219 return T == getObjCIdType();
2221 bool isObjCClassType(QualType T) const {
2222 return T == getObjCClassType();
2224 bool isObjCSelType(QualType T) const {
2225 return T == getObjCSelType();
2227 bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
2230 bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
2232 // Check the safety of assignment from LHS to RHS
2233 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2234 const ObjCObjectPointerType *RHSOPT);
2235 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2236 const ObjCObjectType *RHS);
2237 bool canAssignObjCInterfacesInBlockPointer(
2238 const ObjCObjectPointerType *LHSOPT,
2239 const ObjCObjectPointerType *RHSOPT,
2240 bool BlockReturnType);
2241 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2242 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2243 const ObjCObjectPointerType *RHSOPT);
2244 bool canBindObjCObjectType(QualType To, QualType From);
2246 // Functions for calculating composite types
2247 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2248 bool Unqualified = false, bool BlockReturnType = false);
2249 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2250 bool Unqualified = false);
2251 QualType mergeFunctionParameterTypes(QualType, QualType,
2252 bool OfBlockPointer = false,
2253 bool Unqualified = false);
2254 QualType mergeTransparentUnionType(QualType, QualType,
2255 bool OfBlockPointer=false,
2256 bool Unqualified = false);
2258 QualType mergeObjCGCQualifiers(QualType, QualType);
2260 bool FunctionTypesMatchOnNSConsumedAttrs(
2261 const FunctionProtoType *FromFunctionType,
2262 const FunctionProtoType *ToFunctionType);
2264 void ResetObjCLayout(const ObjCContainerDecl *CD);
2266 //===--------------------------------------------------------------------===//
2267 // Integer Predicates
2268 //===--------------------------------------------------------------------===//
2270 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2271 // of bits in an integer type excluding any padding bits.
2272 unsigned getIntWidth(QualType T) const;
2274 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2275 // unsigned integer type. This method takes a signed type, and returns the
2276 // corresponding unsigned integer type.
2277 QualType getCorrespondingUnsignedType(QualType T) const;
2279 //===--------------------------------------------------------------------===//
2281 //===--------------------------------------------------------------------===//
2283 /// \brief Make an APSInt of the appropriate width and signedness for the
2284 /// given \p Value and integer \p Type.
2285 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2286 // If Type is a signed integer type larger than 64 bits, we need to be sure
2287 // to sign extend Res appropriately.
2288 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2290 unsigned Width = getIntWidth(Type);
2291 if (Width != Res.getBitWidth())
2292 return Res.extOrTrunc(Width);
2296 bool isSentinelNullExpr(const Expr *E);
2298 /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
2300 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2301 /// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
2303 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2305 /// \brief Return true if there is at least one \@implementation in the TU.
2306 bool AnyObjCImplementation() {
2307 return !ObjCImpls.empty();
2310 /// \brief Set the implementation of ObjCInterfaceDecl.
2311 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2312 ObjCImplementationDecl *ImplD);
2313 /// \brief Set the implementation of ObjCCategoryDecl.
2314 void setObjCImplementation(ObjCCategoryDecl *CatD,
2315 ObjCCategoryImplDecl *ImplD);
2317 /// \brief Get the duplicate declaration of a ObjCMethod in the same
2318 /// interface, or null if none exists.
2319 const ObjCMethodDecl *
2320 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2322 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2323 const ObjCMethodDecl *Redecl);
2325 /// \brief Returns the Objective-C interface that \p ND belongs to if it is
2326 /// an Objective-C method/property/ivar etc. that is part of an interface,
2327 /// otherwise returns null.
2328 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2330 /// \brief Set the copy inialization expression of a block var decl.
2331 void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2332 /// \brief Get the copy initialization expression of the VarDecl \p VD, or
2333 /// NULL if none exists.
2334 Expr *getBlockVarCopyInits(const VarDecl* VD);
2336 /// \brief Allocate an uninitialized TypeSourceInfo.
2338 /// The caller should initialize the memory held by TypeSourceInfo using
2339 /// the TypeLoc wrappers.
2341 /// \param T the type that will be the basis for type source info. This type
2342 /// should refer to how the declarator was written in source code, not to
2343 /// what type semantic analysis resolved the declarator to.
2345 /// \param Size the size of the type info to create, or 0 if the size
2346 /// should be calculated based on the type.
2347 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2349 /// \brief Allocate a TypeSourceInfo where all locations have been
2350 /// initialized to a given location, which defaults to the empty
2353 getTrivialTypeSourceInfo(QualType T,
2354 SourceLocation Loc = SourceLocation()) const;
2356 /// \brief Add a deallocation callback that will be invoked when the
2357 /// ASTContext is destroyed.
2359 /// \param Callback A callback function that will be invoked on destruction.
2361 /// \param Data Pointer data that will be provided to the callback function
2362 /// when it is called.
2363 void AddDeallocation(void (*Callback)(void*), void *Data);
2365 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2366 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2368 /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
2369 /// lazily, only when used; this is only relevant for function or file scoped
2370 /// var definitions.
2372 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2374 bool DeclMustBeEmitted(const Decl *D);
2376 const CXXConstructorDecl *
2377 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2379 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2380 CXXConstructorDecl *CD);
2382 void addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
2383 unsigned ParmIdx, Expr *DAE);
2385 Expr *getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
2388 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2390 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2392 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2394 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2396 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2397 unsigned getManglingNumber(const NamedDecl *ND) const;
2399 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2400 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2402 /// \brief Retrieve the context for computing mangling numbers in the given
2404 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2406 MangleNumberingContext *createMangleNumberingContext() const;
2408 /// \brief Used by ParmVarDecl to store on the side the
2409 /// index of the parameter when it exceeds the size of the normal bitfield.
2410 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2412 /// \brief Used by ParmVarDecl to retrieve on the side the
2413 /// index of the parameter when it exceeds the size of the normal bitfield.
2414 unsigned getParameterIndex(const ParmVarDecl *D) const;
2416 /// \brief Get the storage for the constant value of a materialized temporary
2417 /// of static storage duration.
2418 APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
2421 //===--------------------------------------------------------------------===//
2423 //===--------------------------------------------------------------------===//
2425 /// \brief The number of implicitly-declared default constructors.
2426 static unsigned NumImplicitDefaultConstructors;
2428 /// \brief The number of implicitly-declared default constructors for
2429 /// which declarations were built.
2430 static unsigned NumImplicitDefaultConstructorsDeclared;
2432 /// \brief The number of implicitly-declared copy constructors.
2433 static unsigned NumImplicitCopyConstructors;
2435 /// \brief The number of implicitly-declared copy constructors for
2436 /// which declarations were built.
2437 static unsigned NumImplicitCopyConstructorsDeclared;
2439 /// \brief The number of implicitly-declared move constructors.
2440 static unsigned NumImplicitMoveConstructors;
2442 /// \brief The number of implicitly-declared move constructors for
2443 /// which declarations were built.
2444 static unsigned NumImplicitMoveConstructorsDeclared;
2446 /// \brief The number of implicitly-declared copy assignment operators.
2447 static unsigned NumImplicitCopyAssignmentOperators;
2449 /// \brief The number of implicitly-declared copy assignment operators for
2450 /// which declarations were built.
2451 static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2453 /// \brief The number of implicitly-declared move assignment operators.
2454 static unsigned NumImplicitMoveAssignmentOperators;
2456 /// \brief The number of implicitly-declared move assignment operators for
2457 /// which declarations were built.
2458 static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2460 /// \brief The number of implicitly-declared destructors.
2461 static unsigned NumImplicitDestructors;
2463 /// \brief The number of implicitly-declared destructors for which
2464 /// declarations were built.
2465 static unsigned NumImplicitDestructorsDeclared;
2468 ASTContext(const ASTContext &) = delete;
2469 void operator=(const ASTContext &) = delete;
2472 /// \brief Initialize built-in types.
2474 /// This routine may only be invoked once for a given ASTContext object.
2475 /// It is normally invoked after ASTContext construction.
2477 /// \param Target The target
2478 void InitBuiltinTypes(const TargetInfo &Target,
2479 const TargetInfo *AuxTarget = nullptr);
2482 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2484 // Return the Objective-C type encoding for a given type.
2485 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2486 bool ExpandPointedToStructures,
2487 bool ExpandStructures,
2488 const FieldDecl *Field,
2489 bool OutermostType = false,
2490 bool EncodingProperty = false,
2491 bool StructField = false,
2492 bool EncodeBlockParameters = false,
2493 bool EncodeClassNames = false,
2494 bool EncodePointerToObjCTypedef = false,
2495 QualType *NotEncodedT=nullptr) const;
2497 // Adds the encoding of the structure's members.
2498 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2499 const FieldDecl *Field,
2500 bool includeVBases = true,
2501 QualType *NotEncodedT=nullptr) const;
2503 // Adds the encoding of a method parameter or return type.
2504 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2505 QualType T, std::string& S,
2506 bool Extended) const;
2508 /// \brief Returns true if this is an inline-initialized static data member
2509 /// which is treated as a definition for MSVC compatibility.
2510 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2513 const ASTRecordLayout &
2514 getObjCLayout(const ObjCInterfaceDecl *D,
2515 const ObjCImplementationDecl *Impl) const;
2517 /// \brief A set of deallocations that should be performed when the
2518 /// ASTContext is destroyed.
2519 // FIXME: We really should have a better mechanism in the ASTContext to
2520 // manage running destructors for types which do variable sized allocation
2521 // within the AST. In some places we thread the AST bump pointer allocator
2522 // into the datastructures which avoids this mess during deallocation but is
2523 // wasteful of memory, and here we require a lot of error prone book keeping
2524 // in order to track and run destructors while we're tearing things down.
2525 typedef llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>
2526 DeallocationFunctionsAndArguments;
2527 DeallocationFunctionsAndArguments Deallocations;
2529 // FIXME: This currently contains the set of StoredDeclMaps used
2530 // by DeclContext objects. This probably should not be in ASTContext,
2531 // but we include it here so that ASTContext can quickly deallocate them.
2532 llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2534 friend class DeclContext;
2535 friend class DeclarationNameTable;
2536 void ReleaseDeclContextMaps();
2537 void ReleaseParentMapEntries();
2539 std::unique_ptr<ParentMapPointers> PointerParents;
2540 std::unique_ptr<ParentMapOtherNodes> OtherParents;
2542 std::unique_ptr<VTableContextBase> VTContext;
2545 enum PragmaSectionFlag : unsigned {
2551 PSF_Invalid = 0x80000000U,
2554 struct SectionInfo {
2555 DeclaratorDecl *Decl;
2556 SourceLocation PragmaSectionLocation;
2559 SectionInfo(DeclaratorDecl *Decl,
2560 SourceLocation PragmaSectionLocation,
2563 PragmaSectionLocation(PragmaSectionLocation),
2564 SectionFlags(SectionFlags) {}
2567 llvm::StringMap<SectionInfo> SectionInfos;
2570 /// \brief Utility function for constructing a nullary selector.
2571 static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2572 IdentifierInfo* II = &Ctx.Idents.get(name);
2573 return Ctx.Selectors.getSelector(0, &II);
2576 /// \brief Utility function for constructing an unary selector.
2577 static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2578 IdentifierInfo* II = &Ctx.Idents.get(name);
2579 return Ctx.Selectors.getSelector(1, &II);
2582 } // end namespace clang
2584 // operator new and delete aren't allowed inside namespaces.
2586 /// @brief Placement new for using the ASTContext's allocator.
2588 /// This placement form of operator new uses the ASTContext's allocator for
2589 /// obtaining memory.
2591 /// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2592 /// here need to also be made there.
2594 /// We intentionally avoid using a nothrow specification here so that the calls
2595 /// to this operator will not perform a null check on the result -- the
2596 /// underlying allocator never returns null pointers.
2598 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2600 /// // Default alignment (8)
2601 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2602 /// // Specific alignment
2603 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2605 /// Memory allocated through this placement new operator does not need to be
2606 /// explicitly freed, as ASTContext will free all of this memory when it gets
2607 /// destroyed. Please note that you cannot use delete on the pointer.
2609 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2610 /// @param C The ASTContext that provides the allocator.
2611 /// @param Alignment The alignment of the allocated memory (if the underlying
2612 /// allocator supports it).
2613 /// @return The allocated memory. Could be NULL.
2614 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2616 return C.Allocate(Bytes, Alignment);
2618 /// @brief Placement delete companion to the new above.
2620 /// This operator is just a companion to the new above. There is no way of
2621 /// invoking it directly; see the new operator for more details. This operator
2622 /// is called implicitly by the compiler if a placement new expression using
2623 /// the ASTContext throws in the object constructor.
2624 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2628 /// This placement form of operator new[] uses the ASTContext's allocator for
2629 /// obtaining memory.
2631 /// We intentionally avoid using a nothrow specification here so that the calls
2632 /// to this operator will not perform a null check on the result -- the
2633 /// underlying allocator never returns null pointers.
2635 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2637 /// // Default alignment (8)
2638 /// char *data = new (Context) char[10];
2639 /// // Specific alignment
2640 /// char *data = new (Context, 4) char[10];
2642 /// Memory allocated through this placement new[] operator does not need to be
2643 /// explicitly freed, as ASTContext will free all of this memory when it gets
2644 /// destroyed. Please note that you cannot use delete on the pointer.
2646 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2647 /// @param C The ASTContext that provides the allocator.
2648 /// @param Alignment The alignment of the allocated memory (if the underlying
2649 /// allocator supports it).
2650 /// @return The allocated memory. Could be NULL.
2651 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2652 size_t Alignment = 8) {
2653 return C.Allocate(Bytes, Alignment);
2656 /// @brief Placement delete[] companion to the new[] above.
2658 /// This operator is just a companion to the new[] above. There is no way of
2659 /// invoking it directly; see the new[] operator for more details. This operator
2660 /// is called implicitly by the compiler if a placement new[] expression using
2661 /// the ASTContext throws in the object constructor.
2662 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2666 /// \brief Create the representation of a LazyGenerationalUpdatePtr.
2667 template <typename Owner, typename T,
2668 void (clang::ExternalASTSource::*Update)(Owner)>
2669 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
2670 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
2671 const clang::ASTContext &Ctx, T Value) {
2672 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
2673 // include ASTContext.h. We explicitly instantiate it for all relevant types
2674 // in ASTContext.cpp.
2675 if (auto *Source = Ctx.getExternalSource())
2676 return new (Ctx) LazyData(Source, Value);