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 /// 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/ComparisonCategories.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/ExternalASTSource.h"
26 #include "clang/AST/NestedNameSpecifier.h"
27 #include "clang/AST/PrettyPrinter.h"
28 #include "clang/AST/RawCommentList.h"
29 #include "clang/AST/TemplateBase.h"
30 #include "clang/AST/TemplateName.h"
31 #include "clang/AST/Type.h"
32 #include "clang/Basic/AddressSpaces.h"
33 #include "clang/Basic/IdentifierTable.h"
34 #include "clang/Basic/LLVM.h"
35 #include "clang/Basic/LangOptions.h"
36 #include "clang/Basic/Linkage.h"
37 #include "clang/Basic/OperatorKinds.h"
38 #include "clang/Basic/PartialDiagnostic.h"
39 #include "clang/Basic/SanitizerBlacklist.h"
40 #include "clang/Basic/SourceLocation.h"
41 #include "clang/Basic/Specifiers.h"
42 #include "clang/Basic/TargetInfo.h"
43 #include "clang/Basic/XRayLists.h"
44 #include "llvm/ADT/APSInt.h"
45 #include "llvm/ADT/ArrayRef.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/FoldingSet.h"
48 #include "llvm/ADT/IntrusiveRefCntPtr.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/None.h"
51 #include "llvm/ADT/Optional.h"
52 #include "llvm/ADT/PointerIntPair.h"
53 #include "llvm/ADT/PointerUnion.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/StringMap.h"
56 #include "llvm/ADT/StringRef.h"
57 #include "llvm/ADT/TinyPtrVector.h"
58 #include "llvm/ADT/Triple.h"
59 #include "llvm/ADT/iterator_range.h"
60 #include "llvm/Support/AlignOf.h"
61 #include "llvm/Support/Allocator.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/Compiler.h"
70 #include <type_traits>
83 class ASTMutationListener;
84 class ASTRecordLayout;
87 class BuiltinTemplateDecl;
90 class CXXConstructorDecl;
93 class DiagnosticsEngine;
96 class MangleNumberingContext;
97 class MaterializeTemporaryExpr;
98 class MemberSpecializationInfo;
100 class ObjCCategoryDecl;
101 class ObjCCategoryImplDecl;
102 class ObjCContainerDecl;
104 class ObjCImplementationDecl;
105 class ObjCInterfaceDecl;
107 class ObjCMethodDecl;
108 class ObjCPropertyDecl;
109 class ObjCPropertyImplDecl;
110 class ObjCProtocolDecl;
111 class ObjCTypeParamDecl;
114 class StoredDeclsMap;
116 class TemplateParameterList;
117 class TemplateTemplateParmDecl;
118 class TemplateTypeParmDecl;
119 class UnresolvedSetIterator;
120 class UsingShadowDecl;
121 class VarTemplateDecl;
122 class VTableContextBase;
128 } // namespace Builtin
130 enum BuiltinTemplateKind : int;
136 } // namespace comments
141 bool AlignIsRequired : 1;
143 TypeInfo() : AlignIsRequired(false) {}
144 TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
145 : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
148 /// Holds long-lived AST nodes (such as types and decls) that can be
149 /// referred to throughout the semantic analysis of a file.
150 class ASTContext : public RefCountedBase<ASTContext> {
151 friend class NestedNameSpecifier;
153 mutable SmallVector<Type *, 0> Types;
154 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
155 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
156 mutable llvm::FoldingSet<PointerType> PointerTypes;
157 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
158 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
159 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
160 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
161 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
162 mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
163 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
164 mutable std::vector<VariableArrayType*> VariableArrayTypes;
165 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
166 mutable llvm::FoldingSet<DependentSizedExtVectorType>
167 DependentSizedExtVectorTypes;
168 mutable llvm::FoldingSet<DependentAddressSpaceType>
169 DependentAddressSpaceTypes;
170 mutable llvm::FoldingSet<VectorType> VectorTypes;
171 mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes;
172 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
173 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
175 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
176 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
177 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
178 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
179 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
180 SubstTemplateTypeParmTypes;
181 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
182 SubstTemplateTypeParmPackTypes;
183 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
184 TemplateSpecializationTypes;
185 mutable llvm::FoldingSet<ParenType> ParenTypes;
186 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
187 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
188 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
190 DependentTemplateSpecializationTypes;
191 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
192 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
193 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
194 mutable llvm::FoldingSet<DependentUnaryTransformType>
195 DependentUnaryTransformTypes;
196 mutable llvm::FoldingSet<AutoType> AutoTypes;
197 mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
198 DeducedTemplateSpecializationTypes;
199 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
200 llvm::FoldingSet<AttributedType> AttributedTypes;
201 mutable llvm::FoldingSet<PipeType> PipeTypes;
203 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
204 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
205 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
206 SubstTemplateTemplateParms;
207 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
209 SubstTemplateTemplateParmPacks;
211 /// The set of nested name specifiers.
213 /// This set is managed by the NestedNameSpecifier class.
214 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
215 mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
217 /// A cache mapping from RecordDecls to ASTRecordLayouts.
219 /// This is lazily created. This is intentionally not serialized.
220 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
222 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
225 /// A cache from types to size and alignment information.
226 using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
227 mutable TypeInfoMap MemoizedTypeInfo;
229 /// A cache mapping from CXXRecordDecls to key functions.
230 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
232 /// Mapping from ObjCContainers to their ObjCImplementations.
233 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
235 /// Mapping from ObjCMethod to its duplicate declaration in the same
237 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
239 /// Mapping from __block VarDecls to their copy initialization expr.
240 llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
242 /// Mapping from class scope functions specialization to their
243 /// template patterns.
244 llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
245 ClassScopeSpecializationPattern;
247 /// Mapping from materialized temporaries with static storage duration
248 /// that appear in constant initializers to their evaluated values. These are
249 /// allocated in a std::map because their address must be stable.
250 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue *>
251 MaterializedTemporaryValues;
253 /// Representation of a "canonical" template template parameter that
254 /// is used in canonical template names.
255 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
256 TemplateTemplateParmDecl *Parm;
259 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
262 TemplateTemplateParmDecl *getParam() const { return Parm; }
264 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
266 static void Profile(llvm::FoldingSetNodeID &ID,
267 TemplateTemplateParmDecl *Parm);
269 mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
270 CanonTemplateTemplateParms;
272 TemplateTemplateParmDecl *
273 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
275 /// The typedef for the __int128_t type.
276 mutable TypedefDecl *Int128Decl = nullptr;
278 /// The typedef for the __uint128_t type.
279 mutable TypedefDecl *UInt128Decl = nullptr;
281 /// The typedef for the target specific predefined
282 /// __builtin_va_list type.
283 mutable TypedefDecl *BuiltinVaListDecl = nullptr;
285 /// The typedef for the predefined \c __builtin_ms_va_list type.
286 mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
288 /// The typedef for the predefined \c id type.
289 mutable TypedefDecl *ObjCIdDecl = nullptr;
291 /// The typedef for the predefined \c SEL type.
292 mutable TypedefDecl *ObjCSelDecl = nullptr;
294 /// The typedef for the predefined \c Class type.
295 mutable TypedefDecl *ObjCClassDecl = nullptr;
297 /// The typedef for the predefined \c Protocol class in Objective-C.
298 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
300 /// The typedef for the predefined 'BOOL' type.
301 mutable TypedefDecl *BOOLDecl = nullptr;
303 // Typedefs which may be provided defining the structure of Objective-C
305 QualType ObjCIdRedefinitionType;
306 QualType ObjCClassRedefinitionType;
307 QualType ObjCSelRedefinitionType;
309 /// The identifier 'bool'.
310 mutable IdentifierInfo *BoolName = nullptr;
312 /// The identifier 'NSObject'.
313 IdentifierInfo *NSObjectName = nullptr;
315 /// The identifier 'NSCopying'.
316 IdentifierInfo *NSCopyingName = nullptr;
318 /// The identifier '__make_integer_seq'.
319 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
321 /// The identifier '__type_pack_element'.
322 mutable IdentifierInfo *TypePackElementName = nullptr;
324 QualType ObjCConstantStringType;
325 mutable RecordDecl *CFConstantStringTagDecl = nullptr;
326 mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
328 mutable QualType ObjCSuperType;
330 QualType ObjCNSStringType;
332 /// The typedef declaration for the Objective-C "instancetype" type.
333 TypedefDecl *ObjCInstanceTypeDecl = nullptr;
335 /// The type for the C FILE type.
336 TypeDecl *FILEDecl = nullptr;
338 /// The type for the C jmp_buf type.
339 TypeDecl *jmp_bufDecl = nullptr;
341 /// The type for the C sigjmp_buf type.
342 TypeDecl *sigjmp_bufDecl = nullptr;
344 /// The type for the C ucontext_t type.
345 TypeDecl *ucontext_tDecl = nullptr;
347 /// Type for the Block descriptor for Blocks CodeGen.
349 /// Since this is only used for generation of debug info, it is not
351 mutable RecordDecl *BlockDescriptorType = nullptr;
353 /// Type for the Block descriptor for Blocks CodeGen.
355 /// Since this is only used for generation of debug info, it is not
357 mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
359 /// Declaration for the CUDA cudaConfigureCall function.
360 FunctionDecl *cudaConfigureCallDecl = nullptr;
362 /// Keeps track of all declaration attributes.
364 /// Since so few decls have attrs, we keep them in a hash map instead of
365 /// wasting space in the Decl class.
366 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
368 /// A mapping from non-redeclarable declarations in modules that were
369 /// merged with other declarations to the canonical declaration that they were
371 llvm::DenseMap<Decl*, Decl*> MergedDecls;
373 /// A mapping from a defining declaration to a list of modules (other
374 /// than the owning module of the declaration) that contain merged
375 /// definitions of that entity.
376 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
378 /// Initializers for a module, in order. Each Decl will be either
379 /// something that has a semantic effect on startup (such as a variable with
380 /// a non-constant initializer), or an ImportDecl (which recursively triggers
381 /// initialization of another module).
382 struct PerModuleInitializers {
383 llvm::SmallVector<Decl*, 4> Initializers;
384 llvm::SmallVector<uint32_t, 4> LazyInitializers;
386 void resolve(ASTContext &Ctx);
388 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
390 ASTContext &this_() { return *this; }
393 /// A type synonym for the TemplateOrInstantiation mapping.
394 using TemplateOrSpecializationInfo =
395 llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
398 friend class ASTDeclReader;
399 friend class ASTReader;
400 friend class ASTWriter;
401 friend class CXXRecordDecl;
403 /// A mapping to contain the template or declaration that
404 /// a variable declaration describes or was instantiated from,
407 /// For non-templates, this value will be NULL. For variable
408 /// declarations that describe a variable template, this will be a
409 /// pointer to a VarTemplateDecl. For static data members
410 /// of class template specializations, this will be the
411 /// MemberSpecializationInfo referring to the member variable that was
412 /// instantiated or specialized. Thus, the mapping will keep track of
413 /// the static data member templates from which static data members of
414 /// class template specializations were instantiated.
416 /// Given the following example:
419 /// template<typename T>
424 /// template<typename T>
425 /// T X<T>::value = T(17);
427 /// int *x = &X<int>::value;
430 /// This mapping will contain an entry that maps from the VarDecl for
431 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
432 /// class template X) and will be marked TSK_ImplicitInstantiation.
433 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
434 TemplateOrInstantiation;
436 /// Keeps track of the declaration from which a using declaration was
437 /// created during instantiation.
439 /// The source and target declarations are always a UsingDecl, an
440 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
444 /// template<typename T>
449 /// template<typename T>
450 /// struct B : A<T> {
454 /// template struct B<int>;
457 /// This mapping will contain an entry that maps from the UsingDecl in
458 /// B<int> to the UnresolvedUsingDecl in B<T>.
459 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
461 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
462 InstantiatedFromUsingShadowDecl;
464 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
466 /// Mapping that stores the methods overridden by a given C++
469 /// Since most C++ member functions aren't virtual and therefore
470 /// don't override anything, we store the overridden functions in
471 /// this map on the side rather than within the CXXMethodDecl structure.
472 using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
473 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
475 /// Mapping from each declaration context to its corresponding
476 /// mangling numbering context (used for constructs like lambdas which
477 /// need to be consistently numbered for the mangler).
478 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
479 MangleNumberingContexts;
481 /// Side-table of mangling numbers for declarations which rarely
482 /// need them (like static local vars).
483 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
484 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
486 /// Mapping that stores parameterIndex values for ParmVarDecls when
487 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
488 using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
489 ParameterIndexTable ParamIndices;
491 ImportDecl *FirstLocalImport = nullptr;
492 ImportDecl *LastLocalImport = nullptr;
494 TranslationUnitDecl *TUDecl;
495 mutable ExternCContextDecl *ExternCContext = nullptr;
496 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
497 mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
499 /// The associated SourceManager object.
500 SourceManager &SourceMgr;
502 /// The language options used to create the AST associated with
503 /// this ASTContext object.
504 LangOptions &LangOpts;
506 /// Blacklist object that is used by sanitizers to decide which
507 /// entities should not be instrumented.
508 std::unique_ptr<SanitizerBlacklist> SanitizerBL;
510 /// Function filtering mechanism to determine whether a given function
511 /// should be imbued with the XRay "always" or "never" attributes.
512 std::unique_ptr<XRayFunctionFilter> XRayFilter;
514 /// The allocator used to create AST objects.
516 /// AST objects are never destructed; rather, all memory associated with the
517 /// AST objects will be released when the ASTContext itself is destroyed.
518 mutable llvm::BumpPtrAllocator BumpAlloc;
520 /// Allocator for partial diagnostics.
521 PartialDiagnostic::StorageAllocator DiagAllocator;
523 /// The current C++ ABI.
524 std::unique_ptr<CXXABI> ABI;
525 CXXABI *createCXXABI(const TargetInfo &T);
527 /// The logical -> physical address space map.
528 const LangASMap *AddrSpaceMap = nullptr;
530 /// Address space map mangling must be used with language specific
531 /// address spaces (e.g. OpenCL/CUDA)
532 bool AddrSpaceMapMangling;
534 const TargetInfo *Target = nullptr;
535 const TargetInfo *AuxTarget = nullptr;
536 clang::PrintingPolicy PrintingPolicy;
539 IdentifierTable &Idents;
540 SelectorTable &Selectors;
541 Builtin::Context &BuiltinInfo;
542 mutable DeclarationNameTable DeclarationNames;
543 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
544 ASTMutationListener *Listener = nullptr;
546 /// Contains parents of a node.
547 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
549 /// Maps from a node to its parents. This is used for nodes that have
550 /// pointer identity only, which are more common and we can save space by
551 /// only storing a unique pointer to them.
552 using ParentMapPointers =
553 llvm::DenseMap<const void *,
554 llvm::PointerUnion4<const Decl *, const Stmt *,
555 ast_type_traits::DynTypedNode *,
558 /// Parent map for nodes without pointer identity. We store a full
559 /// DynTypedNode for all keys.
560 using ParentMapOtherNodes =
561 llvm::DenseMap<ast_type_traits::DynTypedNode,
562 llvm::PointerUnion4<const Decl *, const Stmt *,
563 ast_type_traits::DynTypedNode *,
566 /// Container for either a single DynTypedNode or for an ArrayRef to
567 /// DynTypedNode. For use with ParentMap.
568 class DynTypedNodeList {
569 using DynTypedNode = ast_type_traits::DynTypedNode;
571 llvm::AlignedCharArrayUnion<ast_type_traits::DynTypedNode,
572 ArrayRef<DynTypedNode>> Storage;
576 DynTypedNodeList(const DynTypedNode &N) : IsSingleNode(true) {
577 new (Storage.buffer) DynTypedNode(N);
580 DynTypedNodeList(ArrayRef<DynTypedNode> A) : IsSingleNode(false) {
581 new (Storage.buffer) ArrayRef<DynTypedNode>(A);
584 const ast_type_traits::DynTypedNode *begin() const {
586 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
588 return reinterpret_cast<const DynTypedNode *>(Storage.buffer);
591 const ast_type_traits::DynTypedNode *end() const {
593 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
595 return reinterpret_cast<const DynTypedNode *>(Storage.buffer) + 1;
598 size_t size() const { return end() - begin(); }
599 bool empty() const { return begin() == end(); }
601 const DynTypedNode &operator[](size_t N) const {
602 assert(N < size() && "Out of bounds!");
603 return *(begin() + N);
607 /// Returns the parents of the given node.
609 /// Note that this will lazily compute the parents of all nodes
610 /// and store them for later retrieval. Thus, the first call is O(n)
611 /// in the number of AST nodes.
613 /// Caveats and FIXMEs:
614 /// Calculating the parent map over all AST nodes will need to load the
615 /// full AST. This can be undesirable in the case where the full AST is
616 /// expensive to create (for example, when using precompiled header
617 /// preambles). Thus, there are good opportunities for optimization here.
618 /// One idea is to walk the given node downwards, looking for references
619 /// to declaration contexts - once a declaration context is found, compute
620 /// the parent map for the declaration context; if that can satisfy the
621 /// request, loading the whole AST can be avoided. Note that this is made
622 /// more complex by statements in templates having multiple parents - those
623 /// problems can be solved by building closure over the templated parts of
624 /// the AST, which also avoids touching large parts of the AST.
625 /// Additionally, we will want to add an interface to already give a hint
626 /// where to search for the parents, for example when looking at a statement
627 /// inside a certain function.
629 /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
630 /// NestedNameSpecifier or NestedNameSpecifierLoc.
631 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node) {
632 return getParents(ast_type_traits::DynTypedNode::create(Node));
635 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node);
637 const clang::PrintingPolicy &getPrintingPolicy() const {
638 return PrintingPolicy;
641 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
642 PrintingPolicy = Policy;
645 SourceManager& getSourceManager() { return SourceMgr; }
646 const SourceManager& getSourceManager() const { return SourceMgr; }
648 llvm::BumpPtrAllocator &getAllocator() const {
652 void *Allocate(size_t Size, unsigned Align = 8) const {
653 return BumpAlloc.Allocate(Size, Align);
655 template <typename T> T *Allocate(size_t Num = 1) const {
656 return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
658 void Deallocate(void *Ptr) const {}
660 /// Return the total amount of physical memory allocated for representing
661 /// AST nodes and type information.
662 size_t getASTAllocatedMemory() const {
663 return BumpAlloc.getTotalMemory();
666 /// Return the total memory used for various side tables.
667 size_t getSideTableAllocatedMemory() const;
669 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
670 return DiagAllocator;
673 const TargetInfo &getTargetInfo() const { return *Target; }
674 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
676 /// getIntTypeForBitwidth -
677 /// sets integer QualTy according to specified details:
678 /// bitwidth, signed/unsigned.
679 /// Returns empty type if there is no appropriate target types.
680 QualType getIntTypeForBitwidth(unsigned DestWidth,
681 unsigned Signed) const;
683 /// getRealTypeForBitwidth -
684 /// sets floating point QualTy according to specified bitwidth.
685 /// Returns empty type if there is no appropriate target types.
686 QualType getRealTypeForBitwidth(unsigned DestWidth) const;
688 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
690 const LangOptions& getLangOpts() const { return LangOpts; }
692 const SanitizerBlacklist &getSanitizerBlacklist() const {
696 const XRayFunctionFilter &getXRayFilter() const {
700 DiagnosticsEngine &getDiagnostics() const;
702 FullSourceLoc getFullLoc(SourceLocation Loc) const {
703 return FullSourceLoc(Loc,SourceMgr);
706 /// All comments in this translation unit.
707 RawCommentList Comments;
709 /// True if comments are already loaded from ExternalASTSource.
710 mutable bool CommentsLoaded = false;
712 class RawCommentAndCacheFlags {
715 /// We searched for a comment attached to the particular declaration, but
721 /// We have found a comment attached to this particular declaration.
726 /// This declaration does not have an attached comment, and we have
727 /// searched the redeclaration chain.
729 /// If getRaw() == 0, the whole redeclaration chain does not have any
732 /// If getRaw() != 0, it is a comment propagated from other
737 Kind getKind() const LLVM_READONLY {
738 return Data.getInt();
741 void setKind(Kind K) {
745 const RawComment *getRaw() const LLVM_READONLY {
746 return Data.getPointer();
749 void setRaw(const RawComment *RC) {
753 const Decl *getOriginalDecl() const LLVM_READONLY {
757 void setOriginalDecl(const Decl *Orig) {
762 llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
763 const Decl *OriginalDecl;
766 /// Mapping from declarations to comments attached to any
769 /// Raw comments are owned by Comments list. This mapping is populated
771 mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
773 /// Mapping from declarations to parsed comments attached to any
775 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
777 /// Return the documentation comment attached to a given declaration,
778 /// without looking into cache.
779 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
782 RawCommentList &getRawCommentList() {
786 void addComment(const RawComment &RC) {
787 assert(LangOpts.RetainCommentsFromSystemHeaders ||
788 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
789 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
792 /// Return the documentation comment attached to a given declaration.
793 /// Returns nullptr if no comment is attached.
795 /// \param OriginalDecl if not nullptr, is set to declaration AST node that
796 /// had the comment, if the comment we found comes from a redeclaration.
798 getRawCommentForAnyRedecl(const Decl *D,
799 const Decl **OriginalDecl = nullptr) const;
801 /// Return parsed documentation comment attached to a given declaration.
802 /// Returns nullptr if no comment is attached.
804 /// \param PP the Preprocessor used with this TU. Could be nullptr if
805 /// preprocessor is not available.
806 comments::FullComment *getCommentForDecl(const Decl *D,
807 const Preprocessor *PP) const;
809 /// Return parsed documentation comment attached to a given declaration.
810 /// Returns nullptr if no comment is attached. Does not look at any
811 /// redeclarations of the declaration.
812 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
814 comments::FullComment *cloneFullComment(comments::FullComment *FC,
815 const Decl *D) const;
818 mutable comments::CommandTraits CommentCommandTraits;
820 /// Iterator that visits import declarations.
821 class import_iterator {
822 ImportDecl *Import = nullptr;
825 using value_type = ImportDecl *;
826 using reference = ImportDecl *;
827 using pointer = ImportDecl *;
828 using difference_type = int;
829 using iterator_category = std::forward_iterator_tag;
831 import_iterator() = default;
832 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
834 reference operator*() const { return Import; }
835 pointer operator->() const { return Import; }
837 import_iterator &operator++() {
838 Import = ASTContext::getNextLocalImport(Import);
842 import_iterator operator++(int) {
843 import_iterator Other(*this);
848 friend bool operator==(import_iterator X, import_iterator Y) {
849 return X.Import == Y.Import;
852 friend bool operator!=(import_iterator X, import_iterator Y) {
853 return X.Import != Y.Import;
858 comments::CommandTraits &getCommentCommandTraits() const {
859 return CommentCommandTraits;
862 /// Retrieve the attributes for the given declaration.
863 AttrVec& getDeclAttrs(const Decl *D);
865 /// Erase the attributes corresponding to the given declaration.
866 void eraseDeclAttrs(const Decl *D);
868 /// If this variable is an instantiated static data member of a
869 /// class template specialization, returns the templated static data member
870 /// from which it was instantiated.
872 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
875 TemplateOrSpecializationInfo
876 getTemplateOrSpecializationInfo(const VarDecl *Var);
878 FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
880 void setClassScopeSpecializationPattern(FunctionDecl *FD,
881 FunctionDecl *Pattern);
883 /// Note that the static data member \p Inst is an instantiation of
884 /// the static data member template \p Tmpl of a class template.
885 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
886 TemplateSpecializationKind TSK,
887 SourceLocation PointOfInstantiation = SourceLocation());
889 void setTemplateOrSpecializationInfo(VarDecl *Inst,
890 TemplateOrSpecializationInfo TSI);
892 /// If the given using decl \p Inst is an instantiation of a
893 /// (possibly unresolved) using decl from a template instantiation,
895 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
897 /// Remember that the using decl \p Inst is an instantiation
898 /// of the using decl \p Pattern of a class template.
899 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
901 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
902 UsingShadowDecl *Pattern);
903 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
905 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
907 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
909 // Access to the set of methods overridden by the given C++ method.
910 using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
911 overridden_cxx_method_iterator
912 overridden_methods_begin(const CXXMethodDecl *Method) const;
914 overridden_cxx_method_iterator
915 overridden_methods_end(const CXXMethodDecl *Method) const;
917 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
919 using overridden_method_range =
920 llvm::iterator_range<overridden_cxx_method_iterator>;
922 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
924 /// Note that the given C++ \p Method overrides the given \p
925 /// Overridden method.
926 void addOverriddenMethod(const CXXMethodDecl *Method,
927 const CXXMethodDecl *Overridden);
929 /// Return C++ or ObjC overridden methods for the given \p Method.
931 /// An ObjC method is considered to override any method in the class's
932 /// base classes, its protocols, or its categories' protocols, that has
933 /// the same selector and is of the same kind (class or instance).
934 /// A method in an implementation is not considered as overriding the same
935 /// method in the interface or its categories.
936 void getOverriddenMethods(
937 const NamedDecl *Method,
938 SmallVectorImpl<const NamedDecl *> &Overridden) const;
940 /// Notify the AST context that a new import declaration has been
941 /// parsed or implicitly created within this translation unit.
942 void addedLocalImportDecl(ImportDecl *Import);
944 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
945 return Import->NextLocalImport;
948 using import_range = llvm::iterator_range<import_iterator>;
950 import_range local_imports() const {
951 return import_range(import_iterator(FirstLocalImport), import_iterator());
954 Decl *getPrimaryMergedDecl(Decl *D) {
955 Decl *Result = MergedDecls.lookup(D);
956 return Result ? Result : D;
958 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
959 MergedDecls[D] = Primary;
962 /// Note that the definition \p ND has been merged into module \p M,
963 /// and should be visible whenever \p M is visible.
964 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
965 bool NotifyListeners = true);
967 /// Clean up the merged definition list. Call this if you might have
968 /// added duplicates into the list.
969 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
971 /// Get the additional modules in which the definition \p Def has
973 ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def) {
974 auto MergedIt = MergedDefModules.find(Def);
975 if (MergedIt == MergedDefModules.end())
977 return MergedIt->second;
980 /// Add a declaration to the list of declarations that are initialized
981 /// for a module. This will typically be a global variable (with internal
982 /// linkage) that runs module initializers, such as the iostream initializer,
983 /// or an ImportDecl nominating another module that has initializers.
984 void addModuleInitializer(Module *M, Decl *Init);
986 void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs);
988 /// Get the initializations to perform when importing a module, if any.
989 ArrayRef<Decl*> getModuleInitializers(Module *M);
991 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
993 ExternCContextDecl *getExternCContextDecl() const;
994 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
995 BuiltinTemplateDecl *getTypePackElementDecl() const;
1001 CanQualType WCharTy; // [C++ 3.9.1p5].
1002 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
1003 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
1004 CanQualType Char8Ty; // [C++20 proposal]
1005 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
1006 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
1007 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
1008 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
1009 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
1010 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty;
1011 CanQualType ShortAccumTy, AccumTy,
1012 LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1013 CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
1014 CanQualType ShortFractTy, FractTy, LongFractTy;
1015 CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
1016 CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy;
1017 CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy,
1018 SatUnsignedLongAccumTy;
1019 CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
1020 CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
1021 SatUnsignedLongFractTy;
1022 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
1023 CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
1024 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
1025 CanQualType Float128ComplexTy;
1026 CanQualType VoidPtrTy, NullPtrTy;
1027 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
1028 CanQualType BuiltinFnTy;
1029 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
1030 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
1031 CanQualType ObjCBuiltinBoolTy;
1032 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1033 CanQualType SingletonId;
1034 #include "clang/Basic/OpenCLImageTypes.def"
1035 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
1036 CanQualType OCLQueueTy, OCLReserveIDTy;
1037 CanQualType OMPArraySectionTy;
1039 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
1040 mutable QualType AutoDeductTy; // Deduction against 'auto'.
1041 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
1043 // Decl used to help define __builtin_va_list for some targets.
1044 // The decl is built when constructing 'BuiltinVaListDecl'.
1045 mutable Decl *VaListTagDecl;
1047 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1048 SelectorTable &sels, Builtin::Context &builtins);
1049 ASTContext(const ASTContext &) = delete;
1050 ASTContext &operator=(const ASTContext &) = delete;
1053 /// Attach an external AST source to the AST context.
1055 /// The external AST source provides the ability to load parts of
1056 /// the abstract syntax tree as needed from some external storage,
1057 /// e.g., a precompiled header.
1058 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1060 /// Retrieve a pointer to the external AST source associated
1061 /// with this AST context, if any.
1062 ExternalASTSource *getExternalSource() const {
1063 return ExternalSource.get();
1066 /// Attach an AST mutation listener to the AST context.
1068 /// The AST mutation listener provides the ability to track modifications to
1069 /// the abstract syntax tree entities committed after they were initially
1071 void setASTMutationListener(ASTMutationListener *Listener) {
1072 this->Listener = Listener;
1075 /// Retrieve a pointer to the AST mutation listener associated
1076 /// with this AST context, if any.
1077 ASTMutationListener *getASTMutationListener() const { return Listener; }
1079 void PrintStats() const;
1080 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1082 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1083 const IdentifierInfo *II) const;
1085 /// Create a new implicit TU-level CXXRecordDecl or RecordDecl
1087 RecordDecl *buildImplicitRecord(StringRef Name,
1088 RecordDecl::TagKind TK = TTK_Struct) const;
1090 /// Create a new implicit TU-level typedef declaration.
1091 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1093 /// Retrieve the declaration for the 128-bit signed integer type.
1094 TypedefDecl *getInt128Decl() const;
1096 /// Retrieve the declaration for the 128-bit unsigned integer type.
1097 TypedefDecl *getUInt128Decl() const;
1099 //===--------------------------------------------------------------------===//
1100 // Type Constructors
1101 //===--------------------------------------------------------------------===//
1104 /// Return a type with extended qualifiers.
1105 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1107 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1109 QualType getPipeType(QualType T, bool ReadOnly) const;
1112 /// Return the uniqued reference to the type for an address space
1113 /// qualified type with the specified type and address space.
1115 /// The resulting type has a union of the qualifiers from T and the address
1116 /// space. If T already has an address space specifier, it is silently
1118 QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
1120 /// Remove any existing address space on the type and returns the type
1121 /// with qualifiers intact (or that's the idea anyway)
1123 /// The return type should be T with all prior qualifiers minus the address
1125 QualType removeAddrSpaceQualType(QualType T) const;
1127 /// Apply Objective-C protocol qualifiers to the given type.
1128 /// \param allowOnPointerType specifies if we can apply protocol
1129 /// qualifiers on ObjCObjectPointerType. It can be set to true when
1130 /// constructing the canonical type of a Objective-C type parameter.
1131 QualType applyObjCProtocolQualifiers(QualType type,
1132 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1133 bool allowOnPointerType = false) const;
1135 /// Return the uniqued reference to the type for an Objective-C
1136 /// gc-qualified type.
1138 /// The resulting type has a union of the qualifiers from T and the gc
1140 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1142 /// Return the uniqued reference to the type for a \c restrict
1145 /// The resulting type has a union of the qualifiers from \p T and
1147 QualType getRestrictType(QualType T) const {
1148 return T.withFastQualifiers(Qualifiers::Restrict);
1151 /// Return the uniqued reference to the type for a \c volatile
1154 /// The resulting type has a union of the qualifiers from \p T and
1156 QualType getVolatileType(QualType T) const {
1157 return T.withFastQualifiers(Qualifiers::Volatile);
1160 /// Return the uniqued reference to the type for a \c const
1163 /// The resulting type has a union of the qualifiers from \p T and \c const.
1165 /// It can be reasonably expected that this will always be equivalent to
1166 /// calling T.withConst().
1167 QualType getConstType(QualType T) const { return T.withConst(); }
1169 /// Change the ExtInfo on a function type.
1170 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1171 FunctionType::ExtInfo EInfo);
1173 /// Adjust the given function result type.
1174 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1176 /// Change the result type of a function type once it is deduced.
1177 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1179 /// Get a function type and produce the equivalent function type with the
1180 /// specified exception specification. Type sugar that can be present on a
1181 /// declaration of a function with an exception specification is permitted
1182 /// and preserved. Other type sugar (for instance, typedefs) is not.
1183 QualType getFunctionTypeWithExceptionSpec(
1184 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI);
1186 /// Determine whether two function types are the same, ignoring
1187 /// exception specifications in cases where they're part of the type.
1188 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U);
1190 /// Change the exception specification on a function once it is
1191 /// delay-parsed, instantiated, or computed.
1192 void adjustExceptionSpec(FunctionDecl *FD,
1193 const FunctionProtoType::ExceptionSpecInfo &ESI,
1194 bool AsWritten = false);
1196 /// Return the uniqued reference to the type for a complex
1197 /// number with the specified element type.
1198 QualType getComplexType(QualType T) const;
1199 CanQualType getComplexType(CanQualType T) const {
1200 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1203 /// Return the uniqued reference to the type for a pointer to
1204 /// the specified type.
1205 QualType getPointerType(QualType T) const;
1206 CanQualType getPointerType(CanQualType T) const {
1207 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1210 /// Return the uniqued reference to a type adjusted from the original
1211 /// type to a new type.
1212 QualType getAdjustedType(QualType Orig, QualType New) const;
1213 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1214 return CanQualType::CreateUnsafe(
1215 getAdjustedType((QualType)Orig, (QualType)New));
1218 /// Return the uniqued reference to the decayed version of the given
1219 /// type. Can only be called on array and function types which decay to
1221 QualType getDecayedType(QualType T) const;
1222 CanQualType getDecayedType(CanQualType T) const {
1223 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1226 /// Return the uniqued reference to the atomic type for the specified
1228 QualType getAtomicType(QualType T) const;
1230 /// Return the uniqued reference to the type for a block of the
1232 QualType getBlockPointerType(QualType T) const;
1234 /// Gets the struct used to keep track of the descriptor for pointer to
1236 QualType getBlockDescriptorType() const;
1238 /// Return a read_only pipe type for the specified type.
1239 QualType getReadPipeType(QualType T) const;
1241 /// Return a write_only pipe type for the specified type.
1242 QualType getWritePipeType(QualType T) const;
1244 /// Gets the struct used to keep track of the extended descriptor for
1245 /// pointer to blocks.
1246 QualType getBlockDescriptorExtendedType() const;
1248 /// Map an AST Type to an OpenCLTypeKind enum value.
1249 TargetInfo::OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
1251 /// Get address space for OpenCL type.
1252 LangAS getOpenCLTypeAddrSpace(const Type *T) const;
1254 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1255 cudaConfigureCallDecl = FD;
1258 FunctionDecl *getcudaConfigureCallDecl() {
1259 return cudaConfigureCallDecl;
1262 /// Returns true iff we need copy/dispose helpers for the given type.
1263 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1265 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
1266 /// is set to false in this case. If HasByrefExtendedLayout returns true,
1267 /// byref variable has extended lifetime.
1268 bool getByrefLifetime(QualType Ty,
1269 Qualifiers::ObjCLifetime &Lifetime,
1270 bool &HasByrefExtendedLayout) const;
1272 /// Return the uniqued reference to the type for an lvalue reference
1273 /// to the specified type.
1274 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1277 /// Return the uniqued reference to the type for an rvalue reference
1278 /// to the specified type.
1279 QualType getRValueReferenceType(QualType T) const;
1281 /// Return the uniqued reference to the type for a member pointer to
1282 /// the specified type in the specified class.
1284 /// The class \p Cls is a \c Type because it could be a dependent name.
1285 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1287 /// Return a non-unique reference to the type for a variable array of
1288 /// the specified element type.
1289 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1290 ArrayType::ArraySizeModifier ASM,
1291 unsigned IndexTypeQuals,
1292 SourceRange Brackets) const;
1294 /// Return a non-unique reference to the type for a dependently-sized
1295 /// array of the specified element type.
1297 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1299 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1300 ArrayType::ArraySizeModifier ASM,
1301 unsigned IndexTypeQuals,
1302 SourceRange Brackets) const;
1304 /// Return a unique reference to the type for an incomplete array of
1305 /// the specified element type.
1306 QualType getIncompleteArrayType(QualType EltTy,
1307 ArrayType::ArraySizeModifier ASM,
1308 unsigned IndexTypeQuals) const;
1310 /// Return the unique reference to the type for a constant array of
1311 /// the specified element type.
1312 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1313 ArrayType::ArraySizeModifier ASM,
1314 unsigned IndexTypeQuals) const;
1316 /// Returns a vla type where known sizes are replaced with [*].
1317 QualType getVariableArrayDecayedType(QualType Ty) const;
1319 /// Return the unique reference to a vector type of the specified
1320 /// element type and size.
1322 /// \pre \p VectorType must be a built-in type.
1323 QualType getVectorType(QualType VectorType, unsigned NumElts,
1324 VectorType::VectorKind VecKind) const;
1325 /// Return the unique reference to the type for a dependently sized vector of
1326 /// the specified element type.
1327 QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr,
1328 SourceLocation AttrLoc,
1329 VectorType::VectorKind VecKind) const;
1331 /// Return the unique reference to an extended vector type
1332 /// of the specified element type and size.
1334 /// \pre \p VectorType must be a built-in type.
1335 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1337 /// \pre Return a non-unique reference to the type for a dependently-sized
1338 /// vector of the specified element type.
1340 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1342 QualType getDependentSizedExtVectorType(QualType VectorType,
1344 SourceLocation AttrLoc) const;
1346 QualType getDependentAddressSpaceType(QualType PointeeType,
1347 Expr *AddrSpaceExpr,
1348 SourceLocation AttrLoc) const;
1350 /// Return a K&R style C function type like 'int()'.
1351 QualType getFunctionNoProtoType(QualType ResultTy,
1352 const FunctionType::ExtInfo &Info) const;
1354 QualType getFunctionNoProtoType(QualType ResultTy) const {
1355 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1358 /// Return a normal function type with a typed argument list.
1359 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1360 const FunctionProtoType::ExtProtoInfo &EPI) const {
1361 return getFunctionTypeInternal(ResultTy, Args, EPI, false);
1364 QualType adjustStringLiteralBaseType(QualType StrLTy) const;
1367 /// Return a normal function type with a typed argument list.
1368 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1369 const FunctionProtoType::ExtProtoInfo &EPI,
1370 bool OnlyWantCanonical) const;
1373 /// Return the unique reference to the type for the specified type
1375 QualType getTypeDeclType(const TypeDecl *Decl,
1376 const TypeDecl *PrevDecl = nullptr) const {
1377 assert(Decl && "Passed null for Decl param");
1378 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1381 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1382 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1383 return QualType(PrevDecl->TypeForDecl, 0);
1386 return getTypeDeclTypeSlow(Decl);
1389 /// Return the unique reference to the type for the specified
1390 /// typedef-name decl.
1391 QualType getTypedefType(const TypedefNameDecl *Decl,
1392 QualType Canon = QualType()) const;
1394 QualType getRecordType(const RecordDecl *Decl) const;
1396 QualType getEnumType(const EnumDecl *Decl) const;
1398 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1400 QualType getAttributedType(AttributedType::Kind attrKind,
1401 QualType modifiedType,
1402 QualType equivalentType);
1404 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1405 QualType Replacement) const;
1406 QualType getSubstTemplateTypeParmPackType(
1407 const TemplateTypeParmType *Replaced,
1408 const TemplateArgument &ArgPack);
1411 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1413 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1415 QualType getTemplateSpecializationType(TemplateName T,
1416 ArrayRef<TemplateArgument> Args,
1417 QualType Canon = QualType()) const;
1420 getCanonicalTemplateSpecializationType(TemplateName T,
1421 ArrayRef<TemplateArgument> Args) const;
1423 QualType getTemplateSpecializationType(TemplateName T,
1424 const TemplateArgumentListInfo &Args,
1425 QualType Canon = QualType()) const;
1428 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1429 const TemplateArgumentListInfo &Args,
1430 QualType Canon = QualType()) const;
1432 QualType getParenType(QualType NamedType) const;
1434 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1435 NestedNameSpecifier *NNS, QualType NamedType,
1436 TagDecl *OwnedTagDecl = nullptr) const;
1437 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1438 NestedNameSpecifier *NNS,
1439 const IdentifierInfo *Name,
1440 QualType Canon = QualType()) const;
1442 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1443 NestedNameSpecifier *NNS,
1444 const IdentifierInfo *Name,
1445 const TemplateArgumentListInfo &Args) const;
1446 QualType getDependentTemplateSpecializationType(
1447 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1448 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1450 TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
1452 /// Get a template argument list with one argument per template parameter
1453 /// in a template parameter list, such as for the injected class name of
1454 /// a class template.
1455 void getInjectedTemplateArgs(const TemplateParameterList *Params,
1456 SmallVectorImpl<TemplateArgument> &Args);
1458 QualType getPackExpansionType(QualType Pattern,
1459 Optional<unsigned> NumExpansions);
1461 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1462 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1464 /// Legacy interface: cannot provide type arguments or __kindof.
1465 QualType getObjCObjectType(QualType Base,
1466 ObjCProtocolDecl * const *Protocols,
1467 unsigned NumProtocols) const;
1469 QualType getObjCObjectType(QualType Base,
1470 ArrayRef<QualType> typeArgs,
1471 ArrayRef<ObjCProtocolDecl *> protocols,
1472 bool isKindOf) const;
1474 QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1475 ArrayRef<ObjCProtocolDecl *> protocols,
1476 QualType Canonical = QualType()) const;
1478 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1480 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1481 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1483 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1484 ObjCInterfaceDecl *IDecl);
1486 /// Return a ObjCObjectPointerType type for the given ObjCObjectType.
1487 QualType getObjCObjectPointerType(QualType OIT) const;
1490 QualType getTypeOfExprType(Expr *e) const;
1491 QualType getTypeOfType(QualType t) const;
1494 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1496 /// Unary type transforms
1497 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1498 UnaryTransformType::UTTKind UKind) const;
1500 /// C++11 deduced auto type.
1501 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1502 bool IsDependent) const;
1504 /// C++11 deduction pattern for 'auto' type.
1505 QualType getAutoDeductType() const;
1507 /// C++11 deduction pattern for 'auto &&' type.
1508 QualType getAutoRRefDeductType() const;
1510 /// C++17 deduced class template specialization type.
1511 QualType getDeducedTemplateSpecializationType(TemplateName Template,
1512 QualType DeducedType,
1513 bool IsDependent) const;
1515 /// Return the unique reference to the type for the specified TagDecl
1516 /// (struct/union/class/enum) decl.
1517 QualType getTagDeclType(const TagDecl *Decl) const;
1519 /// Return the unique type for "size_t" (C99 7.17), defined in
1522 /// The sizeof operator requires this (C99 6.5.3.4p4).
1523 CanQualType getSizeType() const;
1525 /// Return the unique signed counterpart of
1526 /// the integer type corresponding to size_t.
1527 CanQualType getSignedSizeType() const;
1529 /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1531 CanQualType getIntMaxType() const;
1533 /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1535 CanQualType getUIntMaxType() const;
1537 /// Return the unique wchar_t type available in C++ (and available as
1538 /// __wchar_t as a Microsoft extension).
1539 QualType getWCharType() const { return WCharTy; }
1541 /// Return the type of wide characters. In C++, this returns the
1542 /// unique wchar_t type. In C99, this returns a type compatible with the type
1543 /// defined in <stddef.h> as defined by the target.
1544 QualType getWideCharType() const { return WideCharTy; }
1546 /// Return the type of "signed wchar_t".
1548 /// Used when in C++, as a GCC extension.
1549 QualType getSignedWCharType() const;
1551 /// Return the type of "unsigned wchar_t".
1553 /// Used when in C++, as a GCC extension.
1554 QualType getUnsignedWCharType() const;
1556 /// In C99, this returns a type compatible with the type
1557 /// defined in <stddef.h> as defined by the target.
1558 QualType getWIntType() const { return WIntTy; }
1560 /// Return a type compatible with "intptr_t" (C99 7.18.1.4),
1561 /// as defined by the target.
1562 QualType getIntPtrType() const;
1564 /// Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1565 /// as defined by the target.
1566 QualType getUIntPtrType() const;
1568 /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1569 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1570 QualType getPointerDiffType() const;
1572 /// Return the unique unsigned counterpart of "ptrdiff_t"
1573 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
1574 /// in the definition of %tu format specifier.
1575 QualType getUnsignedPointerDiffType() const;
1577 /// Return the unique type for "pid_t" defined in
1578 /// <sys/types.h>. We need this to compute the correct type for vfork().
1579 QualType getProcessIDType() const;
1581 /// Return the C structure type used to represent constant CFStrings.
1582 QualType getCFConstantStringType() const;
1584 /// Returns the C struct type for objc_super
1585 QualType getObjCSuperType() const;
1586 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1588 /// Get the structure type used to representation CFStrings, or NULL
1589 /// if it hasn't yet been built.
1590 QualType getRawCFConstantStringType() const {
1591 if (CFConstantStringTypeDecl)
1592 return getTypedefType(CFConstantStringTypeDecl);
1595 void setCFConstantStringType(QualType T);
1596 TypedefDecl *getCFConstantStringDecl() const;
1597 RecordDecl *getCFConstantStringTagDecl() const;
1599 // This setter/getter represents the ObjC type for an NSConstantString.
1600 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1601 QualType getObjCConstantStringInterface() const {
1602 return ObjCConstantStringType;
1605 QualType getObjCNSStringType() const {
1606 return ObjCNSStringType;
1609 void setObjCNSStringType(QualType T) {
1610 ObjCNSStringType = T;
1613 /// Retrieve the type that \c id has been defined to, which may be
1614 /// different from the built-in \c id if \c id has been typedef'd.
1615 QualType getObjCIdRedefinitionType() const {
1616 if (ObjCIdRedefinitionType.isNull())
1617 return getObjCIdType();
1618 return ObjCIdRedefinitionType;
1621 /// Set the user-written type that redefines \c id.
1622 void setObjCIdRedefinitionType(QualType RedefType) {
1623 ObjCIdRedefinitionType = RedefType;
1626 /// Retrieve the type that \c Class has been defined to, which may be
1627 /// different from the built-in \c Class if \c Class has been typedef'd.
1628 QualType getObjCClassRedefinitionType() const {
1629 if (ObjCClassRedefinitionType.isNull())
1630 return getObjCClassType();
1631 return ObjCClassRedefinitionType;
1634 /// Set the user-written type that redefines 'SEL'.
1635 void setObjCClassRedefinitionType(QualType RedefType) {
1636 ObjCClassRedefinitionType = RedefType;
1639 /// Retrieve the type that 'SEL' has been defined to, which may be
1640 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1641 QualType getObjCSelRedefinitionType() const {
1642 if (ObjCSelRedefinitionType.isNull())
1643 return getObjCSelType();
1644 return ObjCSelRedefinitionType;
1647 /// Set the user-written type that redefines 'SEL'.
1648 void setObjCSelRedefinitionType(QualType RedefType) {
1649 ObjCSelRedefinitionType = RedefType;
1652 /// Retrieve the identifier 'NSObject'.
1653 IdentifierInfo *getNSObjectName() {
1654 if (!NSObjectName) {
1655 NSObjectName = &Idents.get("NSObject");
1658 return NSObjectName;
1661 /// Retrieve the identifier 'NSCopying'.
1662 IdentifierInfo *getNSCopyingName() {
1663 if (!NSCopyingName) {
1664 NSCopyingName = &Idents.get("NSCopying");
1667 return NSCopyingName;
1670 CanQualType getNSUIntegerType() const {
1671 assert(Target && "Expected target to be initialized");
1672 const llvm::Triple &T = Target->getTriple();
1673 // Windows is LLP64 rather than LP64
1674 if (T.isOSWindows() && T.isArch64Bit())
1675 return UnsignedLongLongTy;
1676 return UnsignedLongTy;
1679 CanQualType getNSIntegerType() const {
1680 assert(Target && "Expected target to be initialized");
1681 const llvm::Triple &T = Target->getTriple();
1682 // Windows is LLP64 rather than LP64
1683 if (T.isOSWindows() && T.isArch64Bit())
1688 /// Retrieve the identifier 'bool'.
1689 IdentifierInfo *getBoolName() const {
1691 BoolName = &Idents.get("bool");
1695 IdentifierInfo *getMakeIntegerSeqName() const {
1696 if (!MakeIntegerSeqName)
1697 MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1698 return MakeIntegerSeqName;
1701 IdentifierInfo *getTypePackElementName() const {
1702 if (!TypePackElementName)
1703 TypePackElementName = &Idents.get("__type_pack_element");
1704 return TypePackElementName;
1707 /// Retrieve the Objective-C "instancetype" type, if already known;
1708 /// otherwise, returns a NULL type;
1709 QualType getObjCInstanceType() {
1710 return getTypeDeclType(getObjCInstanceTypeDecl());
1713 /// Retrieve the typedef declaration corresponding to the Objective-C
1714 /// "instancetype" type.
1715 TypedefDecl *getObjCInstanceTypeDecl();
1717 /// Set the type for the C FILE type.
1718 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1720 /// Retrieve the C FILE type.
1721 QualType getFILEType() const {
1723 return getTypeDeclType(FILEDecl);
1727 /// Set the type for the C jmp_buf type.
1728 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1729 this->jmp_bufDecl = jmp_bufDecl;
1732 /// Retrieve the C jmp_buf type.
1733 QualType getjmp_bufType() const {
1735 return getTypeDeclType(jmp_bufDecl);
1739 /// Set the type for the C sigjmp_buf type.
1740 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1741 this->sigjmp_bufDecl = sigjmp_bufDecl;
1744 /// Retrieve the C sigjmp_buf type.
1745 QualType getsigjmp_bufType() const {
1747 return getTypeDeclType(sigjmp_bufDecl);
1751 /// Set the type for the C ucontext_t type.
1752 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1753 this->ucontext_tDecl = ucontext_tDecl;
1756 /// Retrieve the C ucontext_t type.
1757 QualType getucontext_tType() const {
1759 return getTypeDeclType(ucontext_tDecl);
1763 /// The result type of logical operations, '<', '>', '!=', etc.
1764 QualType getLogicalOperationType() const {
1765 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1768 /// Emit the Objective-CC type encoding for the given type \p T into
1771 /// If \p Field is specified then record field names are also encoded.
1772 void getObjCEncodingForType(QualType T, std::string &S,
1773 const FieldDecl *Field=nullptr,
1774 QualType *NotEncodedT=nullptr) const;
1776 /// Emit the Objective-C property type encoding for the given
1777 /// type \p T into \p S.
1778 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1780 void getLegacyIntegralTypeEncoding(QualType &t) const;
1782 /// Put the string version of the type qualifiers \p QT into \p S.
1783 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1784 std::string &S) const;
1786 /// Emit the encoded type for the function \p Decl into \p S.
1788 /// This is in the same format as Objective-C method encodings.
1790 /// \returns true if an error occurred (e.g., because one of the parameter
1791 /// types is incomplete), false otherwise.
1792 std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
1794 /// Emit the encoded type for the method declaration \p Decl into
1796 std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1797 bool Extended = false) const;
1799 /// Return the encoded type for this block declaration.
1800 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1802 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1803 /// this method declaration. If non-NULL, Container must be either
1804 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1805 /// only be NULL when getting encodings for protocol properties.
1806 std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1807 const Decl *Container) const;
1809 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1810 ObjCProtocolDecl *rProto) const;
1812 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1813 const ObjCPropertyDecl *PD,
1814 const Decl *Container) const;
1816 /// Return the size of type \p T for Objective-C encoding purpose,
1818 CharUnits getObjCEncodingTypeSize(QualType T) const;
1820 /// Retrieve the typedef corresponding to the predefined \c id type
1822 TypedefDecl *getObjCIdDecl() const;
1824 /// Represents the Objective-CC \c id type.
1826 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1827 /// pointer type, a pointer to a struct.
1828 QualType getObjCIdType() const {
1829 return getTypeDeclType(getObjCIdDecl());
1832 /// Retrieve the typedef corresponding to the predefined 'SEL' type
1834 TypedefDecl *getObjCSelDecl() const;
1836 /// Retrieve the type that corresponds to the predefined Objective-C
1838 QualType getObjCSelType() const {
1839 return getTypeDeclType(getObjCSelDecl());
1842 /// Retrieve the typedef declaration corresponding to the predefined
1843 /// Objective-C 'Class' type.
1844 TypedefDecl *getObjCClassDecl() const;
1846 /// Represents the Objective-C \c Class type.
1848 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1849 /// pointer type, a pointer to a struct.
1850 QualType getObjCClassType() const {
1851 return getTypeDeclType(getObjCClassDecl());
1854 /// Retrieve the Objective-C class declaration corresponding to
1855 /// the predefined \c Protocol class.
1856 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1858 /// Retrieve declaration of 'BOOL' typedef
1859 TypedefDecl *getBOOLDecl() const {
1863 /// Save declaration of 'BOOL' typedef
1864 void setBOOLDecl(TypedefDecl *TD) {
1868 /// type of 'BOOL' type.
1869 QualType getBOOLType() const {
1870 return getTypeDeclType(getBOOLDecl());
1873 /// Retrieve the type of the Objective-C \c Protocol class.
1874 QualType getObjCProtoType() const {
1875 return getObjCInterfaceType(getObjCProtocolDecl());
1878 /// Retrieve the C type declaration corresponding to the predefined
1879 /// \c __builtin_va_list type.
1880 TypedefDecl *getBuiltinVaListDecl() const;
1882 /// Retrieve the type of the \c __builtin_va_list type.
1883 QualType getBuiltinVaListType() const {
1884 return getTypeDeclType(getBuiltinVaListDecl());
1887 /// Retrieve the C type declaration corresponding to the predefined
1888 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1889 /// for some targets.
1890 Decl *getVaListTagDecl() const;
1892 /// Retrieve the C type declaration corresponding to the predefined
1893 /// \c __builtin_ms_va_list type.
1894 TypedefDecl *getBuiltinMSVaListDecl() const;
1896 /// Retrieve the type of the \c __builtin_ms_va_list type.
1897 QualType getBuiltinMSVaListType() const {
1898 return getTypeDeclType(getBuiltinMSVaListDecl());
1901 /// Return whether a declaration to a builtin is allowed to be
1902 /// overloaded/redeclared.
1903 bool canBuiltinBeRedeclared(const FunctionDecl *) const;
1905 /// Return a type with additional \c const, \c volatile, or
1906 /// \c restrict qualifiers.
1907 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1908 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1911 /// Un-split a SplitQualType.
1912 QualType getQualifiedType(SplitQualType split) const {
1913 return getQualifiedType(split.Ty, split.Quals);
1916 /// Return a type with additional qualifiers.
1917 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1918 if (!Qs.hasNonFastQualifiers())
1919 return T.withFastQualifiers(Qs.getFastQualifiers());
1920 QualifierCollector Qc(Qs);
1921 const Type *Ptr = Qc.strip(T);
1922 return getExtQualType(Ptr, Qc);
1925 /// Return a type with additional qualifiers.
1926 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1927 if (!Qs.hasNonFastQualifiers())
1928 return QualType(T, Qs.getFastQualifiers());
1929 return getExtQualType(T, Qs);
1932 /// Return a type with the given lifetime qualifier.
1934 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1935 QualType getLifetimeQualifiedType(QualType type,
1936 Qualifiers::ObjCLifetime lifetime) {
1937 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1938 assert(lifetime != Qualifiers::OCL_None);
1941 qs.addObjCLifetime(lifetime);
1942 return getQualifiedType(type, qs);
1945 /// getUnqualifiedObjCPointerType - Returns version of
1946 /// Objective-C pointer type with lifetime qualifier removed.
1947 QualType getUnqualifiedObjCPointerType(QualType type) const {
1948 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1949 !type.getQualifiers().hasObjCLifetime())
1951 Qualifiers Qs = type.getQualifiers();
1952 Qs.removeObjCLifetime();
1953 return getQualifiedType(type.getUnqualifiedType(), Qs);
1956 unsigned char getFixedPointScale(QualType Ty) const;
1957 unsigned char getFixedPointIBits(QualType Ty) const;
1959 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1960 SourceLocation NameLoc) const;
1962 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1963 UnresolvedSetIterator End) const;
1965 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1966 bool TemplateKeyword,
1967 TemplateDecl *Template) const;
1969 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1970 const IdentifierInfo *Name) const;
1971 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1972 OverloadedOperatorKind Operator) const;
1973 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1974 TemplateName replacement) const;
1975 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1976 const TemplateArgument &ArgPack) const;
1978 enum GetBuiltinTypeError {
1982 /// Missing a type from <stdio.h>
1985 /// Missing a type from <setjmp.h>
1988 /// Missing a type from <ucontext.h>
1992 /// Return the type for the specified builtin.
1994 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1995 /// arguments to the builtin that are required to be integer constant
1997 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1998 unsigned *IntegerConstantArgs = nullptr) const;
2000 /// Types and expressions required to build C++2a three-way comparisons
2001 /// using operator<=>, including the values return by builtin <=> operators.
2002 ComparisonCategories CompCategories;
2005 CanQualType getFromTargetType(unsigned Type) const;
2006 TypeInfo getTypeInfoImpl(const Type *T) const;
2008 //===--------------------------------------------------------------------===//
2010 //===--------------------------------------------------------------------===//
2013 /// Return one of the GCNone, Weak or Strong Objective-C garbage
2014 /// collection attributes.
2015 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
2017 /// Return true if the given vector types are of the same unqualified
2018 /// type or if they are equivalent to the same GCC vector type.
2020 /// \note This ignores whether they are target-specific (AltiVec or Neon)
2022 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
2024 /// Return true if this is an \c NSObject object with its \c NSObject
2026 static bool isObjCNSObjectType(QualType Ty) {
2027 return Ty->isObjCNSObjectType();
2030 //===--------------------------------------------------------------------===//
2031 // Type Sizing and Analysis
2032 //===--------------------------------------------------------------------===//
2034 /// Return the APFloat 'semantics' for the specified scalar floating
2036 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
2038 /// Get the size and alignment of the specified complete type in bits.
2039 TypeInfo getTypeInfo(const Type *T) const;
2040 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
2042 /// Get default simd alignment of the specified complete type in bits.
2043 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
2045 /// Return the size of the specified (complete) type \p T, in bits.
2046 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
2047 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
2049 /// Return the size of the character type, in bits.
2050 uint64_t getCharWidth() const {
2051 return getTypeSize(CharTy);
2054 /// Convert a size in bits to a size in characters.
2055 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
2057 /// Convert a size in characters to a size in bits.
2058 int64_t toBits(CharUnits CharSize) const;
2060 /// Return the size of the specified (complete) type \p T, in
2062 CharUnits getTypeSizeInChars(QualType T) const;
2063 CharUnits getTypeSizeInChars(const Type *T) const;
2065 /// Return the ABI-specified alignment of a (complete) type \p T, in
2067 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
2068 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
2070 /// Return the ABI-specified alignment of a type, in bits, or 0 if
2071 /// the type is incomplete and we cannot determine the alignment (for
2072 /// example, from alignment attributes).
2073 unsigned getTypeAlignIfKnown(QualType T) const;
2075 /// Return the ABI-specified alignment of a (complete) type \p T, in
2077 CharUnits getTypeAlignInChars(QualType T) const;
2078 CharUnits getTypeAlignInChars(const Type *T) const;
2080 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
2081 // type is a record, its data size is returned.
2082 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
2084 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
2085 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
2087 /// Determine if the alignment the type has was required using an
2088 /// alignment attribute.
2089 bool isAlignmentRequired(const Type *T) const;
2090 bool isAlignmentRequired(QualType T) const;
2092 /// Return the "preferred" alignment of the specified type \p T for
2093 /// the current target, in bits.
2095 /// This can be different than the ABI alignment in cases where it is
2096 /// beneficial for performance to overalign a data type.
2097 unsigned getPreferredTypeAlign(const Type *T) const;
2099 /// Return the default alignment for __attribute__((aligned)) on
2100 /// this target, to be used if no alignment value is specified.
2101 unsigned getTargetDefaultAlignForAttributeAligned() const;
2103 /// Return the alignment in bits that should be given to a
2104 /// global variable with type \p T.
2105 unsigned getAlignOfGlobalVar(QualType T) const;
2107 /// Return the alignment in characters that should be given to a
2108 /// global variable with type \p T.
2109 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
2111 /// Return a conservative estimate of the alignment of the specified
2114 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
2117 /// If \p ForAlignof, references are treated like their underlying type
2118 /// and large arrays don't get any special treatment. If not \p ForAlignof
2119 /// it computes the value expected by CodeGen: references are treated like
2120 /// pointers and large arrays get extra alignment.
2121 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2123 /// Get or compute information about the layout of the specified
2124 /// record (struct/union/class) \p D, which indicates its size and field
2125 /// position information.
2126 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2128 /// Get or compute information about the layout of the specified
2129 /// Objective-C interface.
2130 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2133 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2134 bool Simple = false) const;
2136 /// Get or compute information about the layout of the specified
2137 /// Objective-C implementation.
2139 /// This may differ from the interface if synthesized ivars are present.
2140 const ASTRecordLayout &
2141 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2143 /// Get our current best idea for the key function of the
2144 /// given record decl, or nullptr if there isn't one.
2146 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2147 /// ...the first non-pure virtual function that is not inline at the
2148 /// point of class definition.
2150 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
2151 /// virtual functions that are defined 'inline', which means that
2152 /// the result of this computation can change.
2153 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2155 /// Observe that the given method cannot be a key function.
2156 /// Checks the key-function cache for the method's class and clears it
2157 /// if matches the given declaration.
2159 /// This is used in ABIs where out-of-line definitions marked
2160 /// inline are not considered to be key functions.
2162 /// \param method should be the declaration from the class definition
2163 void setNonKeyFunction(const CXXMethodDecl *method);
2165 /// Loading virtual member pointers using the virtual inheritance model
2166 /// always results in an adjustment using the vbtable even if the index is
2169 /// This is usually OK because the first slot in the vbtable points
2170 /// backwards to the top of the MDC. However, the MDC might be reusing a
2171 /// vbptr from an nv-base. In this case, the first slot in the vbtable
2172 /// points to the start of the nv-base which introduced the vbptr and *not*
2173 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
2174 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2176 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2177 uint64_t getFieldOffset(const ValueDecl *FD) const;
2179 /// Get the offset of an ObjCIvarDecl in bits.
2180 uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2181 const ObjCImplementationDecl *ID,
2182 const ObjCIvarDecl *Ivar) const;
2184 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2186 VTableContextBase *getVTableContext();
2188 MangleContext *createMangleContext();
2190 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2191 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2193 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2194 void CollectInheritedProtocols(const Decl *CDecl,
2195 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2197 /// Return true if the specified type has unique object representations
2198 /// according to (C++17 [meta.unary.prop]p9)
2199 bool hasUniqueObjectRepresentations(QualType Ty) const;
2201 //===--------------------------------------------------------------------===//
2203 //===--------------------------------------------------------------------===//
2205 /// Return the canonical (structural) type corresponding to the
2206 /// specified potentially non-canonical type \p T.
2208 /// The non-canonical version of a type may have many "decorated" versions of
2209 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
2210 /// returned type is guaranteed to be free of any of these, allowing two
2211 /// canonical types to be compared for exact equality with a simple pointer
2213 CanQualType getCanonicalType(QualType T) const {
2214 return CanQualType::CreateUnsafe(T.getCanonicalType());
2217 const Type *getCanonicalType(const Type *T) const {
2218 return T->getCanonicalTypeInternal().getTypePtr();
2221 /// Return the canonical parameter type corresponding to the specific
2222 /// potentially non-canonical one.
2224 /// Qualifiers are stripped off, functions are turned into function
2225 /// pointers, and arrays decay one level into pointers.
2226 CanQualType getCanonicalParamType(QualType T) const;
2228 /// Determine whether the given types \p T1 and \p T2 are equivalent.
2229 bool hasSameType(QualType T1, QualType T2) const {
2230 return getCanonicalType(T1) == getCanonicalType(T2);
2232 bool hasSameType(const Type *T1, const Type *T2) const {
2233 return getCanonicalType(T1) == getCanonicalType(T2);
2236 /// Return this type as a completely-unqualified array type,
2237 /// capturing the qualifiers in \p Quals.
2239 /// This will remove the minimal amount of sugaring from the types, similar
2240 /// to the behavior of QualType::getUnqualifiedType().
2242 /// \param T is the qualified type, which may be an ArrayType
2244 /// \param Quals will receive the full set of qualifiers that were
2245 /// applied to the array.
2247 /// \returns if this is an array type, the completely unqualified array type
2248 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2249 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2251 /// Determine whether the given types are equivalent after
2252 /// cvr-qualifiers have been removed.
2253 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2254 return getCanonicalType(T1).getTypePtr() ==
2255 getCanonicalType(T2).getTypePtr();
2258 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2259 bool IsParam) const {
2260 auto SubTnullability = SubT->getNullability(*this);
2261 auto SuperTnullability = SuperT->getNullability(*this);
2262 if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
2263 // Neither has nullability; return true
2264 if (!SubTnullability)
2266 // Both have nullability qualifier.
2267 if (*SubTnullability == *SuperTnullability ||
2268 *SubTnullability == NullabilityKind::Unspecified ||
2269 *SuperTnullability == NullabilityKind::Unspecified)
2273 // Ok for the superclass method parameter to be "nonnull" and the subclass
2274 // method parameter to be "nullable"
2275 return (*SuperTnullability == NullabilityKind::NonNull &&
2276 *SubTnullability == NullabilityKind::Nullable);
2279 // For the return type, it's okay for the superclass method to specify
2280 // "nullable" and the subclass method specify "nonnull"
2281 return (*SuperTnullability == NullabilityKind::Nullable &&
2282 *SubTnullability == NullabilityKind::NonNull);
2288 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2289 const ObjCMethodDecl *MethodImp);
2291 bool UnwrapSimilarTypes(QualType &T1, QualType &T2);
2292 bool UnwrapSimilarArrayTypes(QualType &T1, QualType &T2);
2294 /// Determine if two types are similar, according to the C++ rules. That is,
2295 /// determine if they are the same other than qualifiers on the initial
2296 /// sequence of pointer / pointer-to-member / array (and in Clang, object
2297 /// pointer) types and their element types.
2299 /// Clang offers a number of qualifiers in addition to the C++ qualifiers;
2300 /// those qualifiers are also ignored in the 'similarity' check.
2301 bool hasSimilarType(QualType T1, QualType T2);
2303 /// Determine if two types are similar, ignoring only CVR qualifiers.
2304 bool hasCvrSimilarType(QualType T1, QualType T2);
2306 /// Retrieves the "canonical" nested name specifier for a
2307 /// given nested name specifier.
2309 /// The canonical nested name specifier is a nested name specifier
2310 /// that uniquely identifies a type or namespace within the type
2311 /// system. For example, given:
2316 /// template<typename T> struct X { typename T* type; };
2320 /// template<typename T> struct Y {
2321 /// typename N::S::X<T>::type member;
2325 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2326 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2327 /// by declarations in the type system and the canonical type for
2328 /// the template type parameter 'T' is template-param-0-0.
2329 NestedNameSpecifier *
2330 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2332 /// Retrieves the default calling convention for the current target.
2333 CallingConv getDefaultCallingConvention(bool IsVariadic,
2334 bool IsCXXMethod) const;
2336 /// Retrieves the "canonical" template name that refers to a
2339 /// The canonical template name is the simplest expression that can
2340 /// be used to refer to a given template. For most templates, this
2341 /// expression is just the template declaration itself. For example,
2342 /// the template std::vector can be referred to via a variety of
2343 /// names---std::vector, \::std::vector, vector (if vector is in
2344 /// scope), etc.---but all of these names map down to the same
2345 /// TemplateDecl, which is used to form the canonical template name.
2347 /// Dependent template names are more interesting. Here, the
2348 /// template name could be something like T::template apply or
2349 /// std::allocator<T>::template rebind, where the nested name
2350 /// specifier itself is dependent. In this case, the canonical
2351 /// template name uses the shortest form of the dependent
2352 /// nested-name-specifier, which itself contains all canonical
2353 /// types, values, and templates.
2354 TemplateName getCanonicalTemplateName(TemplateName Name) const;
2356 /// Determine whether the given template names refer to the same
2358 bool hasSameTemplateName(TemplateName X, TemplateName Y);
2360 /// Retrieve the "canonical" template argument.
2362 /// The canonical template argument is the simplest template argument
2363 /// (which may be a type, value, expression, or declaration) that
2364 /// expresses the value of the argument.
2365 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2368 /// Type Query functions. If the type is an instance of the specified class,
2369 /// return the Type pointer for the underlying maximally pretty type. This
2370 /// is a member of ASTContext because this may need to do some amount of
2371 /// canonicalization, e.g. to move type qualifiers into the element type.
2372 const ArrayType *getAsArrayType(QualType T) const;
2373 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2374 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2376 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2377 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2379 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2380 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2382 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2384 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2387 /// Return the innermost element type of an array type.
2389 /// For example, will return "int" for int[m][n]
2390 QualType getBaseElementType(const ArrayType *VAT) const;
2392 /// Return the innermost element type of a type (which needn't
2393 /// actually be an array type).
2394 QualType getBaseElementType(QualType QT) const;
2396 /// Return number of constant array elements.
2397 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2399 /// Perform adjustment on the parameter type of a function.
2401 /// This routine adjusts the given parameter type @p T to the actual
2402 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2403 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2404 QualType getAdjustedParameterType(QualType T) const;
2406 /// Retrieve the parameter type as adjusted for use in the signature
2407 /// of a function, decaying array and function types and removing top-level
2409 QualType getSignatureParameterType(QualType T) const;
2411 QualType getExceptionObjectType(QualType T) const;
2413 /// Return the properly qualified result of decaying the specified
2414 /// array type to a pointer.
2416 /// This operation is non-trivial when handling typedefs etc. The canonical
2417 /// type of \p T must be an array type, this returns a pointer to a properly
2418 /// qualified element of the array.
2420 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2421 QualType getArrayDecayedType(QualType T) const;
2423 /// Return the type that \p PromotableType will promote to: C99
2424 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2425 QualType getPromotedIntegerType(QualType PromotableType) const;
2427 /// Recurses in pointer/array types until it finds an Objective-C
2428 /// retainable type and returns its ownership.
2429 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2431 /// Whether this is a promotable bitfield reference according
2432 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2434 /// \returns the type this bit-field will promote to, or NULL if no
2435 /// promotion occurs.
2436 QualType isPromotableBitField(Expr *E) const;
2438 /// Return the highest ranked integer type, see C99 6.3.1.8p1.
2440 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2441 /// \p LHS < \p RHS, return -1.
2442 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2444 /// Compare the rank of the two specified floating point types,
2445 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2447 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2448 /// \p LHS < \p RHS, return -1.
2449 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2451 /// Return a real floating point or a complex type (based on
2452 /// \p typeDomain/\p typeSize).
2454 /// \param typeDomain a real floating point or complex type.
2455 /// \param typeSize a real floating point or complex type.
2456 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2457 QualType typeDomain) const;
2459 unsigned getTargetAddressSpace(QualType T) const {
2460 return getTargetAddressSpace(T.getQualifiers());
2463 unsigned getTargetAddressSpace(Qualifiers Q) const {
2464 return getTargetAddressSpace(Q.getAddressSpace());
2467 unsigned getTargetAddressSpace(LangAS AS) const;
2469 /// Get target-dependent integer value for null pointer which is used for
2470 /// constant folding.
2471 uint64_t getTargetNullPointerValue(QualType QT) const;
2473 bool addressSpaceMapManglingFor(LangAS AS) const {
2474 return AddrSpaceMapMangling || isTargetAddressSpace(AS);
2478 // Helper for integer ordering
2479 unsigned getIntegerRank(const Type *T) const;
2482 //===--------------------------------------------------------------------===//
2483 // Type Compatibility Predicates
2484 //===--------------------------------------------------------------------===//
2486 /// Compatibility predicates used to check assignment expressions.
2487 bool typesAreCompatible(QualType T1, QualType T2,
2488 bool CompareUnqualified = false); // C99 6.2.7p1
2490 bool propertyTypesAreCompatible(QualType, QualType);
2491 bool typesAreBlockPointerCompatible(QualType, QualType);
2493 bool isObjCIdType(QualType T) const {
2494 return T == getObjCIdType();
2497 bool isObjCClassType(QualType T) const {
2498 return T == getObjCClassType();
2501 bool isObjCSelType(QualType T) const {
2502 return T == getObjCSelType();
2505 bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
2508 bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
2510 // Check the safety of assignment from LHS to RHS
2511 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2512 const ObjCObjectPointerType *RHSOPT);
2513 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2514 const ObjCObjectType *RHS);
2515 bool canAssignObjCInterfacesInBlockPointer(
2516 const ObjCObjectPointerType *LHSOPT,
2517 const ObjCObjectPointerType *RHSOPT,
2518 bool BlockReturnType);
2519 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2520 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2521 const ObjCObjectPointerType *RHSOPT);
2522 bool canBindObjCObjectType(QualType To, QualType From);
2524 // Functions for calculating composite types
2525 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2526 bool Unqualified = false, bool BlockReturnType = false);
2527 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2528 bool Unqualified = false);
2529 QualType mergeFunctionParameterTypes(QualType, QualType,
2530 bool OfBlockPointer = false,
2531 bool Unqualified = false);
2532 QualType mergeTransparentUnionType(QualType, QualType,
2533 bool OfBlockPointer=false,
2534 bool Unqualified = false);
2536 QualType mergeObjCGCQualifiers(QualType, QualType);
2538 /// This function merges the ExtParameterInfo lists of two functions. It
2539 /// returns true if the lists are compatible. The merged list is returned in
2542 /// \param FirstFnType The type of the first function.
2544 /// \param SecondFnType The type of the second function.
2546 /// \param CanUseFirst This flag is set to true if the first function's
2547 /// ExtParameterInfo list can be used as the composite list of
2548 /// ExtParameterInfo.
2550 /// \param CanUseSecond This flag is set to true if the second function's
2551 /// ExtParameterInfo list can be used as the composite list of
2552 /// ExtParameterInfo.
2554 /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
2555 /// empty if none of the flags are set.
2557 bool mergeExtParameterInfo(
2558 const FunctionProtoType *FirstFnType,
2559 const FunctionProtoType *SecondFnType,
2560 bool &CanUseFirst, bool &CanUseSecond,
2561 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
2563 void ResetObjCLayout(const ObjCContainerDecl *CD);
2565 //===--------------------------------------------------------------------===//
2566 // Integer Predicates
2567 //===--------------------------------------------------------------------===//
2569 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2570 // of bits in an integer type excluding any padding bits.
2571 unsigned getIntWidth(QualType T) const;
2573 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2574 // unsigned integer type. This method takes a signed type, and returns the
2575 // corresponding unsigned integer type.
2576 // With the introduction of fixed point types in ISO N1169, this method also
2577 // accepts fixed point types and returns the corresponding unsigned type for
2578 // a given fixed point type.
2579 QualType getCorrespondingUnsignedType(QualType T) const;
2581 // Per ISO N1169, this method accepts fixed point types and returns the
2582 // corresponding saturated type for a given fixed point type.
2583 QualType getCorrespondingSaturatedType(QualType Ty) const;
2585 //===--------------------------------------------------------------------===//
2587 //===--------------------------------------------------------------------===//
2589 /// Make an APSInt of the appropriate width and signedness for the
2590 /// given \p Value and integer \p Type.
2591 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2592 // If Type is a signed integer type larger than 64 bits, we need to be sure
2593 // to sign extend Res appropriately.
2594 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2596 unsigned Width = getIntWidth(Type);
2597 if (Width != Res.getBitWidth())
2598 return Res.extOrTrunc(Width);
2602 bool isSentinelNullExpr(const Expr *E);
2604 /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
2606 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2608 /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
2610 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2612 /// Return true if there is at least one \@implementation in the TU.
2613 bool AnyObjCImplementation() {
2614 return !ObjCImpls.empty();
2617 /// Set the implementation of ObjCInterfaceDecl.
2618 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2619 ObjCImplementationDecl *ImplD);
2621 /// Set the implementation of ObjCCategoryDecl.
2622 void setObjCImplementation(ObjCCategoryDecl *CatD,
2623 ObjCCategoryImplDecl *ImplD);
2625 /// Get the duplicate declaration of a ObjCMethod in the same
2626 /// interface, or null if none exists.
2627 const ObjCMethodDecl *
2628 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2630 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2631 const ObjCMethodDecl *Redecl);
2633 /// Returns the Objective-C interface that \p ND belongs to if it is
2634 /// an Objective-C method/property/ivar etc. that is part of an interface,
2635 /// otherwise returns null.
2636 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2638 /// Set the copy inialization expression of a block var decl.
2639 void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2641 /// Get the copy initialization expression of the VarDecl \p VD, or
2642 /// nullptr if none exists.
2643 Expr *getBlockVarCopyInits(const VarDecl* VD);
2645 /// Allocate an uninitialized TypeSourceInfo.
2647 /// The caller should initialize the memory held by TypeSourceInfo using
2648 /// the TypeLoc wrappers.
2650 /// \param T the type that will be the basis for type source info. This type
2651 /// should refer to how the declarator was written in source code, not to
2652 /// what type semantic analysis resolved the declarator to.
2654 /// \param Size the size of the type info to create, or 0 if the size
2655 /// should be calculated based on the type.
2656 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2658 /// Allocate a TypeSourceInfo where all locations have been
2659 /// initialized to a given location, which defaults to the empty
2662 getTrivialTypeSourceInfo(QualType T,
2663 SourceLocation Loc = SourceLocation()) const;
2665 /// Add a deallocation callback that will be invoked when the
2666 /// ASTContext is destroyed.
2668 /// \param Callback A callback function that will be invoked on destruction.
2670 /// \param Data Pointer data that will be provided to the callback function
2671 /// when it is called.
2672 void AddDeallocation(void (*Callback)(void*), void *Data);
2674 /// If T isn't trivially destructible, calls AddDeallocation to register it
2675 /// for destruction.
2676 template <typename T>
2677 void addDestruction(T *Ptr) {
2678 if (!std::is_trivially_destructible<T>::value) {
2679 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
2680 AddDeallocation(DestroyPtr, Ptr);
2684 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2685 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2687 /// Determines if the decl can be CodeGen'ed or deserialized from PCH
2688 /// lazily, only when used; this is only relevant for function or file scoped
2689 /// var definitions.
2691 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2693 bool DeclMustBeEmitted(const Decl *D);
2695 /// Visits all versions of a multiversioned function with the passed
2697 void forEachMultiversionedFunctionVersion(
2698 const FunctionDecl *FD,
2699 llvm::function_ref<void(const FunctionDecl *)> Pred) const;
2701 const CXXConstructorDecl *
2702 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2704 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2705 CXXConstructorDecl *CD);
2707 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2709 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2711 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2713 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2715 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2716 unsigned getManglingNumber(const NamedDecl *ND) const;
2718 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2719 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2721 /// Retrieve the context for computing mangling numbers in the given
2723 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2725 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
2727 /// Used by ParmVarDecl to store on the side the
2728 /// index of the parameter when it exceeds the size of the normal bitfield.
2729 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2731 /// Used by ParmVarDecl to retrieve on the side the
2732 /// index of the parameter when it exceeds the size of the normal bitfield.
2733 unsigned getParameterIndex(const ParmVarDecl *D) const;
2735 /// Get the storage for the constant value of a materialized temporary
2736 /// of static storage duration.
2737 APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
2740 //===--------------------------------------------------------------------===//
2742 //===--------------------------------------------------------------------===//
2744 /// The number of implicitly-declared default constructors.
2745 static unsigned NumImplicitDefaultConstructors;
2747 /// The number of implicitly-declared default constructors for
2748 /// which declarations were built.
2749 static unsigned NumImplicitDefaultConstructorsDeclared;
2751 /// The number of implicitly-declared copy constructors.
2752 static unsigned NumImplicitCopyConstructors;
2754 /// The number of implicitly-declared copy constructors for
2755 /// which declarations were built.
2756 static unsigned NumImplicitCopyConstructorsDeclared;
2758 /// The number of implicitly-declared move constructors.
2759 static unsigned NumImplicitMoveConstructors;
2761 /// The number of implicitly-declared move constructors for
2762 /// which declarations were built.
2763 static unsigned NumImplicitMoveConstructorsDeclared;
2765 /// The number of implicitly-declared copy assignment operators.
2766 static unsigned NumImplicitCopyAssignmentOperators;
2768 /// The number of implicitly-declared copy assignment operators for
2769 /// which declarations were built.
2770 static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2772 /// The number of implicitly-declared move assignment operators.
2773 static unsigned NumImplicitMoveAssignmentOperators;
2775 /// The number of implicitly-declared move assignment operators for
2776 /// which declarations were built.
2777 static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2779 /// The number of implicitly-declared destructors.
2780 static unsigned NumImplicitDestructors;
2782 /// The number of implicitly-declared destructors for which
2783 /// declarations were built.
2784 static unsigned NumImplicitDestructorsDeclared;
2787 /// Initialize built-in types.
2789 /// This routine may only be invoked once for a given ASTContext object.
2790 /// It is normally invoked after ASTContext construction.
2792 /// \param Target The target
2793 void InitBuiltinTypes(const TargetInfo &Target,
2794 const TargetInfo *AuxTarget = nullptr);
2797 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2799 // Return the Objective-C type encoding for a given type.
2800 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2801 bool ExpandPointedToStructures,
2802 bool ExpandStructures,
2803 const FieldDecl *Field,
2804 bool OutermostType = false,
2805 bool EncodingProperty = false,
2806 bool StructField = false,
2807 bool EncodeBlockParameters = false,
2808 bool EncodeClassNames = false,
2809 bool EncodePointerToObjCTypedef = false,
2810 QualType *NotEncodedT=nullptr) const;
2812 // Adds the encoding of the structure's members.
2813 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2814 const FieldDecl *Field,
2815 bool includeVBases = true,
2816 QualType *NotEncodedT=nullptr) const;
2819 // Adds the encoding of a method parameter or return type.
2820 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2821 QualType T, std::string& S,
2822 bool Extended) const;
2824 /// Returns true if this is an inline-initialized static data member
2825 /// which is treated as a definition for MSVC compatibility.
2826 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2828 enum class InlineVariableDefinitionKind {
2829 /// Not an inline variable.
2832 /// Weak definition of inline variable.
2835 /// Weak for now, might become strong later in this TU.
2838 /// Strong definition.
2842 /// Determine whether a definition of this inline variable should
2843 /// be treated as a weak or strong definition. For compatibility with
2844 /// C++14 and before, for a constexpr static data member, if there is an
2845 /// out-of-line declaration of the member, we may promote it from weak to
2847 InlineVariableDefinitionKind
2848 getInlineVariableDefinitionKind(const VarDecl *VD) const;
2851 friend class DeclarationNameTable;
2852 friend class DeclContext;
2854 const ASTRecordLayout &
2855 getObjCLayout(const ObjCInterfaceDecl *D,
2856 const ObjCImplementationDecl *Impl) const;
2858 /// A set of deallocations that should be performed when the
2859 /// ASTContext is destroyed.
2860 // FIXME: We really should have a better mechanism in the ASTContext to
2861 // manage running destructors for types which do variable sized allocation
2862 // within the AST. In some places we thread the AST bump pointer allocator
2863 // into the datastructures which avoids this mess during deallocation but is
2864 // wasteful of memory, and here we require a lot of error prone book keeping
2865 // in order to track and run destructors while we're tearing things down.
2866 using DeallocationFunctionsAndArguments =
2867 llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
2868 DeallocationFunctionsAndArguments Deallocations;
2870 // FIXME: This currently contains the set of StoredDeclMaps used
2871 // by DeclContext objects. This probably should not be in ASTContext,
2872 // but we include it here so that ASTContext can quickly deallocate them.
2873 llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
2875 std::unique_ptr<ParentMapPointers> PointerParents;
2876 std::unique_ptr<ParentMapOtherNodes> OtherParents;
2878 std::unique_ptr<VTableContextBase> VTContext;
2880 void ReleaseDeclContextMaps();
2881 void ReleaseParentMapEntries();
2884 enum PragmaSectionFlag : unsigned {
2890 PSF_Invalid = 0x80000000U,
2893 struct SectionInfo {
2894 DeclaratorDecl *Decl;
2895 SourceLocation PragmaSectionLocation;
2898 SectionInfo() = default;
2899 SectionInfo(DeclaratorDecl *Decl,
2900 SourceLocation PragmaSectionLocation,
2902 : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
2903 SectionFlags(SectionFlags) {}
2906 llvm::StringMap<SectionInfo> SectionInfos;
2909 /// Utility function for constructing a nullary selector.
2910 inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
2911 IdentifierInfo* II = &Ctx.Idents.get(name);
2912 return Ctx.Selectors.getSelector(0, &II);
2915 /// Utility function for constructing an unary selector.
2916 inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
2917 IdentifierInfo* II = &Ctx.Idents.get(name);
2918 return Ctx.Selectors.getSelector(1, &II);
2921 } // namespace clang
2923 // operator new and delete aren't allowed inside namespaces.
2925 /// Placement new for using the ASTContext's allocator.
2927 /// This placement form of operator new uses the ASTContext's allocator for
2928 /// obtaining memory.
2930 /// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2931 /// here need to also be made there.
2933 /// We intentionally avoid using a nothrow specification here so that the calls
2934 /// to this operator will not perform a null check on the result -- the
2935 /// underlying allocator never returns null pointers.
2937 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2939 /// // Default alignment (8)
2940 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2941 /// // Specific alignment
2942 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2944 /// Memory allocated through this placement new operator does not need to be
2945 /// explicitly freed, as ASTContext will free all of this memory when it gets
2946 /// destroyed. Please note that you cannot use delete on the pointer.
2948 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2949 /// @param C The ASTContext that provides the allocator.
2950 /// @param Alignment The alignment of the allocated memory (if the underlying
2951 /// allocator supports it).
2952 /// @return The allocated memory. Could be nullptr.
2953 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2955 return C.Allocate(Bytes, Alignment);
2958 /// Placement delete companion to the new above.
2960 /// This operator is just a companion to the new above. There is no way of
2961 /// invoking it directly; see the new operator for more details. This operator
2962 /// is called implicitly by the compiler if a placement new expression using
2963 /// the ASTContext throws in the object constructor.
2964 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2968 /// This placement form of operator new[] uses the ASTContext's allocator for
2969 /// obtaining memory.
2971 /// We intentionally avoid using a nothrow specification here so that the calls
2972 /// to this operator will not perform a null check on the result -- the
2973 /// underlying allocator never returns null pointers.
2975 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2977 /// // Default alignment (8)
2978 /// char *data = new (Context) char[10];
2979 /// // Specific alignment
2980 /// char *data = new (Context, 4) char[10];
2982 /// Memory allocated through this placement new[] operator does not need to be
2983 /// explicitly freed, as ASTContext will free all of this memory when it gets
2984 /// destroyed. Please note that you cannot use delete on the pointer.
2986 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2987 /// @param C The ASTContext that provides the allocator.
2988 /// @param Alignment The alignment of the allocated memory (if the underlying
2989 /// allocator supports it).
2990 /// @return The allocated memory. Could be nullptr.
2991 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2992 size_t Alignment = 8) {
2993 return C.Allocate(Bytes, Alignment);
2996 /// Placement delete[] companion to the new[] above.
2998 /// This operator is just a companion to the new[] above. There is no way of
2999 /// invoking it directly; see the new[] operator for more details. This operator
3000 /// is called implicitly by the compiler if a placement new[] expression using
3001 /// the ASTContext throws in the object constructor.
3002 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
3006 /// Create the representation of a LazyGenerationalUpdatePtr.
3007 template <typename Owner, typename T,
3008 void (clang::ExternalASTSource::*Update)(Owner)>
3009 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
3010 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
3011 const clang::ASTContext &Ctx, T Value) {
3012 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
3013 // include ASTContext.h. We explicitly instantiate it for all relevant types
3014 // in ASTContext.cpp.
3015 if (auto *Source = Ctx.getExternalSource())
3016 return new (Ctx) LazyData(Source, Value);
3020 #endif // LLVM_CLANG_AST_ASTCONTEXT_H