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/MapVector.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/TinyPtrVector.h"
42 #include "llvm/Support/Allocator.h"
53 class ASTRecordLayout;
56 class DiagnosticsEngine;
58 class ASTMutationListener;
59 class IdentifierTable;
60 class MaterializeTemporaryExpr;
64 class MangleNumberingContext;
68 class ObjCPropertyDecl;
69 class UnresolvedSetIterator;
71 class UsingShadowDecl;
72 class VTableContextBase;
74 namespace Builtin { class Context; }
75 enum BuiltinTemplateKind : int;
84 bool AlignIsRequired : 1;
85 TypeInfo() : Width(0), Align(0), AlignIsRequired(false) {}
86 TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
87 : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
90 /// \brief Holds long-lived AST nodes (such as types and decls) that can be
91 /// referred to throughout the semantic analysis of a file.
92 class ASTContext : public RefCountedBase<ASTContext> {
93 ASTContext &this_() { return *this; }
95 mutable SmallVector<Type *, 0> Types;
96 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
97 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
98 mutable llvm::FoldingSet<PointerType> PointerTypes;
99 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
100 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
101 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
102 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
103 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
104 mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
105 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
106 mutable std::vector<VariableArrayType*> VariableArrayTypes;
107 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
108 mutable llvm::FoldingSet<DependentSizedExtVectorType>
109 DependentSizedExtVectorTypes;
110 mutable llvm::FoldingSet<VectorType> VectorTypes;
111 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
112 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
114 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
115 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
116 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
117 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
118 SubstTemplateTypeParmTypes;
119 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
120 SubstTemplateTypeParmPackTypes;
121 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
122 TemplateSpecializationTypes;
123 mutable llvm::FoldingSet<ParenType> ParenTypes;
124 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
125 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
126 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
128 DependentTemplateSpecializationTypes;
129 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
130 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
131 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
132 mutable llvm::FoldingSet<DependentUnaryTransformType>
133 DependentUnaryTransformTypes;
134 mutable llvm::FoldingSet<AutoType> AutoTypes;
135 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
136 llvm::FoldingSet<AttributedType> AttributedTypes;
137 mutable llvm::FoldingSet<PipeType> PipeTypes;
139 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
140 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
141 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
142 SubstTemplateTemplateParms;
143 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
145 SubstTemplateTemplateParmPacks;
147 /// \brief The set of nested name specifiers.
149 /// This set is managed by the NestedNameSpecifier class.
150 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
151 mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
152 friend class NestedNameSpecifier;
154 /// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
156 /// This is lazily created. This is intentionally not serialized.
157 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
159 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
162 /// \brief A cache from types to size and alignment information.
163 typedef llvm::DenseMap<const Type *, struct TypeInfo> TypeInfoMap;
164 mutable TypeInfoMap MemoizedTypeInfo;
166 /// \brief A cache mapping from CXXRecordDecls to key functions.
167 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
169 /// \brief Mapping from ObjCContainers to their ObjCImplementations.
170 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
172 /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
174 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
176 /// \brief Mapping from __block VarDecls to their copy initialization expr.
177 llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
179 /// \brief Mapping from class scope functions specialization to their
180 /// template patterns.
181 llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
182 ClassScopeSpecializationPattern;
184 /// \brief Mapping from materialized temporaries with static storage duration
185 /// that appear in constant initializers to their evaluated values. These are
186 /// allocated in a std::map because their address must be stable.
187 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue *>
188 MaterializedTemporaryValues;
190 /// \brief Representation of a "canonical" template template parameter that
191 /// is used in canonical template names.
192 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
193 TemplateTemplateParmDecl *Parm;
196 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
199 TemplateTemplateParmDecl *getParam() const { return Parm; }
201 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
203 static void Profile(llvm::FoldingSetNodeID &ID,
204 TemplateTemplateParmDecl *Parm);
206 mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
207 CanonTemplateTemplateParms;
209 TemplateTemplateParmDecl *
210 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
212 /// \brief The typedef for the __int128_t type.
213 mutable TypedefDecl *Int128Decl;
215 /// \brief The typedef for the __uint128_t type.
216 mutable TypedefDecl *UInt128Decl;
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 'bool'.
247 mutable IdentifierInfo *BoolName = nullptr;
249 /// The identifier 'NSObject'.
250 IdentifierInfo *NSObjectName = nullptr;
252 /// The identifier 'NSCopying'.
253 IdentifierInfo *NSCopyingName = nullptr;
255 /// The identifier '__make_integer_seq'.
256 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
258 /// The identifier '__type_pack_element'.
259 mutable IdentifierInfo *TypePackElementName = nullptr;
261 QualType ObjCConstantStringType;
262 mutable RecordDecl *CFConstantStringTagDecl;
263 mutable TypedefDecl *CFConstantStringTypeDecl;
265 mutable QualType ObjCSuperType;
267 QualType ObjCNSStringType;
269 /// \brief The typedef declaration for the Objective-C "instancetype" type.
270 TypedefDecl *ObjCInstanceTypeDecl;
272 /// \brief The type for the C FILE type.
275 /// \brief The type for the C jmp_buf type.
276 TypeDecl *jmp_bufDecl;
278 /// \brief The type for the C sigjmp_buf type.
279 TypeDecl *sigjmp_bufDecl;
281 /// \brief The type for the C ucontext_t type.
282 TypeDecl *ucontext_tDecl;
284 /// \brief Type for the Block descriptor for Blocks CodeGen.
286 /// Since this is only used for generation of debug info, it is not
288 mutable RecordDecl *BlockDescriptorType;
290 /// \brief Type for the Block descriptor for Blocks CodeGen.
292 /// Since this is only used for generation of debug info, it is not
294 mutable RecordDecl *BlockDescriptorExtendedType;
296 /// \brief Declaration for the CUDA cudaConfigureCall function.
297 FunctionDecl *cudaConfigureCallDecl;
299 /// \brief Keeps track of all declaration attributes.
301 /// Since so few decls have attrs, we keep them in a hash map instead of
302 /// wasting space in the Decl class.
303 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
305 /// \brief A mapping from non-redeclarable declarations in modules that were
306 /// merged with other declarations to the canonical declaration that they were
308 llvm::DenseMap<Decl*, Decl*> MergedDecls;
310 /// \brief A mapping from a defining declaration to a list of modules (other
311 /// than the owning module of the declaration) that contain merged
312 /// definitions of that entity.
313 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
316 /// \brief A type synonym for the TemplateOrInstantiation mapping.
317 typedef llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>
318 TemplateOrSpecializationInfo;
322 /// \brief A mapping to contain the template or declaration that
323 /// a variable declaration describes or was instantiated from,
326 /// For non-templates, this value will be NULL. For variable
327 /// declarations that describe a variable template, this will be a
328 /// pointer to a VarTemplateDecl. For static data members
329 /// of class template specializations, this will be the
330 /// MemberSpecializationInfo referring to the member variable that was
331 /// instantiated or specialized. Thus, the mapping will keep track of
332 /// the static data member templates from which static data members of
333 /// class template specializations were instantiated.
335 /// Given the following example:
338 /// template<typename T>
343 /// template<typename T>
344 /// T X<T>::value = T(17);
346 /// int *x = &X<int>::value;
349 /// This mapping will contain an entry that maps from the VarDecl for
350 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
351 /// class template X) and will be marked TSK_ImplicitInstantiation.
352 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
353 TemplateOrInstantiation;
355 /// \brief Keeps track of the declaration from which a UsingDecl was
356 /// created during instantiation.
358 /// The source declaration is always a UsingDecl, an UnresolvedUsingValueDecl,
359 /// or an UnresolvedUsingTypenameDecl.
363 /// template<typename T>
368 /// template<typename T>
369 /// struct B : A<T> {
373 /// template struct B<int>;
376 /// This mapping will contain an entry that maps from the UsingDecl in
377 /// B<int> to the UnresolvedUsingDecl in B<T>.
378 llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
380 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
381 InstantiatedFromUsingShadowDecl;
383 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
385 /// \brief Mapping that stores the methods overridden by a given C++
388 /// Since most C++ member functions aren't virtual and therefore
389 /// don't override anything, we store the overridden functions in
390 /// this map on the side rather than within the CXXMethodDecl structure.
391 typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
392 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
394 /// \brief Mapping from each declaration context to its corresponding
395 /// mangling numbering context (used for constructs like lambdas which
396 /// need to be consistently numbered for the mangler).
397 llvm::DenseMap<const DeclContext *, MangleNumberingContext *>
398 MangleNumberingContexts;
400 /// \brief Side-table of mangling numbers for declarations which rarely
401 /// need them (like static local vars).
402 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
403 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
405 /// \brief Mapping that stores parameterIndex values for ParmVarDecls when
406 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
407 typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
408 ParameterIndexTable ParamIndices;
410 ImportDecl *FirstLocalImport;
411 ImportDecl *LastLocalImport;
413 TranslationUnitDecl *TUDecl;
414 mutable ExternCContextDecl *ExternCContext;
415 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl;
416 mutable BuiltinTemplateDecl *TypePackElementDecl;
418 /// \brief The associated SourceManager object.a
419 SourceManager &SourceMgr;
421 /// \brief The language options used to create the AST associated with
422 /// this ASTContext object.
423 LangOptions &LangOpts;
425 /// \brief Blacklist object that is used by sanitizers to decide which
426 /// entities should not be instrumented.
427 std::unique_ptr<SanitizerBlacklist> SanitizerBL;
429 /// \brief The allocator used to create AST objects.
431 /// AST objects are never destructed; rather, all memory associated with the
432 /// AST objects will be released when the ASTContext itself is destroyed.
433 mutable llvm::BumpPtrAllocator BumpAlloc;
435 /// \brief Allocator for partial diagnostics.
436 PartialDiagnostic::StorageAllocator DiagAllocator;
438 /// \brief The current C++ ABI.
439 std::unique_ptr<CXXABI> ABI;
440 CXXABI *createCXXABI(const TargetInfo &T);
442 /// \brief The logical -> physical address space map.
443 const LangAS::Map *AddrSpaceMap;
445 /// \brief Address space map mangling must be used with language specific
446 /// address spaces (e.g. OpenCL/CUDA)
447 bool AddrSpaceMapMangling;
449 friend class ASTDeclReader;
450 friend class ASTReader;
451 friend class ASTWriter;
452 friend class CXXRecordDecl;
454 const TargetInfo *Target;
455 const TargetInfo *AuxTarget;
456 clang::PrintingPolicy PrintingPolicy;
459 IdentifierTable &Idents;
460 SelectorTable &Selectors;
461 Builtin::Context &BuiltinInfo;
462 mutable DeclarationNameTable DeclarationNames;
463 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
464 ASTMutationListener *Listener;
466 /// \brief Contains parents of a node.
467 typedef llvm::SmallVector<ast_type_traits::DynTypedNode, 2> ParentVector;
469 /// \brief Maps from a node to its parents. This is used for nodes that have
470 /// pointer identity only, which are more common and we can save space by
471 /// only storing a unique pointer to them.
472 typedef llvm::DenseMap<const void *,
473 llvm::PointerUnion4<const Decl *, const Stmt *,
474 ast_type_traits::DynTypedNode *,
475 ParentVector *>> ParentMapPointers;
477 /// Parent map for nodes without pointer identity. We store a full
478 /// DynTypedNode for all keys.
479 typedef llvm::DenseMap<
480 ast_type_traits::DynTypedNode,
481 llvm::PointerUnion4<const Decl *, const Stmt *,
482 ast_type_traits::DynTypedNode *, ParentVector *>>
485 /// Container for either a single DynTypedNode or for an ArrayRef to
486 /// DynTypedNode. For use with ParentMap.
487 class DynTypedNodeList {
488 typedef ast_type_traits::DynTypedNode DynTypedNode;
489 llvm::AlignedCharArrayUnion<ast_type_traits::DynTypedNode,
490 ArrayRef<DynTypedNode>> Storage;
494 DynTypedNodeList(const DynTypedNode &N) : IsSingleNode(true) {
495 new (Storage.buffer) DynTypedNode(N);
497 DynTypedNodeList(ArrayRef<DynTypedNode> A) : IsSingleNode(false) {
498 new (Storage.buffer) ArrayRef<DynTypedNode>(A);
501 const ast_type_traits::DynTypedNode *begin() const {
503 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
505 return reinterpret_cast<const DynTypedNode *>(Storage.buffer);
508 const ast_type_traits::DynTypedNode *end() const {
510 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
512 return reinterpret_cast<const DynTypedNode *>(Storage.buffer) + 1;
515 size_t size() const { return end() - begin(); }
516 bool empty() const { return begin() == end(); }
517 const DynTypedNode &operator[](size_t N) const {
518 assert(N < size() && "Out of bounds!");
519 return *(begin() + N);
523 /// \brief Returns the parents of the given node.
525 /// Note that this will lazily compute the parents of all nodes
526 /// and store them for later retrieval. Thus, the first call is O(n)
527 /// in the number of AST nodes.
529 /// Caveats and FIXMEs:
530 /// Calculating the parent map over all AST nodes will need to load the
531 /// full AST. This can be undesirable in the case where the full AST is
532 /// expensive to create (for example, when using precompiled header
533 /// preambles). Thus, there are good opportunities for optimization here.
534 /// One idea is to walk the given node downwards, looking for references
535 /// to declaration contexts - once a declaration context is found, compute
536 /// the parent map for the declaration context; if that can satisfy the
537 /// request, loading the whole AST can be avoided. Note that this is made
538 /// more complex by statements in templates having multiple parents - those
539 /// problems can be solved by building closure over the templated parts of
540 /// the AST, which also avoids touching large parts of the AST.
541 /// Additionally, we will want to add an interface to already give a hint
542 /// where to search for the parents, for example when looking at a statement
543 /// inside a certain function.
545 /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
546 /// NestedNameSpecifier or NestedNameSpecifierLoc.
547 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node) {
548 return getParents(ast_type_traits::DynTypedNode::create(Node));
551 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node);
553 const clang::PrintingPolicy &getPrintingPolicy() const {
554 return PrintingPolicy;
557 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
558 PrintingPolicy = Policy;
561 SourceManager& getSourceManager() { return SourceMgr; }
562 const SourceManager& getSourceManager() const { return SourceMgr; }
564 llvm::BumpPtrAllocator &getAllocator() const {
568 void *Allocate(size_t Size, unsigned Align = 8) const {
569 return BumpAlloc.Allocate(Size, Align);
571 template <typename T> T *Allocate(size_t Num = 1) const {
572 return static_cast<T *>(Allocate(Num * sizeof(T), llvm::alignOf<T>()));
574 void Deallocate(void *Ptr) const { }
576 /// Return the total amount of physical memory allocated for representing
577 /// AST nodes and type information.
578 size_t getASTAllocatedMemory() const {
579 return BumpAlloc.getTotalMemory();
581 /// Return the total memory used for various side tables.
582 size_t getSideTableAllocatedMemory() const;
584 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
585 return DiagAllocator;
588 const TargetInfo &getTargetInfo() const { return *Target; }
589 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
591 /// getIntTypeForBitwidth -
592 /// sets integer QualTy according to specified details:
593 /// bitwidth, signed/unsigned.
594 /// Returns empty type if there is no appropriate target types.
595 QualType getIntTypeForBitwidth(unsigned DestWidth,
596 unsigned Signed) const;
597 /// getRealTypeForBitwidth -
598 /// sets floating point QualTy according to specified bitwidth.
599 /// Returns empty type if there is no appropriate target types.
600 QualType getRealTypeForBitwidth(unsigned DestWidth) const;
602 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
604 const LangOptions& getLangOpts() const { return LangOpts; }
606 const SanitizerBlacklist &getSanitizerBlacklist() const {
610 DiagnosticsEngine &getDiagnostics() const;
612 FullSourceLoc getFullLoc(SourceLocation Loc) const {
613 return FullSourceLoc(Loc,SourceMgr);
616 /// \brief All comments in this translation unit.
617 RawCommentList Comments;
619 /// \brief True if comments are already loaded from ExternalASTSource.
620 mutable bool CommentsLoaded;
622 class RawCommentAndCacheFlags {
625 /// We searched for a comment attached to the particular declaration, but
631 /// We have found a comment attached to this particular declaration.
636 /// This declaration does not have an attached comment, and we have
637 /// searched the redeclaration chain.
639 /// If getRaw() == 0, the whole redeclaration chain does not have any
642 /// If getRaw() != 0, it is a comment propagated from other
647 Kind getKind() const LLVM_READONLY {
648 return Data.getInt();
651 void setKind(Kind K) {
655 const RawComment *getRaw() const LLVM_READONLY {
656 return Data.getPointer();
659 void setRaw(const RawComment *RC) {
663 const Decl *getOriginalDecl() const LLVM_READONLY {
667 void setOriginalDecl(const Decl *Orig) {
672 llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
673 const Decl *OriginalDecl;
676 /// \brief Mapping from declarations to comments attached to any
679 /// Raw comments are owned by Comments list. This mapping is populated
681 mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
683 /// \brief Mapping from declarations to parsed comments attached to any
685 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
687 /// \brief Return the documentation comment attached to a given declaration,
688 /// without looking into cache.
689 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
692 RawCommentList &getRawCommentList() {
696 void addComment(const RawComment &RC) {
697 assert(LangOpts.RetainCommentsFromSystemHeaders ||
698 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
699 Comments.addComment(RC, BumpAlloc);
702 /// \brief Return the documentation comment attached to a given declaration.
703 /// Returns NULL if no comment is attached.
705 /// \param OriginalDecl if not NULL, is set to declaration AST node that had
706 /// the comment, if the comment we found comes from a redeclaration.
708 getRawCommentForAnyRedecl(const Decl *D,
709 const Decl **OriginalDecl = nullptr) const;
711 /// Return parsed documentation comment attached to a given declaration.
712 /// Returns NULL if no comment is attached.
714 /// \param PP the Preprocessor used with this TU. Could be NULL if
715 /// preprocessor is not available.
716 comments::FullComment *getCommentForDecl(const Decl *D,
717 const Preprocessor *PP) const;
719 /// Return parsed documentation comment attached to a given declaration.
720 /// Returns NULL if no comment is attached. Does not look at any
721 /// redeclarations of the declaration.
722 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
724 comments::FullComment *cloneFullComment(comments::FullComment *FC,
725 const Decl *D) const;
728 mutable comments::CommandTraits CommentCommandTraits;
730 /// \brief Iterator that visits import declarations.
731 class import_iterator {
735 typedef ImportDecl *value_type;
736 typedef ImportDecl *reference;
737 typedef ImportDecl *pointer;
738 typedef int difference_type;
739 typedef std::forward_iterator_tag iterator_category;
741 import_iterator() : Import() {}
742 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
744 reference operator*() const { return Import; }
745 pointer operator->() const { return Import; }
747 import_iterator &operator++() {
748 Import = ASTContext::getNextLocalImport(Import);
752 import_iterator operator++(int) {
753 import_iterator Other(*this);
758 friend bool operator==(import_iterator X, import_iterator Y) {
759 return X.Import == Y.Import;
762 friend bool operator!=(import_iterator X, import_iterator Y) {
763 return X.Import != Y.Import;
768 comments::CommandTraits &getCommentCommandTraits() const {
769 return CommentCommandTraits;
772 /// \brief Retrieve the attributes for the given declaration.
773 AttrVec& getDeclAttrs(const Decl *D);
775 /// \brief Erase the attributes corresponding to the given declaration.
776 void eraseDeclAttrs(const Decl *D);
778 /// \brief If this variable is an instantiated static data member of a
779 /// class template specialization, returns the templated static data member
780 /// from which it was instantiated.
782 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
785 TemplateOrSpecializationInfo
786 getTemplateOrSpecializationInfo(const VarDecl *Var);
788 FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
790 void setClassScopeSpecializationPattern(FunctionDecl *FD,
791 FunctionDecl *Pattern);
793 /// \brief Note that the static data member \p Inst is an instantiation of
794 /// the static data member template \p Tmpl of a class template.
795 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
796 TemplateSpecializationKind TSK,
797 SourceLocation PointOfInstantiation = SourceLocation());
799 void setTemplateOrSpecializationInfo(VarDecl *Inst,
800 TemplateOrSpecializationInfo TSI);
802 /// \brief If the given using decl \p Inst is an instantiation of a
803 /// (possibly unresolved) using decl from a template instantiation,
805 NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
807 /// \brief Remember that the using decl \p Inst is an instantiation
808 /// of the using decl \p Pattern of a class template.
809 void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
811 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
812 UsingShadowDecl *Pattern);
813 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
815 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
817 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
819 // Access to the set of methods overridden by the given C++ method.
820 typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
821 overridden_cxx_method_iterator
822 overridden_methods_begin(const CXXMethodDecl *Method) const;
824 overridden_cxx_method_iterator
825 overridden_methods_end(const CXXMethodDecl *Method) const;
827 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
828 typedef llvm::iterator_range<overridden_cxx_method_iterator>
829 overridden_method_range;
830 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
832 /// \brief Note that the given C++ \p Method overrides the given \p
833 /// Overridden method.
834 void addOverriddenMethod(const CXXMethodDecl *Method,
835 const CXXMethodDecl *Overridden);
837 /// \brief Return C++ or ObjC overridden methods for the given \p Method.
839 /// An ObjC method is considered to override any method in the class's
840 /// base classes, its protocols, or its categories' protocols, that has
841 /// the same selector and is of the same kind (class or instance).
842 /// A method in an implementation is not considered as overriding the same
843 /// method in the interface or its categories.
844 void getOverriddenMethods(
845 const NamedDecl *Method,
846 SmallVectorImpl<const NamedDecl *> &Overridden) const;
848 /// \brief Notify the AST context that a new import declaration has been
849 /// parsed or implicitly created within this translation unit.
850 void addedLocalImportDecl(ImportDecl *Import);
852 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
853 return Import->NextLocalImport;
856 typedef llvm::iterator_range<import_iterator> import_range;
857 import_range local_imports() const {
858 return import_range(import_iterator(FirstLocalImport), import_iterator());
861 Decl *getPrimaryMergedDecl(Decl *D) {
862 Decl *Result = MergedDecls.lookup(D);
863 return Result ? Result : D;
865 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
866 MergedDecls[D] = Primary;
869 /// \brief Note that the definition \p ND has been merged into module \p M,
870 /// and should be visible whenever \p M is visible.
871 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
872 bool NotifyListeners = true);
873 /// \brief Clean up the merged definition list. Call this if you might have
874 /// added duplicates into the list.
875 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
877 /// \brief Get the additional modules in which the definition \p Def has
879 ArrayRef<Module*> getModulesWithMergedDefinition(NamedDecl *Def) {
880 auto MergedIt = MergedDefModules.find(Def);
881 if (MergedIt == MergedDefModules.end())
883 return MergedIt->second;
886 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
888 ExternCContextDecl *getExternCContextDecl() const;
889 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
890 BuiltinTemplateDecl *getTypePackElementDecl() const;
896 CanQualType WCharTy; // [C++ 3.9.1p5].
897 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
898 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
899 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
900 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
901 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
902 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
903 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
904 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty;
905 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
906 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
907 CanQualType Float128ComplexTy;
908 CanQualType VoidPtrTy, NullPtrTy;
909 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
910 CanQualType BuiltinFnTy;
911 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
912 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
913 CanQualType ObjCBuiltinBoolTy;
914 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
915 CanQualType SingletonId;
916 #include "clang/Basic/OpenCLImageTypes.def"
917 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
918 CanQualType OCLQueueTy, OCLNDRangeTy, OCLReserveIDTy;
919 CanQualType OMPArraySectionTy;
921 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
922 mutable QualType AutoDeductTy; // Deduction against 'auto'.
923 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
925 // Decl used to help define __builtin_va_list for some targets.
926 // The decl is built when constructing 'BuiltinVaListDecl'.
927 mutable Decl *VaListTagDecl;
929 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
930 SelectorTable &sels, Builtin::Context &builtins);
934 /// \brief Attach an external AST source to the AST context.
936 /// The external AST source provides the ability to load parts of
937 /// the abstract syntax tree as needed from some external storage,
938 /// e.g., a precompiled header.
939 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
941 /// \brief Retrieve a pointer to the external AST source associated
942 /// with this AST context, if any.
943 ExternalASTSource *getExternalSource() const {
944 return ExternalSource.get();
947 /// \brief Attach an AST mutation listener to the AST context.
949 /// The AST mutation listener provides the ability to track modifications to
950 /// the abstract syntax tree entities committed after they were initially
952 void setASTMutationListener(ASTMutationListener *Listener) {
953 this->Listener = Listener;
956 /// \brief Retrieve a pointer to the AST mutation listener associated
957 /// with this AST context, if any.
958 ASTMutationListener *getASTMutationListener() const { return Listener; }
960 void PrintStats() const;
961 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
963 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
964 const IdentifierInfo *II) const;
966 /// \brief Create a new implicit TU-level CXXRecordDecl or RecordDecl
968 RecordDecl *buildImplicitRecord(StringRef Name,
969 RecordDecl::TagKind TK = TTK_Struct) const;
971 /// \brief Create a new implicit TU-level typedef declaration.
972 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
974 /// \brief Retrieve the declaration for the 128-bit signed integer type.
975 TypedefDecl *getInt128Decl() const;
977 /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
978 TypedefDecl *getUInt128Decl() const;
980 //===--------------------------------------------------------------------===//
982 //===--------------------------------------------------------------------===//
985 /// \brief Return a type with extended qualifiers.
986 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
988 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
991 /// \brief Return the uniqued reference to the type for an address space
992 /// qualified type with the specified type and address space.
994 /// The resulting type has a union of the qualifiers from T and the address
995 /// space. If T already has an address space specifier, it is silently
997 QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
999 /// \brief Return the uniqued reference to the type for an Objective-C
1000 /// gc-qualified type.
1002 /// The retulting type has a union of the qualifiers from T and the gc
1004 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1006 /// \brief Return the uniqued reference to the type for a \c restrict
1009 /// The resulting type has a union of the qualifiers from \p T and
1011 QualType getRestrictType(QualType T) const {
1012 return T.withFastQualifiers(Qualifiers::Restrict);
1015 /// \brief Return the uniqued reference to the type for a \c volatile
1018 /// The resulting type has a union of the qualifiers from \p T and
1020 QualType getVolatileType(QualType T) const {
1021 return T.withFastQualifiers(Qualifiers::Volatile);
1024 /// \brief Return the uniqued reference to the type for a \c const
1027 /// The resulting type has a union of the qualifiers from \p T and \c const.
1029 /// It can be reasonably expected that this will always be equivalent to
1030 /// calling T.withConst().
1031 QualType getConstType(QualType T) const { return T.withConst(); }
1033 /// \brief Change the ExtInfo on a function type.
1034 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1035 FunctionType::ExtInfo EInfo);
1037 /// Adjust the given function result type.
1038 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1040 /// \brief Change the result type of a function type once it is deduced.
1041 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1043 /// \brief Change the exception specification on a function once it is
1044 /// delay-parsed, instantiated, or computed.
1045 void adjustExceptionSpec(FunctionDecl *FD,
1046 const FunctionProtoType::ExceptionSpecInfo &ESI,
1047 bool AsWritten = false);
1049 /// \brief Return the uniqued reference to the type for a complex
1050 /// number with the specified element type.
1051 QualType getComplexType(QualType T) const;
1052 CanQualType getComplexType(CanQualType T) const {
1053 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1056 /// \brief Return the uniqued reference to the type for a pointer to
1057 /// the specified type.
1058 QualType getPointerType(QualType T) const;
1059 CanQualType getPointerType(CanQualType T) const {
1060 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1063 /// \brief Return the uniqued reference to a type adjusted from the original
1064 /// type to a new type.
1065 QualType getAdjustedType(QualType Orig, QualType New) const;
1066 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1067 return CanQualType::CreateUnsafe(
1068 getAdjustedType((QualType)Orig, (QualType)New));
1071 /// \brief Return the uniqued reference to the decayed version of the given
1072 /// type. Can only be called on array and function types which decay to
1074 QualType getDecayedType(QualType T) const;
1075 CanQualType getDecayedType(CanQualType T) const {
1076 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1079 /// \brief Return the uniqued reference to the atomic type for the specified
1081 QualType getAtomicType(QualType T) const;
1083 /// \brief Return the uniqued reference to the type for a block of the
1085 QualType getBlockPointerType(QualType T) const;
1087 /// Gets the struct used to keep track of the descriptor for pointer to
1089 QualType getBlockDescriptorType() const;
1091 /// \brief Return pipe type for the specified type.
1092 QualType getPipeType(QualType T) const;
1094 /// Gets the struct used to keep track of the extended descriptor for
1095 /// pointer to blocks.
1096 QualType getBlockDescriptorExtendedType() const;
1098 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1099 cudaConfigureCallDecl = FD;
1101 FunctionDecl *getcudaConfigureCallDecl() {
1102 return cudaConfigureCallDecl;
1105 /// Returns true iff we need copy/dispose helpers for the given type.
1106 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1109 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set
1110 /// to false in this case. If HasByrefExtendedLayout returns true, byref variable
1111 /// has extended lifetime.
1112 bool getByrefLifetime(QualType Ty,
1113 Qualifiers::ObjCLifetime &Lifetime,
1114 bool &HasByrefExtendedLayout) const;
1116 /// \brief Return the uniqued reference to the type for an lvalue reference
1117 /// to the specified type.
1118 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1121 /// \brief Return the uniqued reference to the type for an rvalue reference
1122 /// to the specified type.
1123 QualType getRValueReferenceType(QualType T) const;
1125 /// \brief Return the uniqued reference to the type for a member pointer to
1126 /// the specified type in the specified class.
1128 /// The class \p Cls is a \c Type because it could be a dependent name.
1129 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1131 /// \brief Return a non-unique reference to the type for a variable array of
1132 /// the specified element type.
1133 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1134 ArrayType::ArraySizeModifier ASM,
1135 unsigned IndexTypeQuals,
1136 SourceRange Brackets) const;
1138 /// \brief Return a non-unique reference to the type for a dependently-sized
1139 /// array of the specified element type.
1141 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1143 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1144 ArrayType::ArraySizeModifier ASM,
1145 unsigned IndexTypeQuals,
1146 SourceRange Brackets) const;
1148 /// \brief Return a unique reference to the type for an incomplete array of
1149 /// the specified element type.
1150 QualType getIncompleteArrayType(QualType EltTy,
1151 ArrayType::ArraySizeModifier ASM,
1152 unsigned IndexTypeQuals) const;
1154 /// \brief Return the unique reference to the type for a constant array of
1155 /// the specified element type.
1156 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1157 ArrayType::ArraySizeModifier ASM,
1158 unsigned IndexTypeQuals) const;
1160 /// \brief Returns a vla type where known sizes are replaced with [*].
1161 QualType getVariableArrayDecayedType(QualType Ty) const;
1163 /// \brief Return the unique reference to a vector type of the specified
1164 /// element type and size.
1166 /// \pre \p VectorType must be a built-in type.
1167 QualType getVectorType(QualType VectorType, unsigned NumElts,
1168 VectorType::VectorKind VecKind) const;
1170 /// \brief Return the unique reference to an extended vector type
1171 /// of the specified element type and size.
1173 /// \pre \p VectorType must be a built-in type.
1174 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1176 /// \pre Return a non-unique reference to the type for a dependently-sized
1177 /// vector of the specified element type.
1179 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1181 QualType getDependentSizedExtVectorType(QualType VectorType,
1183 SourceLocation AttrLoc) const;
1185 /// \brief Return a K&R style C function type like 'int()'.
1186 QualType getFunctionNoProtoType(QualType ResultTy,
1187 const FunctionType::ExtInfo &Info) const;
1189 QualType getFunctionNoProtoType(QualType ResultTy) const {
1190 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1193 /// \brief Return a normal function type with a typed argument list.
1194 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1195 const FunctionProtoType::ExtProtoInfo &EPI) const;
1197 /// \brief Return the unique reference to the type for the specified type
1199 QualType getTypeDeclType(const TypeDecl *Decl,
1200 const TypeDecl *PrevDecl = nullptr) const {
1201 assert(Decl && "Passed null for Decl param");
1202 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1205 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1206 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1207 return QualType(PrevDecl->TypeForDecl, 0);
1210 return getTypeDeclTypeSlow(Decl);
1213 /// \brief Return the unique reference to the type for the specified
1214 /// typedef-name decl.
1215 QualType getTypedefType(const TypedefNameDecl *Decl,
1216 QualType Canon = QualType()) const;
1218 QualType getRecordType(const RecordDecl *Decl) const;
1220 QualType getEnumType(const EnumDecl *Decl) const;
1222 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1224 QualType getAttributedType(AttributedType::Kind attrKind,
1225 QualType modifiedType,
1226 QualType equivalentType);
1228 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1229 QualType Replacement) const;
1230 QualType getSubstTemplateTypeParmPackType(
1231 const TemplateTypeParmType *Replaced,
1232 const TemplateArgument &ArgPack);
1235 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1237 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1239 QualType getTemplateSpecializationType(TemplateName T,
1240 ArrayRef<TemplateArgument> Args,
1241 QualType Canon = QualType()) const;
1244 getCanonicalTemplateSpecializationType(TemplateName T,
1245 ArrayRef<TemplateArgument> Args) const;
1247 QualType getTemplateSpecializationType(TemplateName T,
1248 const TemplateArgumentListInfo &Args,
1249 QualType Canon = QualType()) const;
1252 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1253 const TemplateArgumentListInfo &Args,
1254 QualType Canon = QualType()) const;
1256 QualType getParenType(QualType NamedType) const;
1258 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1259 NestedNameSpecifier *NNS,
1260 QualType NamedType) const;
1261 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1262 NestedNameSpecifier *NNS,
1263 const IdentifierInfo *Name,
1264 QualType Canon = QualType()) const;
1266 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1267 NestedNameSpecifier *NNS,
1268 const IdentifierInfo *Name,
1269 const TemplateArgumentListInfo &Args) const;
1270 QualType getDependentTemplateSpecializationType(
1271 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1272 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1274 QualType getPackExpansionType(QualType Pattern,
1275 Optional<unsigned> NumExpansions);
1277 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1278 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1280 /// Legacy interface: cannot provide type arguments or __kindof.
1281 QualType getObjCObjectType(QualType Base,
1282 ObjCProtocolDecl * const *Protocols,
1283 unsigned NumProtocols) const;
1285 QualType getObjCObjectType(QualType Base,
1286 ArrayRef<QualType> typeArgs,
1287 ArrayRef<ObjCProtocolDecl *> protocols,
1288 bool isKindOf) const;
1290 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1291 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1292 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1294 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1295 ObjCInterfaceDecl *IDecl);
1297 /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1298 QualType getObjCObjectPointerType(QualType OIT) const;
1300 /// \brief GCC extension.
1301 QualType getTypeOfExprType(Expr *e) const;
1302 QualType getTypeOfType(QualType t) const;
1304 /// \brief C++11 decltype.
1305 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1307 /// \brief Unary type transforms
1308 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1309 UnaryTransformType::UTTKind UKind) const;
1311 /// \brief C++11 deduced auto type.
1312 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1313 bool IsDependent) const;
1315 /// \brief C++11 deduction pattern for 'auto' type.
1316 QualType getAutoDeductType() const;
1318 /// \brief C++11 deduction pattern for 'auto &&' type.
1319 QualType getAutoRRefDeductType() const;
1321 /// \brief Return the unique reference to the type for the specified TagDecl
1322 /// (struct/union/class/enum) decl.
1323 QualType getTagDeclType(const TagDecl *Decl) const;
1325 /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1328 /// The sizeof operator requires this (C99 6.5.3.4p4).
1329 CanQualType getSizeType() const;
1331 /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1333 CanQualType getIntMaxType() const;
1335 /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1337 CanQualType getUIntMaxType() const;
1339 /// \brief Return the unique wchar_t type available in C++ (and available as
1340 /// __wchar_t as a Microsoft extension).
1341 QualType getWCharType() const { return WCharTy; }
1343 /// \brief Return the type of wide characters. In C++, this returns the
1344 /// unique wchar_t type. In C99, this returns a type compatible with the type
1345 /// defined in <stddef.h> as defined by the target.
1346 QualType getWideCharType() const { return WideCharTy; }
1348 /// \brief Return the type of "signed wchar_t".
1350 /// Used when in C++, as a GCC extension.
1351 QualType getSignedWCharType() const;
1353 /// \brief Return the type of "unsigned wchar_t".
1355 /// Used when in C++, as a GCC extension.
1356 QualType getUnsignedWCharType() const;
1358 /// \brief In C99, this returns a type compatible with the type
1359 /// defined in <stddef.h> as defined by the target.
1360 QualType getWIntType() const { return WIntTy; }
1362 /// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4),
1363 /// as defined by the target.
1364 QualType getIntPtrType() const;
1366 /// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1367 /// as defined by the target.
1368 QualType getUIntPtrType() const;
1370 /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1371 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1372 QualType getPointerDiffType() const;
1374 /// \brief Return the unique type for "pid_t" defined in
1375 /// <sys/types.h>. We need this to compute the correct type for vfork().
1376 QualType getProcessIDType() const;
1378 /// \brief Return the C structure type used to represent constant CFStrings.
1379 QualType getCFConstantStringType() const;
1381 /// \brief Returns the C struct type for objc_super
1382 QualType getObjCSuperType() const;
1383 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1385 /// Get the structure type used to representation CFStrings, or NULL
1386 /// if it hasn't yet been built.
1387 QualType getRawCFConstantStringType() const {
1388 if (CFConstantStringTypeDecl)
1389 return getTypedefType(CFConstantStringTypeDecl);
1392 void setCFConstantStringType(QualType T);
1393 TypedefDecl *getCFConstantStringDecl() const;
1394 RecordDecl *getCFConstantStringTagDecl() const;
1396 // This setter/getter represents the ObjC type for an NSConstantString.
1397 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1398 QualType getObjCConstantStringInterface() const {
1399 return ObjCConstantStringType;
1402 QualType getObjCNSStringType() const {
1403 return ObjCNSStringType;
1406 void setObjCNSStringType(QualType T) {
1407 ObjCNSStringType = T;
1410 /// \brief Retrieve the type that \c id has been defined to, which may be
1411 /// different from the built-in \c id if \c id has been typedef'd.
1412 QualType getObjCIdRedefinitionType() const {
1413 if (ObjCIdRedefinitionType.isNull())
1414 return getObjCIdType();
1415 return ObjCIdRedefinitionType;
1418 /// \brief Set the user-written type that redefines \c id.
1419 void setObjCIdRedefinitionType(QualType RedefType) {
1420 ObjCIdRedefinitionType = RedefType;
1423 /// \brief Retrieve the type that \c Class has been defined to, which may be
1424 /// different from the built-in \c Class if \c Class has been typedef'd.
1425 QualType getObjCClassRedefinitionType() const {
1426 if (ObjCClassRedefinitionType.isNull())
1427 return getObjCClassType();
1428 return ObjCClassRedefinitionType;
1431 /// \brief Set the user-written type that redefines 'SEL'.
1432 void setObjCClassRedefinitionType(QualType RedefType) {
1433 ObjCClassRedefinitionType = RedefType;
1436 /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1437 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1438 QualType getObjCSelRedefinitionType() const {
1439 if (ObjCSelRedefinitionType.isNull())
1440 return getObjCSelType();
1441 return ObjCSelRedefinitionType;
1445 /// \brief Set the user-written type that redefines 'SEL'.
1446 void setObjCSelRedefinitionType(QualType RedefType) {
1447 ObjCSelRedefinitionType = RedefType;
1450 /// Retrieve the identifier 'NSObject'.
1451 IdentifierInfo *getNSObjectName() {
1452 if (!NSObjectName) {
1453 NSObjectName = &Idents.get("NSObject");
1456 return NSObjectName;
1459 /// Retrieve the identifier 'NSCopying'.
1460 IdentifierInfo *getNSCopyingName() {
1461 if (!NSCopyingName) {
1462 NSCopyingName = &Idents.get("NSCopying");
1465 return NSCopyingName;
1468 /// Retrieve the identifier 'bool'.
1469 IdentifierInfo *getBoolName() const {
1471 BoolName = &Idents.get("bool");
1475 IdentifierInfo *getMakeIntegerSeqName() const {
1476 if (!MakeIntegerSeqName)
1477 MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1478 return MakeIntegerSeqName;
1481 IdentifierInfo *getTypePackElementName() const {
1482 if (!TypePackElementName)
1483 TypePackElementName = &Idents.get("__type_pack_element");
1484 return TypePackElementName;
1487 /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1488 /// otherwise, returns a NULL type;
1489 QualType getObjCInstanceType() {
1490 return getTypeDeclType(getObjCInstanceTypeDecl());
1493 /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1494 /// "instancetype" type.
1495 TypedefDecl *getObjCInstanceTypeDecl();
1497 /// \brief Set the type for the C FILE type.
1498 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1500 /// \brief Retrieve the C FILE type.
1501 QualType getFILEType() const {
1503 return getTypeDeclType(FILEDecl);
1507 /// \brief Set the type for the C jmp_buf type.
1508 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1509 this->jmp_bufDecl = jmp_bufDecl;
1512 /// \brief Retrieve the C jmp_buf type.
1513 QualType getjmp_bufType() const {
1515 return getTypeDeclType(jmp_bufDecl);
1519 /// \brief Set the type for the C sigjmp_buf type.
1520 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1521 this->sigjmp_bufDecl = sigjmp_bufDecl;
1524 /// \brief Retrieve the C sigjmp_buf type.
1525 QualType getsigjmp_bufType() const {
1527 return getTypeDeclType(sigjmp_bufDecl);
1531 /// \brief Set the type for the C ucontext_t type.
1532 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1533 this->ucontext_tDecl = ucontext_tDecl;
1536 /// \brief Retrieve the C ucontext_t type.
1537 QualType getucontext_tType() const {
1539 return getTypeDeclType(ucontext_tDecl);
1543 /// \brief The result type of logical operations, '<', '>', '!=', etc.
1544 QualType getLogicalOperationType() const {
1545 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1548 /// \brief Emit the Objective-CC type encoding for the given type \p T into
1551 /// If \p Field is specified then record field names are also encoded.
1552 void getObjCEncodingForType(QualType T, std::string &S,
1553 const FieldDecl *Field=nullptr,
1554 QualType *NotEncodedT=nullptr) const;
1556 /// \brief Emit the Objective-C property type encoding for the given
1557 /// type \p T into \p S.
1558 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1560 void getLegacyIntegralTypeEncoding(QualType &t) const;
1562 /// \brief Put the string version of the type qualifiers \p QT into \p S.
1563 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1564 std::string &S) const;
1566 /// \brief Emit the encoded type for the function \p Decl into \p S.
1568 /// This is in the same format as Objective-C method encodings.
1570 /// \returns true if an error occurred (e.g., because one of the parameter
1571 /// types is incomplete), false otherwise.
1572 bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1574 /// \brief Emit the encoded type for the method declaration \p Decl into
1577 /// \returns true if an error occurred (e.g., because one of the parameter
1578 /// types is incomplete), false otherwise.
1579 bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1580 bool Extended = false)
1583 /// \brief Return the encoded type for this block declaration.
1584 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1586 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1587 /// this method declaration. If non-NULL, Container must be either
1588 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1589 /// only be NULL when getting encodings for protocol properties.
1590 void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1591 const Decl *Container,
1592 std::string &S) const;
1594 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1595 ObjCProtocolDecl *rProto) const;
1597 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1598 const ObjCPropertyDecl *PD,
1599 const Decl *Container) const;
1601 /// \brief Return the size of type \p T for Objective-C encoding purpose,
1603 CharUnits getObjCEncodingTypeSize(QualType T) const;
1605 /// \brief Retrieve the typedef corresponding to the predefined \c id type
1607 TypedefDecl *getObjCIdDecl() const;
1609 /// \brief Represents the Objective-CC \c id type.
1611 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1612 /// pointer type, a pointer to a struct.
1613 QualType getObjCIdType() const {
1614 return getTypeDeclType(getObjCIdDecl());
1617 /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1619 TypedefDecl *getObjCSelDecl() const;
1621 /// \brief Retrieve the type that corresponds to the predefined Objective-C
1623 QualType getObjCSelType() const {
1624 return getTypeDeclType(getObjCSelDecl());
1627 /// \brief Retrieve the typedef declaration corresponding to the predefined
1628 /// Objective-C 'Class' type.
1629 TypedefDecl *getObjCClassDecl() const;
1631 /// \brief Represents the Objective-C \c Class type.
1633 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1634 /// pointer type, a pointer to a struct.
1635 QualType getObjCClassType() const {
1636 return getTypeDeclType(getObjCClassDecl());
1639 /// \brief Retrieve the Objective-C class declaration corresponding to
1640 /// the predefined \c Protocol class.
1641 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1643 /// \brief Retrieve declaration of 'BOOL' typedef
1644 TypedefDecl *getBOOLDecl() const {
1648 /// \brief Save declaration of 'BOOL' typedef
1649 void setBOOLDecl(TypedefDecl *TD) {
1653 /// \brief type of 'BOOL' type.
1654 QualType getBOOLType() const {
1655 return getTypeDeclType(getBOOLDecl());
1658 /// \brief Retrieve the type of the Objective-C \c Protocol class.
1659 QualType getObjCProtoType() const {
1660 return getObjCInterfaceType(getObjCProtocolDecl());
1663 /// \brief Retrieve the C type declaration corresponding to the predefined
1664 /// \c __builtin_va_list type.
1665 TypedefDecl *getBuiltinVaListDecl() const;
1667 /// \brief Retrieve the type of the \c __builtin_va_list type.
1668 QualType getBuiltinVaListType() const {
1669 return getTypeDeclType(getBuiltinVaListDecl());
1672 /// \brief Retrieve the C type declaration corresponding to the predefined
1673 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1674 /// for some targets.
1675 Decl *getVaListTagDecl() const;
1677 /// Retrieve the C type declaration corresponding to the predefined
1678 /// \c __builtin_ms_va_list type.
1679 TypedefDecl *getBuiltinMSVaListDecl() const;
1681 /// Retrieve the type of the \c __builtin_ms_va_list type.
1682 QualType getBuiltinMSVaListType() const {
1683 return getTypeDeclType(getBuiltinMSVaListDecl());
1686 /// \brief Return a type with additional \c const, \c volatile, or
1687 /// \c restrict qualifiers.
1688 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1689 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1692 /// \brief Un-split a SplitQualType.
1693 QualType getQualifiedType(SplitQualType split) const {
1694 return getQualifiedType(split.Ty, split.Quals);
1697 /// \brief Return a type with additional qualifiers.
1698 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1699 if (!Qs.hasNonFastQualifiers())
1700 return T.withFastQualifiers(Qs.getFastQualifiers());
1701 QualifierCollector Qc(Qs);
1702 const Type *Ptr = Qc.strip(T);
1703 return getExtQualType(Ptr, Qc);
1706 /// \brief Return a type with additional qualifiers.
1707 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1708 if (!Qs.hasNonFastQualifiers())
1709 return QualType(T, Qs.getFastQualifiers());
1710 return getExtQualType(T, Qs);
1713 /// \brief Return a type with the given lifetime qualifier.
1715 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1716 QualType getLifetimeQualifiedType(QualType type,
1717 Qualifiers::ObjCLifetime lifetime) {
1718 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1719 assert(lifetime != Qualifiers::OCL_None);
1722 qs.addObjCLifetime(lifetime);
1723 return getQualifiedType(type, qs);
1726 /// getUnqualifiedObjCPointerType - Returns version of
1727 /// Objective-C pointer type with lifetime qualifier removed.
1728 QualType getUnqualifiedObjCPointerType(QualType type) const {
1729 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1730 !type.getQualifiers().hasObjCLifetime())
1732 Qualifiers Qs = type.getQualifiers();
1733 Qs.removeObjCLifetime();
1734 return getQualifiedType(type.getUnqualifiedType(), Qs);
1737 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1738 SourceLocation NameLoc) const;
1740 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1741 UnresolvedSetIterator End) const;
1743 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1744 bool TemplateKeyword,
1745 TemplateDecl *Template) const;
1747 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1748 const IdentifierInfo *Name) const;
1749 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1750 OverloadedOperatorKind Operator) const;
1751 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1752 TemplateName replacement) const;
1753 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1754 const TemplateArgument &ArgPack) const;
1756 enum GetBuiltinTypeError {
1757 GE_None, ///< No error
1758 GE_Missing_stdio, ///< Missing a type from <stdio.h>
1759 GE_Missing_setjmp, ///< Missing a type from <setjmp.h>
1760 GE_Missing_ucontext ///< Missing a type from <ucontext.h>
1763 /// \brief Return the type for the specified builtin.
1765 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1766 /// arguments to the builtin that are required to be integer constant
1768 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1769 unsigned *IntegerConstantArgs = nullptr) const;
1772 CanQualType getFromTargetType(unsigned Type) const;
1773 TypeInfo getTypeInfoImpl(const Type *T) const;
1775 //===--------------------------------------------------------------------===//
1777 //===--------------------------------------------------------------------===//
1780 /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1781 /// collection attributes.
1782 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1784 /// \brief Return true if the given vector types are of the same unqualified
1785 /// type or if they are equivalent to the same GCC vector type.
1787 /// \note This ignores whether they are target-specific (AltiVec or Neon)
1789 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1791 /// \brief Return true if this is an \c NSObject object with its \c NSObject
1793 static bool isObjCNSObjectType(QualType Ty) {
1794 return Ty->isObjCNSObjectType();
1797 //===--------------------------------------------------------------------===//
1798 // Type Sizing and Analysis
1799 //===--------------------------------------------------------------------===//
1801 /// \brief Return the APFloat 'semantics' for the specified scalar floating
1803 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1805 /// \brief Get the size and alignment of the specified complete type in bits.
1806 TypeInfo getTypeInfo(const Type *T) const;
1807 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
1809 /// \brief Get default simd alignment of the specified complete type in bits.
1810 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
1812 /// \brief Return the size of the specified (complete) type \p T, in bits.
1813 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
1814 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
1816 /// \brief Return the size of the character type, in bits.
1817 uint64_t getCharWidth() const {
1818 return getTypeSize(CharTy);
1821 /// \brief Convert a size in bits to a size in characters.
1822 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1824 /// \brief Convert a size in characters to a size in bits.
1825 int64_t toBits(CharUnits CharSize) const;
1827 /// \brief Return the size of the specified (complete) type \p T, in
1829 CharUnits getTypeSizeInChars(QualType T) const;
1830 CharUnits getTypeSizeInChars(const Type *T) const;
1832 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1834 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
1835 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
1837 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1839 CharUnits getTypeAlignInChars(QualType T) const;
1840 CharUnits getTypeAlignInChars(const Type *T) const;
1842 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1843 // type is a record, its data size is returned.
1844 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1846 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1847 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1849 /// \brief Determine if the alignment the type has was required using an
1850 /// alignment attribute.
1851 bool isAlignmentRequired(const Type *T) const;
1852 bool isAlignmentRequired(QualType T) const;
1854 /// \brief Return the "preferred" alignment of the specified type \p T for
1855 /// the current target, in bits.
1857 /// This can be different than the ABI alignment in cases where it is
1858 /// beneficial for performance to overalign a data type.
1859 unsigned getPreferredTypeAlign(const Type *T) const;
1861 /// \brief Return the default alignment for __attribute__((aligned)) on
1862 /// this target, to be used if no alignment value is specified.
1863 unsigned getTargetDefaultAlignForAttributeAligned(void) const;
1865 /// \brief Return the alignment in bits that should be given to a
1866 /// global variable with type \p T.
1867 unsigned getAlignOfGlobalVar(QualType T) const;
1869 /// \brief Return the alignment in characters that should be given to a
1870 /// global variable with type \p T.
1871 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
1873 /// \brief Return a conservative estimate of the alignment of the specified
1876 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
1879 /// If \p ForAlignof, references are treated like their underlying type
1880 /// and large arrays don't get any special treatment. If not \p ForAlignof
1881 /// it computes the value expected by CodeGen: references are treated like
1882 /// pointers and large arrays get extra alignment.
1883 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
1885 /// \brief Get or compute information about the layout of the specified
1886 /// record (struct/union/class) \p D, which indicates its size and field
1887 /// position information.
1888 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1890 /// \brief Get or compute information about the layout of the specified
1891 /// Objective-C interface.
1892 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1895 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
1896 bool Simple = false) const;
1898 /// \brief Get or compute information about the layout of the specified
1899 /// Objective-C implementation.
1901 /// This may differ from the interface if synthesized ivars are present.
1902 const ASTRecordLayout &
1903 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1905 /// \brief Get our current best idea for the key function of the
1906 /// given record decl, or NULL if there isn't one.
1908 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
1909 /// ...the first non-pure virtual function that is not inline at the
1910 /// point of class definition.
1912 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
1913 /// virtual functions that are defined 'inline', which means that
1914 /// the result of this computation can change.
1915 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
1917 /// \brief Observe that the given method cannot be a key function.
1918 /// Checks the key-function cache for the method's class and clears it
1919 /// if matches the given declaration.
1921 /// This is used in ABIs where out-of-line definitions marked
1922 /// inline are not considered to be key functions.
1924 /// \param method should be the declaration from the class definition
1925 void setNonKeyFunction(const CXXMethodDecl *method);
1927 /// Loading virtual member pointers using the virtual inheritance model
1928 /// always results in an adjustment using the vbtable even if the index is
1931 /// This is usually OK because the first slot in the vbtable points
1932 /// backwards to the top of the MDC. However, the MDC might be reusing a
1933 /// vbptr from an nv-base. In this case, the first slot in the vbtable
1934 /// points to the start of the nv-base which introduced the vbptr and *not*
1935 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
1936 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
1938 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1939 uint64_t getFieldOffset(const ValueDecl *FD) const;
1941 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1943 VTableContextBase *getVTableContext();
1945 MangleContext *createMangleContext();
1947 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1948 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1950 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1951 void CollectInheritedProtocols(const Decl *CDecl,
1952 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1954 //===--------------------------------------------------------------------===//
1956 //===--------------------------------------------------------------------===//
1958 /// \brief Return the canonical (structural) type corresponding to the
1959 /// specified potentially non-canonical type \p T.
1961 /// The non-canonical version of a type may have many "decorated" versions of
1962 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
1963 /// returned type is guaranteed to be free of any of these, allowing two
1964 /// canonical types to be compared for exact equality with a simple pointer
1966 CanQualType getCanonicalType(QualType T) const {
1967 return CanQualType::CreateUnsafe(T.getCanonicalType());
1970 const Type *getCanonicalType(const Type *T) const {
1971 return T->getCanonicalTypeInternal().getTypePtr();
1974 /// \brief Return the canonical parameter type corresponding to the specific
1975 /// potentially non-canonical one.
1977 /// Qualifiers are stripped off, functions are turned into function
1978 /// pointers, and arrays decay one level into pointers.
1979 CanQualType getCanonicalParamType(QualType T) const;
1981 /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
1982 bool hasSameType(QualType T1, QualType T2) const {
1983 return getCanonicalType(T1) == getCanonicalType(T2);
1986 bool hasSameType(const Type *T1, const Type *T2) const {
1987 return getCanonicalType(T1) == getCanonicalType(T2);
1990 /// \brief Return this type as a completely-unqualified array type,
1991 /// capturing the qualifiers in \p Quals.
1993 /// This will remove the minimal amount of sugaring from the types, similar
1994 /// to the behavior of QualType::getUnqualifiedType().
1996 /// \param T is the qualified type, which may be an ArrayType
1998 /// \param Quals will receive the full set of qualifiers that were
1999 /// applied to the array.
2001 /// \returns if this is an array type, the completely unqualified array type
2002 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2003 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2005 /// \brief Determine whether the given types are equivalent after
2006 /// cvr-qualifiers have been removed.
2007 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2008 return getCanonicalType(T1).getTypePtr() ==
2009 getCanonicalType(T2).getTypePtr();
2012 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2013 bool IsParam) const {
2014 auto SubTnullability = SubT->getNullability(*this);
2015 auto SuperTnullability = SuperT->getNullability(*this);
2016 if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
2017 // Neither has nullability; return true
2018 if (!SubTnullability)
2020 // Both have nullability qualifier.
2021 if (*SubTnullability == *SuperTnullability ||
2022 *SubTnullability == NullabilityKind::Unspecified ||
2023 *SuperTnullability == NullabilityKind::Unspecified)
2027 // Ok for the superclass method parameter to be "nonnull" and the subclass
2028 // method parameter to be "nullable"
2029 return (*SuperTnullability == NullabilityKind::NonNull &&
2030 *SubTnullability == NullabilityKind::Nullable);
2033 // For the return type, it's okay for the superclass method to specify
2034 // "nullable" and the subclass method specify "nonnull"
2035 return (*SuperTnullability == NullabilityKind::Nullable &&
2036 *SubTnullability == NullabilityKind::NonNull);
2042 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2043 const ObjCMethodDecl *MethodImp);
2045 bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
2047 /// \brief Retrieves the "canonical" nested name specifier for a
2048 /// given nested name specifier.
2050 /// The canonical nested name specifier is a nested name specifier
2051 /// that uniquely identifies a type or namespace within the type
2052 /// system. For example, given:
2057 /// template<typename T> struct X { typename T* type; };
2061 /// template<typename T> struct Y {
2062 /// typename N::S::X<T>::type member;
2066 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2067 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2068 /// by declarations in the type system and the canonical type for
2069 /// the template type parameter 'T' is template-param-0-0.
2070 NestedNameSpecifier *
2071 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2073 /// \brief Retrieves the default calling convention for the current target.
2074 CallingConv getDefaultCallingConvention(bool isVariadic,
2075 bool IsCXXMethod) const;
2077 /// \brief Retrieves the "canonical" template name that refers to a
2080 /// The canonical template name is the simplest expression that can
2081 /// be used to refer to a given template. For most templates, this
2082 /// expression is just the template declaration itself. For example,
2083 /// the template std::vector can be referred to via a variety of
2084 /// names---std::vector, \::std::vector, vector (if vector is in
2085 /// scope), etc.---but all of these names map down to the same
2086 /// TemplateDecl, which is used to form the canonical template name.
2088 /// Dependent template names are more interesting. Here, the
2089 /// template name could be something like T::template apply or
2090 /// std::allocator<T>::template rebind, where the nested name
2091 /// specifier itself is dependent. In this case, the canonical
2092 /// template name uses the shortest form of the dependent
2093 /// nested-name-specifier, which itself contains all canonical
2094 /// types, values, and templates.
2095 TemplateName getCanonicalTemplateName(TemplateName Name) const;
2097 /// \brief Determine whether the given template names refer to the same
2099 bool hasSameTemplateName(TemplateName X, TemplateName Y);
2101 /// \brief Retrieve the "canonical" template argument.
2103 /// The canonical template argument is the simplest template argument
2104 /// (which may be a type, value, expression, or declaration) that
2105 /// expresses the value of the argument.
2106 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2109 /// Type Query functions. If the type is an instance of the specified class,
2110 /// return the Type pointer for the underlying maximally pretty type. This
2111 /// is a member of ASTContext because this may need to do some amount of
2112 /// canonicalization, e.g. to move type qualifiers into the element type.
2113 const ArrayType *getAsArrayType(QualType T) const;
2114 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2115 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2117 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2118 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2120 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2121 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2123 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2125 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2128 /// \brief Return the innermost element type of an array type.
2130 /// For example, will return "int" for int[m][n]
2131 QualType getBaseElementType(const ArrayType *VAT) const;
2133 /// \brief Return the innermost element type of a type (which needn't
2134 /// actually be an array type).
2135 QualType getBaseElementType(QualType QT) const;
2137 /// \brief Return number of constant array elements.
2138 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2140 /// \brief Perform adjustment on the parameter type of a function.
2142 /// This routine adjusts the given parameter type @p T to the actual
2143 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2144 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2145 QualType getAdjustedParameterType(QualType T) const;
2147 /// \brief Retrieve the parameter type as adjusted for use in the signature
2148 /// of a function, decaying array and function types and removing top-level
2150 QualType getSignatureParameterType(QualType T) const;
2152 QualType getExceptionObjectType(QualType T) const;
2154 /// \brief Return the properly qualified result of decaying the specified
2155 /// array type to a pointer.
2157 /// This operation is non-trivial when handling typedefs etc. The canonical
2158 /// type of \p T must be an array type, this returns a pointer to a properly
2159 /// qualified element of the array.
2161 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2162 QualType getArrayDecayedType(QualType T) const;
2164 /// \brief Return the type that \p PromotableType will promote to: C99
2165 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2166 QualType getPromotedIntegerType(QualType PromotableType) const;
2168 /// \brief Recurses in pointer/array types until it finds an Objective-C
2169 /// retainable type and returns its ownership.
2170 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2172 /// \brief Whether this is a promotable bitfield reference according
2173 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2175 /// \returns the type this bit-field will promote to, or NULL if no
2176 /// promotion occurs.
2177 QualType isPromotableBitField(Expr *E) const;
2179 /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
2181 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2182 /// \p LHS < \p RHS, return -1.
2183 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2185 /// \brief Compare the rank of the two specified floating point types,
2186 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2188 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2189 /// \p LHS < \p RHS, return -1.
2190 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2192 /// \brief Return a real floating point or a complex type (based on
2193 /// \p typeDomain/\p typeSize).
2195 /// \param typeDomain a real floating point or complex type.
2196 /// \param typeSize a real floating point or complex type.
2197 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2198 QualType typeDomain) const;
2200 unsigned getTargetAddressSpace(QualType T) const {
2201 return getTargetAddressSpace(T.getQualifiers());
2204 unsigned getTargetAddressSpace(Qualifiers Q) const {
2205 return getTargetAddressSpace(Q.getAddressSpace());
2208 unsigned getTargetAddressSpace(unsigned AS) const {
2209 if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
2212 return (*AddrSpaceMap)[AS - LangAS::Offset];
2215 bool addressSpaceMapManglingFor(unsigned AS) const {
2216 return AddrSpaceMapMangling ||
2217 AS < LangAS::Offset ||
2218 AS >= LangAS::Offset + LangAS::Count;
2222 // Helper for integer ordering
2223 unsigned getIntegerRank(const Type *T) const;
2227 //===--------------------------------------------------------------------===//
2228 // Type Compatibility Predicates
2229 //===--------------------------------------------------------------------===//
2231 /// Compatibility predicates used to check assignment expressions.
2232 bool typesAreCompatible(QualType T1, QualType T2,
2233 bool CompareUnqualified = false); // C99 6.2.7p1
2235 bool propertyTypesAreCompatible(QualType, QualType);
2236 bool typesAreBlockPointerCompatible(QualType, QualType);
2238 bool isObjCIdType(QualType T) const {
2239 return T == getObjCIdType();
2241 bool isObjCClassType(QualType T) const {
2242 return T == getObjCClassType();
2244 bool isObjCSelType(QualType T) const {
2245 return T == getObjCSelType();
2247 bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
2250 bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
2252 // Check the safety of assignment from LHS to RHS
2253 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2254 const ObjCObjectPointerType *RHSOPT);
2255 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2256 const ObjCObjectType *RHS);
2257 bool canAssignObjCInterfacesInBlockPointer(
2258 const ObjCObjectPointerType *LHSOPT,
2259 const ObjCObjectPointerType *RHSOPT,
2260 bool BlockReturnType);
2261 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2262 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2263 const ObjCObjectPointerType *RHSOPT);
2264 bool canBindObjCObjectType(QualType To, QualType From);
2266 // Functions for calculating composite types
2267 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2268 bool Unqualified = false, bool BlockReturnType = false);
2269 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2270 bool Unqualified = false);
2271 QualType mergeFunctionParameterTypes(QualType, QualType,
2272 bool OfBlockPointer = false,
2273 bool Unqualified = false);
2274 QualType mergeTransparentUnionType(QualType, QualType,
2275 bool OfBlockPointer=false,
2276 bool Unqualified = false);
2278 QualType mergeObjCGCQualifiers(QualType, QualType);
2280 bool doFunctionTypesMatchOnExtParameterInfos(
2281 const FunctionProtoType *FromFunctionType,
2282 const FunctionProtoType *ToFunctionType);
2284 void ResetObjCLayout(const ObjCContainerDecl *CD);
2286 //===--------------------------------------------------------------------===//
2287 // Integer Predicates
2288 //===--------------------------------------------------------------------===//
2290 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2291 // of bits in an integer type excluding any padding bits.
2292 unsigned getIntWidth(QualType T) const;
2294 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2295 // unsigned integer type. This method takes a signed type, and returns the
2296 // corresponding unsigned integer type.
2297 QualType getCorrespondingUnsignedType(QualType T) const;
2299 //===--------------------------------------------------------------------===//
2301 //===--------------------------------------------------------------------===//
2303 /// \brief Make an APSInt of the appropriate width and signedness for the
2304 /// given \p Value and integer \p Type.
2305 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2306 // If Type is a signed integer type larger than 64 bits, we need to be sure
2307 // to sign extend Res appropriately.
2308 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2310 unsigned Width = getIntWidth(Type);
2311 if (Width != Res.getBitWidth())
2312 return Res.extOrTrunc(Width);
2316 bool isSentinelNullExpr(const Expr *E);
2318 /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
2320 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2321 /// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
2323 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2325 /// \brief Return true if there is at least one \@implementation in the TU.
2326 bool AnyObjCImplementation() {
2327 return !ObjCImpls.empty();
2330 /// \brief Set the implementation of ObjCInterfaceDecl.
2331 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2332 ObjCImplementationDecl *ImplD);
2333 /// \brief Set the implementation of ObjCCategoryDecl.
2334 void setObjCImplementation(ObjCCategoryDecl *CatD,
2335 ObjCCategoryImplDecl *ImplD);
2337 /// \brief Get the duplicate declaration of a ObjCMethod in the same
2338 /// interface, or null if none exists.
2339 const ObjCMethodDecl *
2340 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2342 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2343 const ObjCMethodDecl *Redecl);
2345 /// \brief Returns the Objective-C interface that \p ND belongs to if it is
2346 /// an Objective-C method/property/ivar etc. that is part of an interface,
2347 /// otherwise returns null.
2348 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2350 /// \brief Set the copy inialization expression of a block var decl.
2351 void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2352 /// \brief Get the copy initialization expression of the VarDecl \p VD, or
2353 /// NULL if none exists.
2354 Expr *getBlockVarCopyInits(const VarDecl* VD);
2356 /// \brief Allocate an uninitialized TypeSourceInfo.
2358 /// The caller should initialize the memory held by TypeSourceInfo using
2359 /// the TypeLoc wrappers.
2361 /// \param T the type that will be the basis for type source info. This type
2362 /// should refer to how the declarator was written in source code, not to
2363 /// what type semantic analysis resolved the declarator to.
2365 /// \param Size the size of the type info to create, or 0 if the size
2366 /// should be calculated based on the type.
2367 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2369 /// \brief Allocate a TypeSourceInfo where all locations have been
2370 /// initialized to a given location, which defaults to the empty
2373 getTrivialTypeSourceInfo(QualType T,
2374 SourceLocation Loc = SourceLocation()) const;
2376 /// \brief Add a deallocation callback that will be invoked when the
2377 /// ASTContext is destroyed.
2379 /// \param Callback A callback function that will be invoked on destruction.
2381 /// \param Data Pointer data that will be provided to the callback function
2382 /// when it is called.
2383 void AddDeallocation(void (*Callback)(void*), void *Data);
2385 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2386 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2388 /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
2389 /// lazily, only when used; this is only relevant for function or file scoped
2390 /// var definitions.
2392 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2394 bool DeclMustBeEmitted(const Decl *D);
2396 const CXXConstructorDecl *
2397 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2399 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2400 CXXConstructorDecl *CD);
2402 void addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
2403 unsigned ParmIdx, Expr *DAE);
2405 Expr *getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
2408 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2410 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2412 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2414 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2416 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2417 unsigned getManglingNumber(const NamedDecl *ND) const;
2419 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2420 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2422 /// \brief Retrieve the context for computing mangling numbers in the given
2424 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2426 MangleNumberingContext *createMangleNumberingContext() const;
2428 /// \brief Used by ParmVarDecl to store on the side the
2429 /// index of the parameter when it exceeds the size of the normal bitfield.
2430 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2432 /// \brief Used by ParmVarDecl to retrieve on the side the
2433 /// index of the parameter when it exceeds the size of the normal bitfield.
2434 unsigned getParameterIndex(const ParmVarDecl *D) const;
2436 /// \brief Get the storage for the constant value of a materialized temporary
2437 /// of static storage duration.
2438 APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
2441 //===--------------------------------------------------------------------===//
2443 //===--------------------------------------------------------------------===//
2445 /// \brief The number of implicitly-declared default constructors.
2446 static unsigned NumImplicitDefaultConstructors;
2448 /// \brief The number of implicitly-declared default constructors for
2449 /// which declarations were built.
2450 static unsigned NumImplicitDefaultConstructorsDeclared;
2452 /// \brief The number of implicitly-declared copy constructors.
2453 static unsigned NumImplicitCopyConstructors;
2455 /// \brief The number of implicitly-declared copy constructors for
2456 /// which declarations were built.
2457 static unsigned NumImplicitCopyConstructorsDeclared;
2459 /// \brief The number of implicitly-declared move constructors.
2460 static unsigned NumImplicitMoveConstructors;
2462 /// \brief The number of implicitly-declared move constructors for
2463 /// which declarations were built.
2464 static unsigned NumImplicitMoveConstructorsDeclared;
2466 /// \brief The number of implicitly-declared copy assignment operators.
2467 static unsigned NumImplicitCopyAssignmentOperators;
2469 /// \brief The number of implicitly-declared copy assignment operators for
2470 /// which declarations were built.
2471 static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2473 /// \brief The number of implicitly-declared move assignment operators.
2474 static unsigned NumImplicitMoveAssignmentOperators;
2476 /// \brief The number of implicitly-declared move assignment operators for
2477 /// which declarations were built.
2478 static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2480 /// \brief The number of implicitly-declared destructors.
2481 static unsigned NumImplicitDestructors;
2483 /// \brief The number of implicitly-declared destructors for which
2484 /// declarations were built.
2485 static unsigned NumImplicitDestructorsDeclared;
2488 ASTContext(const ASTContext &) = delete;
2489 void operator=(const ASTContext &) = delete;
2492 /// \brief Initialize built-in types.
2494 /// This routine may only be invoked once for a given ASTContext object.
2495 /// It is normally invoked after ASTContext construction.
2497 /// \param Target The target
2498 void InitBuiltinTypes(const TargetInfo &Target,
2499 const TargetInfo *AuxTarget = nullptr);
2502 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2504 // Return the Objective-C type encoding for a given type.
2505 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2506 bool ExpandPointedToStructures,
2507 bool ExpandStructures,
2508 const FieldDecl *Field,
2509 bool OutermostType = false,
2510 bool EncodingProperty = false,
2511 bool StructField = false,
2512 bool EncodeBlockParameters = false,
2513 bool EncodeClassNames = false,
2514 bool EncodePointerToObjCTypedef = false,
2515 QualType *NotEncodedT=nullptr) const;
2517 // Adds the encoding of the structure's members.
2518 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2519 const FieldDecl *Field,
2520 bool includeVBases = true,
2521 QualType *NotEncodedT=nullptr) const;
2523 // Adds the encoding of a method parameter or return type.
2524 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2525 QualType T, std::string& S,
2526 bool Extended) const;
2528 /// \brief Returns true if this is an inline-initialized static data member
2529 /// which is treated as a definition for MSVC compatibility.
2530 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2532 enum class InlineVariableDefinitionKind {
2533 None, ///< Not an inline variable.
2534 Weak, ///< Weak definition of inline variable.
2535 WeakUnknown, ///< Weak for now, might become strong later in this TU.
2536 Strong ///< Strong definition.
2538 /// \brief Determine whether a definition of this inline variable should
2539 /// be treated as a weak or strong definition. For compatibility with
2540 /// C++14 and before, for a constexpr static data member, if there is an
2541 /// out-of-line declaration of the member, we may promote it from weak to
2543 InlineVariableDefinitionKind
2544 getInlineVariableDefinitionKind(const VarDecl *VD) const;
2547 const ASTRecordLayout &
2548 getObjCLayout(const ObjCInterfaceDecl *D,
2549 const ObjCImplementationDecl *Impl) const;
2551 /// \brief A set of deallocations that should be performed when the
2552 /// ASTContext is destroyed.
2553 // FIXME: We really should have a better mechanism in the ASTContext to
2554 // manage running destructors for types which do variable sized allocation
2555 // within the AST. In some places we thread the AST bump pointer allocator
2556 // into the datastructures which avoids this mess during deallocation but is
2557 // wasteful of memory, and here we require a lot of error prone book keeping
2558 // in order to track and run destructors while we're tearing things down.
2559 typedef llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>
2560 DeallocationFunctionsAndArguments;
2561 DeallocationFunctionsAndArguments Deallocations;
2563 // FIXME: This currently contains the set of StoredDeclMaps used
2564 // by DeclContext objects. This probably should not be in ASTContext,
2565 // but we include it here so that ASTContext can quickly deallocate them.
2566 llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2568 friend class DeclContext;
2569 friend class DeclarationNameTable;
2570 void ReleaseDeclContextMaps();
2571 void ReleaseParentMapEntries();
2573 std::unique_ptr<ParentMapPointers> PointerParents;
2574 std::unique_ptr<ParentMapOtherNodes> OtherParents;
2576 std::unique_ptr<VTableContextBase> VTContext;
2579 enum PragmaSectionFlag : unsigned {
2585 PSF_Invalid = 0x80000000U,
2588 struct SectionInfo {
2589 DeclaratorDecl *Decl;
2590 SourceLocation PragmaSectionLocation;
2593 SectionInfo(DeclaratorDecl *Decl,
2594 SourceLocation PragmaSectionLocation,
2597 PragmaSectionLocation(PragmaSectionLocation),
2598 SectionFlags(SectionFlags) {}
2601 llvm::StringMap<SectionInfo> SectionInfos;
2604 /// \brief Utility function for constructing a nullary selector.
2605 static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2606 IdentifierInfo* II = &Ctx.Idents.get(name);
2607 return Ctx.Selectors.getSelector(0, &II);
2610 /// \brief Utility function for constructing an unary selector.
2611 static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2612 IdentifierInfo* II = &Ctx.Idents.get(name);
2613 return Ctx.Selectors.getSelector(1, &II);
2616 } // end namespace clang
2618 // operator new and delete aren't allowed inside namespaces.
2620 /// @brief Placement new for using the ASTContext's allocator.
2622 /// This placement form of operator new uses the ASTContext's allocator for
2623 /// obtaining memory.
2625 /// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2626 /// here need to also be made there.
2628 /// We intentionally avoid using a nothrow specification here so that the calls
2629 /// to this operator will not perform a null check on the result -- the
2630 /// underlying allocator never returns null pointers.
2632 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2634 /// // Default alignment (8)
2635 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2636 /// // Specific alignment
2637 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2639 /// Memory allocated through this placement new operator does not need to be
2640 /// explicitly freed, as ASTContext will free all of this memory when it gets
2641 /// destroyed. Please note that you cannot use delete on the pointer.
2643 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2644 /// @param C The ASTContext that provides the allocator.
2645 /// @param Alignment The alignment of the allocated memory (if the underlying
2646 /// allocator supports it).
2647 /// @return The allocated memory. Could be NULL.
2648 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2650 return C.Allocate(Bytes, Alignment);
2652 /// @brief Placement delete companion to the new above.
2654 /// This operator is just a companion to the new above. There is no way of
2655 /// invoking it directly; see the new operator for more details. This operator
2656 /// is called implicitly by the compiler if a placement new expression using
2657 /// the ASTContext throws in the object constructor.
2658 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2662 /// This placement form of operator new[] uses the ASTContext's allocator for
2663 /// obtaining memory.
2665 /// We intentionally avoid using a nothrow specification here so that the calls
2666 /// to this operator will not perform a null check on the result -- the
2667 /// underlying allocator never returns null pointers.
2669 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2671 /// // Default alignment (8)
2672 /// char *data = new (Context) char[10];
2673 /// // Specific alignment
2674 /// char *data = new (Context, 4) char[10];
2676 /// Memory allocated through this placement new[] operator does not need to be
2677 /// explicitly freed, as ASTContext will free all of this memory when it gets
2678 /// destroyed. Please note that you cannot use delete on the pointer.
2680 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2681 /// @param C The ASTContext that provides the allocator.
2682 /// @param Alignment The alignment of the allocated memory (if the underlying
2683 /// allocator supports it).
2684 /// @return The allocated memory. Could be NULL.
2685 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2686 size_t Alignment = 8) {
2687 return C.Allocate(Bytes, Alignment);
2690 /// @brief Placement delete[] companion to the new[] above.
2692 /// This operator is just a companion to the new[] above. There is no way of
2693 /// invoking it directly; see the new[] operator for more details. This operator
2694 /// is called implicitly by the compiler if a placement new[] expression using
2695 /// the ASTContext throws in the object constructor.
2696 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2700 /// \brief Create the representation of a LazyGenerationalUpdatePtr.
2701 template <typename Owner, typename T,
2702 void (clang::ExternalASTSource::*Update)(Owner)>
2703 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
2704 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
2705 const clang::ASTContext &Ctx, T Value) {
2706 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
2707 // include ASTContext.h. We explicitly instantiate it for all relevant types
2708 // in ASTContext.cpp.
2709 if (auto *Source = Ctx.getExternalSource())
2710 return new (Ctx) LazyData(Source, Value);