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/ASTContextAllocate.h"
19 #include "clang/AST/ASTTypeTraits.h"
20 #include "clang/AST/CanonicalType.h"
21 #include "clang/AST/CommentCommandTraits.h"
22 #include "clang/AST/ComparisonCategories.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/AST/DeclBase.h"
25 #include "clang/AST/DeclarationName.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExternalASTSource.h"
28 #include "clang/AST/NestedNameSpecifier.h"
29 #include "clang/AST/PrettyPrinter.h"
30 #include "clang/AST/RawCommentList.h"
31 #include "clang/AST/TemplateBase.h"
32 #include "clang/AST/TemplateName.h"
33 #include "clang/AST/Type.h"
34 #include "clang/Basic/AddressSpaces.h"
35 #include "clang/Basic/AttrKinds.h"
36 #include "clang/Basic/IdentifierTable.h"
37 #include "clang/Basic/LLVM.h"
38 #include "clang/Basic/LangOptions.h"
39 #include "clang/Basic/Linkage.h"
40 #include "clang/Basic/OperatorKinds.h"
41 #include "clang/Basic/PartialDiagnostic.h"
42 #include "clang/Basic/SanitizerBlacklist.h"
43 #include "clang/Basic/SourceLocation.h"
44 #include "clang/Basic/Specifiers.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "clang/Basic/XRayLists.h"
47 #include "llvm/ADT/APSInt.h"
48 #include "llvm/ADT/ArrayRef.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/FoldingSet.h"
51 #include "llvm/ADT/IntrusiveRefCntPtr.h"
52 #include "llvm/ADT/MapVector.h"
53 #include "llvm/ADT/None.h"
54 #include "llvm/ADT/Optional.h"
55 #include "llvm/ADT/PointerIntPair.h"
56 #include "llvm/ADT/PointerUnion.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/StringMap.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/TinyPtrVector.h"
61 #include "llvm/ADT/Triple.h"
62 #include "llvm/ADT/iterator_range.h"
63 #include "llvm/Support/AlignOf.h"
64 #include "llvm/Support/Allocator.h"
65 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/Compiler.h"
73 #include <type_traits>
87 class ASTMutationListener;
88 class ASTRecordLayout;
91 class BuiltinTemplateDecl;
94 class CXXConstructorDecl;
97 class DiagnosticsEngine;
99 class FixedPointSemantics;
101 class MangleNumberingContext;
102 class MaterializeTemporaryExpr;
103 class MemberSpecializationInfo;
105 class ObjCCategoryDecl;
106 class ObjCCategoryImplDecl;
107 class ObjCContainerDecl;
109 class ObjCImplementationDecl;
110 class ObjCInterfaceDecl;
112 class ObjCMethodDecl;
113 class ObjCPropertyDecl;
114 class ObjCPropertyImplDecl;
115 class ObjCProtocolDecl;
116 class ObjCTypeParamDecl;
119 class StoredDeclsMap;
121 class TemplateParameterList;
122 class TemplateTemplateParmDecl;
123 class TemplateTypeParmDecl;
124 class UnresolvedSetIterator;
125 class UsingShadowDecl;
126 class VarTemplateDecl;
127 class VTableContextBase;
133 } // namespace Builtin
135 enum BuiltinTemplateKind : int;
141 } // namespace comments
146 bool AlignIsRequired : 1;
148 TypeInfo() : AlignIsRequired(false) {}
149 TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
150 : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
153 /// Holds long-lived AST nodes (such as types and decls) that can be
154 /// referred to throughout the semantic analysis of a file.
155 class ASTContext : public RefCountedBase<ASTContext> {
157 /// Copy initialization expr of a __block variable and a boolean flag that
158 /// indicates whether the expression can throw.
159 struct BlockVarCopyInit {
160 BlockVarCopyInit() = default;
161 BlockVarCopyInit(Expr *CopyExpr, bool CanThrow)
162 : ExprAndFlag(CopyExpr, CanThrow) {}
163 void setExprAndFlag(Expr *CopyExpr, bool CanThrow) {
164 ExprAndFlag.setPointerAndInt(CopyExpr, CanThrow);
166 Expr *getCopyExpr() const { return ExprAndFlag.getPointer(); }
167 bool canThrow() const { return ExprAndFlag.getInt(); }
168 llvm::PointerIntPair<Expr *, 1, bool> ExprAndFlag;
172 friend class NestedNameSpecifier;
174 mutable SmallVector<Type *, 0> Types;
175 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
176 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
177 mutable llvm::FoldingSet<PointerType> PointerTypes;
178 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
179 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
180 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
181 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
182 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
183 mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
184 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
185 mutable std::vector<VariableArrayType*> VariableArrayTypes;
186 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
187 mutable llvm::FoldingSet<DependentSizedExtVectorType>
188 DependentSizedExtVectorTypes;
189 mutable llvm::FoldingSet<DependentAddressSpaceType>
190 DependentAddressSpaceTypes;
191 mutable llvm::FoldingSet<VectorType> VectorTypes;
192 mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes;
193 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
194 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
196 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
197 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
198 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
199 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
200 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
201 SubstTemplateTypeParmTypes;
202 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
203 SubstTemplateTypeParmPackTypes;
204 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
205 TemplateSpecializationTypes;
206 mutable llvm::FoldingSet<ParenType> ParenTypes;
207 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
208 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
209 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
211 DependentTemplateSpecializationTypes;
212 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
213 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
214 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
215 mutable llvm::FoldingSet<DependentUnaryTransformType>
216 DependentUnaryTransformTypes;
217 mutable llvm::FoldingSet<AutoType> AutoTypes;
218 mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
219 DeducedTemplateSpecializationTypes;
220 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
221 llvm::FoldingSet<AttributedType> AttributedTypes;
222 mutable llvm::FoldingSet<PipeType> PipeTypes;
224 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
225 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
226 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
227 SubstTemplateTemplateParms;
228 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
230 SubstTemplateTemplateParmPacks;
232 /// The set of nested name specifiers.
234 /// This set is managed by the NestedNameSpecifier class.
235 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
236 mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
238 /// A cache mapping from RecordDecls to ASTRecordLayouts.
240 /// This is lazily created. This is intentionally not serialized.
241 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
243 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
246 /// A cache from types to size and alignment information.
247 using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
248 mutable TypeInfoMap MemoizedTypeInfo;
250 /// A cache from types to unadjusted alignment information. Only ARM and
251 /// AArch64 targets need this information, keeping it separate prevents
252 /// imposing overhead on TypeInfo size.
253 using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>;
254 mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
256 /// A cache mapping from CXXRecordDecls to key functions.
257 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
259 /// Mapping from ObjCContainers to their ObjCImplementations.
260 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
262 /// Mapping from ObjCMethod to its duplicate declaration in the same
264 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
266 /// Mapping from __block VarDecls to BlockVarCopyInit.
267 llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
269 /// Mapping from class scope functions specialization to their
270 /// template patterns.
271 llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
272 ClassScopeSpecializationPattern;
274 /// Mapping from materialized temporaries with static storage duration
275 /// that appear in constant initializers to their evaluated values. These are
276 /// allocated in a std::map because their address must be stable.
277 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue *>
278 MaterializedTemporaryValues;
280 /// Representation of a "canonical" template template parameter that
281 /// is used in canonical template names.
282 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
283 TemplateTemplateParmDecl *Parm;
286 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
289 TemplateTemplateParmDecl *getParam() const { return Parm; }
291 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
293 static void Profile(llvm::FoldingSetNodeID &ID,
294 TemplateTemplateParmDecl *Parm);
296 mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
297 CanonTemplateTemplateParms;
299 TemplateTemplateParmDecl *
300 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
302 /// The typedef for the __int128_t type.
303 mutable TypedefDecl *Int128Decl = nullptr;
305 /// The typedef for the __uint128_t type.
306 mutable TypedefDecl *UInt128Decl = nullptr;
308 /// The typedef for the target specific predefined
309 /// __builtin_va_list type.
310 mutable TypedefDecl *BuiltinVaListDecl = nullptr;
312 /// The typedef for the predefined \c __builtin_ms_va_list type.
313 mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
315 /// The typedef for the predefined \c id type.
316 mutable TypedefDecl *ObjCIdDecl = nullptr;
318 /// The typedef for the predefined \c SEL type.
319 mutable TypedefDecl *ObjCSelDecl = nullptr;
321 /// The typedef for the predefined \c Class type.
322 mutable TypedefDecl *ObjCClassDecl = nullptr;
324 /// The typedef for the predefined \c Protocol class in Objective-C.
325 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
327 /// The typedef for the predefined 'BOOL' type.
328 mutable TypedefDecl *BOOLDecl = nullptr;
330 // Typedefs which may be provided defining the structure of Objective-C
332 QualType ObjCIdRedefinitionType;
333 QualType ObjCClassRedefinitionType;
334 QualType ObjCSelRedefinitionType;
336 /// The identifier 'bool'.
337 mutable IdentifierInfo *BoolName = nullptr;
339 /// The identifier 'NSObject'.
340 mutable IdentifierInfo *NSObjectName = nullptr;
342 /// The identifier 'NSCopying'.
343 IdentifierInfo *NSCopyingName = nullptr;
345 /// The identifier '__make_integer_seq'.
346 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
348 /// The identifier '__type_pack_element'.
349 mutable IdentifierInfo *TypePackElementName = nullptr;
351 QualType ObjCConstantStringType;
352 mutable RecordDecl *CFConstantStringTagDecl = nullptr;
353 mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
355 mutable QualType ObjCSuperType;
357 QualType ObjCNSStringType;
359 /// The typedef declaration for the Objective-C "instancetype" type.
360 TypedefDecl *ObjCInstanceTypeDecl = nullptr;
362 /// The type for the C FILE type.
363 TypeDecl *FILEDecl = nullptr;
365 /// The type for the C jmp_buf type.
366 TypeDecl *jmp_bufDecl = nullptr;
368 /// The type for the C sigjmp_buf type.
369 TypeDecl *sigjmp_bufDecl = nullptr;
371 /// The type for the C ucontext_t type.
372 TypeDecl *ucontext_tDecl = nullptr;
374 /// Type for the Block descriptor for Blocks CodeGen.
376 /// Since this is only used for generation of debug info, it is not
378 mutable RecordDecl *BlockDescriptorType = nullptr;
380 /// Type for the Block descriptor for Blocks CodeGen.
382 /// Since this is only used for generation of debug info, it is not
384 mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
386 /// Declaration for the CUDA cudaConfigureCall function.
387 FunctionDecl *cudaConfigureCallDecl = nullptr;
389 /// Keeps track of all declaration attributes.
391 /// Since so few decls have attrs, we keep them in a hash map instead of
392 /// wasting space in the Decl class.
393 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
395 /// A mapping from non-redeclarable declarations in modules that were
396 /// merged with other declarations to the canonical declaration that they were
398 llvm::DenseMap<Decl*, Decl*> MergedDecls;
400 /// A mapping from a defining declaration to a list of modules (other
401 /// than the owning module of the declaration) that contain merged
402 /// definitions of that entity.
403 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
405 /// Initializers for a module, in order. Each Decl will be either
406 /// something that has a semantic effect on startup (such as a variable with
407 /// a non-constant initializer), or an ImportDecl (which recursively triggers
408 /// initialization of another module).
409 struct PerModuleInitializers {
410 llvm::SmallVector<Decl*, 4> Initializers;
411 llvm::SmallVector<uint32_t, 4> LazyInitializers;
413 void resolve(ASTContext &Ctx);
415 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
417 ASTContext &this_() { return *this; }
420 /// A type synonym for the TemplateOrInstantiation mapping.
421 using TemplateOrSpecializationInfo =
422 llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
425 friend class ASTDeclReader;
426 friend class ASTReader;
427 friend class ASTWriter;
428 friend class CXXRecordDecl;
430 /// A mapping to contain the template or declaration that
431 /// a variable declaration describes or was instantiated from,
434 /// For non-templates, this value will be NULL. For variable
435 /// declarations that describe a variable template, this will be a
436 /// pointer to a VarTemplateDecl. For static data members
437 /// of class template specializations, this will be the
438 /// MemberSpecializationInfo referring to the member variable that was
439 /// instantiated or specialized. Thus, the mapping will keep track of
440 /// the static data member templates from which static data members of
441 /// class template specializations were instantiated.
443 /// Given the following example:
446 /// template<typename T>
451 /// template<typename T>
452 /// T X<T>::value = T(17);
454 /// int *x = &X<int>::value;
457 /// This mapping will contain an entry that maps from the VarDecl for
458 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
459 /// class template X) and will be marked TSK_ImplicitInstantiation.
460 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
461 TemplateOrInstantiation;
463 /// Keeps track of the declaration from which a using declaration was
464 /// created during instantiation.
466 /// The source and target declarations are always a UsingDecl, an
467 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
471 /// template<typename T>
476 /// template<typename T>
477 /// struct B : A<T> {
481 /// template struct B<int>;
484 /// This mapping will contain an entry that maps from the UsingDecl in
485 /// B<int> to the UnresolvedUsingDecl in B<T>.
486 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
488 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
489 InstantiatedFromUsingShadowDecl;
491 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
493 /// Mapping that stores the methods overridden by a given C++
496 /// Since most C++ member functions aren't virtual and therefore
497 /// don't override anything, we store the overridden functions in
498 /// this map on the side rather than within the CXXMethodDecl structure.
499 using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
500 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
502 /// Mapping from each declaration context to its corresponding
503 /// mangling numbering context (used for constructs like lambdas which
504 /// need to be consistently numbered for the mangler).
505 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
506 MangleNumberingContexts;
508 /// Side-table of mangling numbers for declarations which rarely
509 /// need them (like static local vars).
510 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
511 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
513 /// Mapping that stores parameterIndex values for ParmVarDecls when
514 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
515 using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
516 ParameterIndexTable ParamIndices;
518 ImportDecl *FirstLocalImport = nullptr;
519 ImportDecl *LastLocalImport = nullptr;
521 TranslationUnitDecl *TUDecl;
522 mutable ExternCContextDecl *ExternCContext = nullptr;
523 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
524 mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
526 /// The associated SourceManager object.
527 SourceManager &SourceMgr;
529 /// The language options used to create the AST associated with
530 /// this ASTContext object.
531 LangOptions &LangOpts;
533 /// Blacklist object that is used by sanitizers to decide which
534 /// entities should not be instrumented.
535 std::unique_ptr<SanitizerBlacklist> SanitizerBL;
537 /// Function filtering mechanism to determine whether a given function
538 /// should be imbued with the XRay "always" or "never" attributes.
539 std::unique_ptr<XRayFunctionFilter> XRayFilter;
541 /// The allocator used to create AST objects.
543 /// AST objects are never destructed; rather, all memory associated with the
544 /// AST objects will be released when the ASTContext itself is destroyed.
545 mutable llvm::BumpPtrAllocator BumpAlloc;
547 /// Allocator for partial diagnostics.
548 PartialDiagnostic::StorageAllocator DiagAllocator;
550 /// The current C++ ABI.
551 std::unique_ptr<CXXABI> ABI;
552 CXXABI *createCXXABI(const TargetInfo &T);
554 /// The logical -> physical address space map.
555 const LangASMap *AddrSpaceMap = nullptr;
557 /// Address space map mangling must be used with language specific
558 /// address spaces (e.g. OpenCL/CUDA)
559 bool AddrSpaceMapMangling;
561 const TargetInfo *Target = nullptr;
562 const TargetInfo *AuxTarget = nullptr;
563 clang::PrintingPolicy PrintingPolicy;
566 IdentifierTable &Idents;
567 SelectorTable &Selectors;
568 Builtin::Context &BuiltinInfo;
569 mutable DeclarationNameTable DeclarationNames;
570 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
571 ASTMutationListener *Listener = nullptr;
573 /// Container for either a single DynTypedNode or for an ArrayRef to
574 /// DynTypedNode. For use with ParentMap.
575 class DynTypedNodeList {
576 using DynTypedNode = ast_type_traits::DynTypedNode;
578 llvm::AlignedCharArrayUnion<ast_type_traits::DynTypedNode,
579 ArrayRef<DynTypedNode>> Storage;
583 DynTypedNodeList(const DynTypedNode &N) : IsSingleNode(true) {
584 new (Storage.buffer) DynTypedNode(N);
587 DynTypedNodeList(ArrayRef<DynTypedNode> A) : IsSingleNode(false) {
588 new (Storage.buffer) ArrayRef<DynTypedNode>(A);
591 const ast_type_traits::DynTypedNode *begin() const {
593 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
595 return reinterpret_cast<const DynTypedNode *>(Storage.buffer);
598 const ast_type_traits::DynTypedNode *end() const {
600 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
602 return reinterpret_cast<const DynTypedNode *>(Storage.buffer) + 1;
605 size_t size() const { return end() - begin(); }
606 bool empty() const { return begin() == end(); }
608 const DynTypedNode &operator[](size_t N) const {
609 assert(N < size() && "Out of bounds!");
610 return *(begin() + N);
614 // A traversal scope limits the parts of the AST visible to certain analyses.
615 // RecursiveASTVisitor::TraverseAST will only visit reachable nodes, and
616 // getParents() will only observe reachable parent edges.
618 // The scope is defined by a set of "top-level" declarations.
619 // Initially, it is the entire TU: {getTranslationUnitDecl()}.
620 // Changing the scope clears the parent cache, which is expensive to rebuild.
621 std::vector<Decl *> getTraversalScope() const { return TraversalScope; }
622 void setTraversalScope(const std::vector<Decl *> &);
624 /// Returns the parents of the given node (within the traversal scope).
626 /// Note that this will lazily compute the parents of all nodes
627 /// and store them for later retrieval. Thus, the first call is O(n)
628 /// in the number of AST nodes.
630 /// Caveats and FIXMEs:
631 /// Calculating the parent map over all AST nodes will need to load the
632 /// full AST. This can be undesirable in the case where the full AST is
633 /// expensive to create (for example, when using precompiled header
634 /// preambles). Thus, there are good opportunities for optimization here.
635 /// One idea is to walk the given node downwards, looking for references
636 /// to declaration contexts - once a declaration context is found, compute
637 /// the parent map for the declaration context; if that can satisfy the
638 /// request, loading the whole AST can be avoided. Note that this is made
639 /// more complex by statements in templates having multiple parents - those
640 /// problems can be solved by building closure over the templated parts of
641 /// the AST, which also avoids touching large parts of the AST.
642 /// Additionally, we will want to add an interface to already give a hint
643 /// where to search for the parents, for example when looking at a statement
644 /// inside a certain function.
646 /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
647 /// NestedNameSpecifier or NestedNameSpecifierLoc.
648 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node) {
649 return getParents(ast_type_traits::DynTypedNode::create(Node));
652 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node);
654 const clang::PrintingPolicy &getPrintingPolicy() const {
655 return PrintingPolicy;
658 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
659 PrintingPolicy = Policy;
662 SourceManager& getSourceManager() { return SourceMgr; }
663 const SourceManager& getSourceManager() const { return SourceMgr; }
665 llvm::BumpPtrAllocator &getAllocator() const {
669 void *Allocate(size_t Size, unsigned Align = 8) const {
670 return BumpAlloc.Allocate(Size, Align);
672 template <typename T> T *Allocate(size_t Num = 1) const {
673 return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
675 void Deallocate(void *Ptr) const {}
677 /// Return the total amount of physical memory allocated for representing
678 /// AST nodes and type information.
679 size_t getASTAllocatedMemory() const {
680 return BumpAlloc.getTotalMemory();
683 /// Return the total memory used for various side tables.
684 size_t getSideTableAllocatedMemory() const;
686 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
687 return DiagAllocator;
690 const TargetInfo &getTargetInfo() const { return *Target; }
691 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
693 /// getIntTypeForBitwidth -
694 /// sets integer QualTy according to specified details:
695 /// bitwidth, signed/unsigned.
696 /// Returns empty type if there is no appropriate target types.
697 QualType getIntTypeForBitwidth(unsigned DestWidth,
698 unsigned Signed) const;
700 /// getRealTypeForBitwidth -
701 /// sets floating point QualTy according to specified bitwidth.
702 /// Returns empty type if there is no appropriate target types.
703 QualType getRealTypeForBitwidth(unsigned DestWidth) const;
705 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
707 const LangOptions& getLangOpts() const { return LangOpts; }
709 const SanitizerBlacklist &getSanitizerBlacklist() const {
713 const XRayFunctionFilter &getXRayFilter() const {
717 DiagnosticsEngine &getDiagnostics() const;
719 FullSourceLoc getFullLoc(SourceLocation Loc) const {
720 return FullSourceLoc(Loc,SourceMgr);
723 /// All comments in this translation unit.
724 RawCommentList Comments;
726 /// True if comments are already loaded from ExternalASTSource.
727 mutable bool CommentsLoaded = false;
729 class RawCommentAndCacheFlags {
732 /// We searched for a comment attached to the particular declaration, but
738 /// We have found a comment attached to this particular declaration.
743 /// This declaration does not have an attached comment, and we have
744 /// searched the redeclaration chain.
746 /// If getRaw() == 0, the whole redeclaration chain does not have any
749 /// If getRaw() != 0, it is a comment propagated from other
754 Kind getKind() const LLVM_READONLY {
755 return Data.getInt();
758 void setKind(Kind K) {
762 const RawComment *getRaw() const LLVM_READONLY {
763 return Data.getPointer();
766 void setRaw(const RawComment *RC) {
770 const Decl *getOriginalDecl() const LLVM_READONLY {
774 void setOriginalDecl(const Decl *Orig) {
779 llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
780 const Decl *OriginalDecl;
783 /// Mapping from declarations to comments attached to any
786 /// Raw comments are owned by Comments list. This mapping is populated
788 mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
790 /// Mapping from declarations to parsed comments attached to any
792 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
794 /// Return the documentation comment attached to a given declaration,
795 /// without looking into cache.
796 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
799 RawCommentList &getRawCommentList() {
803 void addComment(const RawComment &RC) {
804 assert(LangOpts.RetainCommentsFromSystemHeaders ||
805 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
806 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
809 /// Return the documentation comment attached to a given declaration.
810 /// Returns nullptr if no comment is attached.
812 /// \param OriginalDecl if not nullptr, is set to declaration AST node that
813 /// had the comment, if the comment we found comes from a redeclaration.
815 getRawCommentForAnyRedecl(const Decl *D,
816 const Decl **OriginalDecl = nullptr) const;
818 /// Return parsed documentation comment attached to a given declaration.
819 /// Returns nullptr if no comment is attached.
821 /// \param PP the Preprocessor used with this TU. Could be nullptr if
822 /// preprocessor is not available.
823 comments::FullComment *getCommentForDecl(const Decl *D,
824 const Preprocessor *PP) const;
826 /// Return parsed documentation comment attached to a given declaration.
827 /// Returns nullptr if no comment is attached. Does not look at any
828 /// redeclarations of the declaration.
829 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
831 comments::FullComment *cloneFullComment(comments::FullComment *FC,
832 const Decl *D) const;
835 mutable comments::CommandTraits CommentCommandTraits;
837 /// Iterator that visits import declarations.
838 class import_iterator {
839 ImportDecl *Import = nullptr;
842 using value_type = ImportDecl *;
843 using reference = ImportDecl *;
844 using pointer = ImportDecl *;
845 using difference_type = int;
846 using iterator_category = std::forward_iterator_tag;
848 import_iterator() = default;
849 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
851 reference operator*() const { return Import; }
852 pointer operator->() const { return Import; }
854 import_iterator &operator++() {
855 Import = ASTContext::getNextLocalImport(Import);
859 import_iterator operator++(int) {
860 import_iterator Other(*this);
865 friend bool operator==(import_iterator X, import_iterator Y) {
866 return X.Import == Y.Import;
869 friend bool operator!=(import_iterator X, import_iterator Y) {
870 return X.Import != Y.Import;
875 comments::CommandTraits &getCommentCommandTraits() const {
876 return CommentCommandTraits;
879 /// Retrieve the attributes for the given declaration.
880 AttrVec& getDeclAttrs(const Decl *D);
882 /// Erase the attributes corresponding to the given declaration.
883 void eraseDeclAttrs(const Decl *D);
885 /// If this variable is an instantiated static data member of a
886 /// class template specialization, returns the templated static data member
887 /// from which it was instantiated.
889 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
892 TemplateOrSpecializationInfo
893 getTemplateOrSpecializationInfo(const VarDecl *Var);
895 FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
897 void setClassScopeSpecializationPattern(FunctionDecl *FD,
898 FunctionDecl *Pattern);
900 /// Note that the static data member \p Inst is an instantiation of
901 /// the static data member template \p Tmpl of a class template.
902 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
903 TemplateSpecializationKind TSK,
904 SourceLocation PointOfInstantiation = SourceLocation());
906 void setTemplateOrSpecializationInfo(VarDecl *Inst,
907 TemplateOrSpecializationInfo TSI);
909 /// If the given using decl \p Inst is an instantiation of a
910 /// (possibly unresolved) using decl from a template instantiation,
912 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
914 /// Remember that the using decl \p Inst is an instantiation
915 /// of the using decl \p Pattern of a class template.
916 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
918 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
919 UsingShadowDecl *Pattern);
920 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
922 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
924 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
926 // Access to the set of methods overridden by the given C++ method.
927 using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
928 overridden_cxx_method_iterator
929 overridden_methods_begin(const CXXMethodDecl *Method) const;
931 overridden_cxx_method_iterator
932 overridden_methods_end(const CXXMethodDecl *Method) const;
934 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
936 using overridden_method_range =
937 llvm::iterator_range<overridden_cxx_method_iterator>;
939 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
941 /// Note that the given C++ \p Method overrides the given \p
942 /// Overridden method.
943 void addOverriddenMethod(const CXXMethodDecl *Method,
944 const CXXMethodDecl *Overridden);
946 /// Return C++ or ObjC overridden methods for the given \p Method.
948 /// An ObjC method is considered to override any method in the class's
949 /// base classes, its protocols, or its categories' protocols, that has
950 /// the same selector and is of the same kind (class or instance).
951 /// A method in an implementation is not considered as overriding the same
952 /// method in the interface or its categories.
953 void getOverriddenMethods(
954 const NamedDecl *Method,
955 SmallVectorImpl<const NamedDecl *> &Overridden) const;
957 /// Notify the AST context that a new import declaration has been
958 /// parsed or implicitly created within this translation unit.
959 void addedLocalImportDecl(ImportDecl *Import);
961 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
962 return Import->NextLocalImport;
965 using import_range = llvm::iterator_range<import_iterator>;
967 import_range local_imports() const {
968 return import_range(import_iterator(FirstLocalImport), import_iterator());
971 Decl *getPrimaryMergedDecl(Decl *D) {
972 Decl *Result = MergedDecls.lookup(D);
973 return Result ? Result : D;
975 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
976 MergedDecls[D] = Primary;
979 /// Note that the definition \p ND has been merged into module \p M,
980 /// and should be visible whenever \p M is visible.
981 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
982 bool NotifyListeners = true);
984 /// Clean up the merged definition list. Call this if you might have
985 /// added duplicates into the list.
986 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
988 /// Get the additional modules in which the definition \p Def has
990 ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def) {
992 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
993 if (MergedIt == MergedDefModules.end())
995 return MergedIt->second;
998 /// Add a declaration to the list of declarations that are initialized
999 /// for a module. This will typically be a global variable (with internal
1000 /// linkage) that runs module initializers, such as the iostream initializer,
1001 /// or an ImportDecl nominating another module that has initializers.
1002 void addModuleInitializer(Module *M, Decl *Init);
1004 void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs);
1006 /// Get the initializations to perform when importing a module, if any.
1007 ArrayRef<Decl*> getModuleInitializers(Module *M);
1009 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
1011 ExternCContextDecl *getExternCContextDecl() const;
1012 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
1013 BuiltinTemplateDecl *getTypePackElementDecl() const;
1019 CanQualType WCharTy; // [C++ 3.9.1p5].
1020 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
1021 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
1022 CanQualType Char8Ty; // [C++20 proposal]
1023 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
1024 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
1025 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
1026 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
1027 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
1028 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty;
1029 CanQualType ShortAccumTy, AccumTy,
1030 LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1031 CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
1032 CanQualType ShortFractTy, FractTy, LongFractTy;
1033 CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
1034 CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy;
1035 CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy,
1036 SatUnsignedLongAccumTy;
1037 CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
1038 CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
1039 SatUnsignedLongFractTy;
1040 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
1041 CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
1042 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
1043 CanQualType Float128ComplexTy;
1044 CanQualType VoidPtrTy, NullPtrTy;
1045 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
1046 CanQualType BuiltinFnTy;
1047 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
1048 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
1049 CanQualType ObjCBuiltinBoolTy;
1050 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1051 CanQualType SingletonId;
1052 #include "clang/Basic/OpenCLImageTypes.def"
1053 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
1054 CanQualType OCLQueueTy, OCLReserveIDTy;
1055 CanQualType OMPArraySectionTy;
1056 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1058 #include "clang/Basic/OpenCLExtensionTypes.def"
1060 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
1061 mutable QualType AutoDeductTy; // Deduction against 'auto'.
1062 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
1064 // Decl used to help define __builtin_va_list for some targets.
1065 // The decl is built when constructing 'BuiltinVaListDecl'.
1066 mutable Decl *VaListTagDecl;
1068 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1069 SelectorTable &sels, Builtin::Context &builtins);
1070 ASTContext(const ASTContext &) = delete;
1071 ASTContext &operator=(const ASTContext &) = delete;
1074 /// Attach an external AST source to the AST context.
1076 /// The external AST source provides the ability to load parts of
1077 /// the abstract syntax tree as needed from some external storage,
1078 /// e.g., a precompiled header.
1079 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1081 /// Retrieve a pointer to the external AST source associated
1082 /// with this AST context, if any.
1083 ExternalASTSource *getExternalSource() const {
1084 return ExternalSource.get();
1087 /// Attach an AST mutation listener to the AST context.
1089 /// The AST mutation listener provides the ability to track modifications to
1090 /// the abstract syntax tree entities committed after they were initially
1092 void setASTMutationListener(ASTMutationListener *Listener) {
1093 this->Listener = Listener;
1096 /// Retrieve a pointer to the AST mutation listener associated
1097 /// with this AST context, if any.
1098 ASTMutationListener *getASTMutationListener() const { return Listener; }
1100 void PrintStats() const;
1101 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1103 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1104 const IdentifierInfo *II) const;
1106 /// Create a new implicit TU-level CXXRecordDecl or RecordDecl
1108 RecordDecl *buildImplicitRecord(StringRef Name,
1109 RecordDecl::TagKind TK = TTK_Struct) const;
1111 /// Create a new implicit TU-level typedef declaration.
1112 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1114 /// Retrieve the declaration for the 128-bit signed integer type.
1115 TypedefDecl *getInt128Decl() const;
1117 /// Retrieve the declaration for the 128-bit unsigned integer type.
1118 TypedefDecl *getUInt128Decl() const;
1120 //===--------------------------------------------------------------------===//
1121 // Type Constructors
1122 //===--------------------------------------------------------------------===//
1125 /// Return a type with extended qualifiers.
1126 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1128 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1130 QualType getPipeType(QualType T, bool ReadOnly) const;
1133 /// Return the uniqued reference to the type for an address space
1134 /// qualified type with the specified type and address space.
1136 /// The resulting type has a union of the qualifiers from T and the address
1137 /// space. If T already has an address space specifier, it is silently
1139 QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
1141 /// Remove any existing address space on the type and returns the type
1142 /// with qualifiers intact (or that's the idea anyway)
1144 /// The return type should be T with all prior qualifiers minus the address
1146 QualType removeAddrSpaceQualType(QualType T) const;
1148 /// Apply Objective-C protocol qualifiers to the given type.
1149 /// \param allowOnPointerType specifies if we can apply protocol
1150 /// qualifiers on ObjCObjectPointerType. It can be set to true when
1151 /// constructing the canonical type of a Objective-C type parameter.
1152 QualType applyObjCProtocolQualifiers(QualType type,
1153 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1154 bool allowOnPointerType = false) const;
1156 /// Return the uniqued reference to the type for an Objective-C
1157 /// gc-qualified type.
1159 /// The resulting type has a union of the qualifiers from T and the gc
1161 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1163 /// Return the uniqued reference to the type for a \c restrict
1166 /// The resulting type has a union of the qualifiers from \p T and
1168 QualType getRestrictType(QualType T) const {
1169 return T.withFastQualifiers(Qualifiers::Restrict);
1172 /// Return the uniqued reference to the type for a \c volatile
1175 /// The resulting type has a union of the qualifiers from \p T and
1177 QualType getVolatileType(QualType T) const {
1178 return T.withFastQualifiers(Qualifiers::Volatile);
1181 /// Return the uniqued reference to the type for a \c const
1184 /// The resulting type has a union of the qualifiers from \p T and \c const.
1186 /// It can be reasonably expected that this will always be equivalent to
1187 /// calling T.withConst().
1188 QualType getConstType(QualType T) const { return T.withConst(); }
1190 /// Change the ExtInfo on a function type.
1191 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1192 FunctionType::ExtInfo EInfo);
1194 /// Adjust the given function result type.
1195 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1197 /// Change the result type of a function type once it is deduced.
1198 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1200 /// Get a function type and produce the equivalent function type with the
1201 /// specified exception specification. Type sugar that can be present on a
1202 /// declaration of a function with an exception specification is permitted
1203 /// and preserved. Other type sugar (for instance, typedefs) is not.
1204 QualType getFunctionTypeWithExceptionSpec(
1205 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI);
1207 /// Determine whether two function types are the same, ignoring
1208 /// exception specifications in cases where they're part of the type.
1209 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U);
1211 /// Change the exception specification on a function once it is
1212 /// delay-parsed, instantiated, or computed.
1213 void adjustExceptionSpec(FunctionDecl *FD,
1214 const FunctionProtoType::ExceptionSpecInfo &ESI,
1215 bool AsWritten = false);
1217 /// Return the uniqued reference to the type for a complex
1218 /// number with the specified element type.
1219 QualType getComplexType(QualType T) const;
1220 CanQualType getComplexType(CanQualType T) const {
1221 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1224 /// Return the uniqued reference to the type for a pointer to
1225 /// the specified type.
1226 QualType getPointerType(QualType T) const;
1227 CanQualType getPointerType(CanQualType T) const {
1228 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1231 /// Return the uniqued reference to a type adjusted from the original
1232 /// type to a new type.
1233 QualType getAdjustedType(QualType Orig, QualType New) const;
1234 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1235 return CanQualType::CreateUnsafe(
1236 getAdjustedType((QualType)Orig, (QualType)New));
1239 /// Return the uniqued reference to the decayed version of the given
1240 /// type. Can only be called on array and function types which decay to
1242 QualType getDecayedType(QualType T) const;
1243 CanQualType getDecayedType(CanQualType T) const {
1244 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1247 /// Return the uniqued reference to the atomic type for the specified
1249 QualType getAtomicType(QualType T) const;
1251 /// Return the uniqued reference to the type for a block of the
1253 QualType getBlockPointerType(QualType T) const;
1255 /// Gets the struct used to keep track of the descriptor for pointer to
1257 QualType getBlockDescriptorType() const;
1259 /// Return a read_only pipe type for the specified type.
1260 QualType getReadPipeType(QualType T) const;
1262 /// Return a write_only pipe type for the specified type.
1263 QualType getWritePipeType(QualType T) const;
1265 /// Gets the struct used to keep track of the extended descriptor for
1266 /// pointer to blocks.
1267 QualType getBlockDescriptorExtendedType() const;
1269 /// Map an AST Type to an OpenCLTypeKind enum value.
1270 TargetInfo::OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
1272 /// Get address space for OpenCL type.
1273 LangAS getOpenCLTypeAddrSpace(const Type *T) const;
1275 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1276 cudaConfigureCallDecl = FD;
1279 FunctionDecl *getcudaConfigureCallDecl() {
1280 return cudaConfigureCallDecl;
1283 /// Returns true iff we need copy/dispose helpers for the given type.
1284 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1286 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
1287 /// is set to false in this case. If HasByrefExtendedLayout returns true,
1288 /// byref variable has extended lifetime.
1289 bool getByrefLifetime(QualType Ty,
1290 Qualifiers::ObjCLifetime &Lifetime,
1291 bool &HasByrefExtendedLayout) const;
1293 /// Return the uniqued reference to the type for an lvalue reference
1294 /// to the specified type.
1295 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1298 /// Return the uniqued reference to the type for an rvalue reference
1299 /// to the specified type.
1300 QualType getRValueReferenceType(QualType T) const;
1302 /// Return the uniqued reference to the type for a member pointer to
1303 /// the specified type in the specified class.
1305 /// The class \p Cls is a \c Type because it could be a dependent name.
1306 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1308 /// Return a non-unique reference to the type for a variable array of
1309 /// the specified element type.
1310 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1311 ArrayType::ArraySizeModifier ASM,
1312 unsigned IndexTypeQuals,
1313 SourceRange Brackets) const;
1315 /// Return a non-unique reference to the type for a dependently-sized
1316 /// array of the specified element type.
1318 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1320 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1321 ArrayType::ArraySizeModifier ASM,
1322 unsigned IndexTypeQuals,
1323 SourceRange Brackets) const;
1325 /// Return a unique reference to the type for an incomplete array of
1326 /// the specified element type.
1327 QualType getIncompleteArrayType(QualType EltTy,
1328 ArrayType::ArraySizeModifier ASM,
1329 unsigned IndexTypeQuals) const;
1331 /// Return the unique reference to the type for a constant array of
1332 /// the specified element type.
1333 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1334 ArrayType::ArraySizeModifier ASM,
1335 unsigned IndexTypeQuals) const;
1337 /// Returns a vla type where known sizes are replaced with [*].
1338 QualType getVariableArrayDecayedType(QualType Ty) const;
1340 /// Return the unique reference to a vector type of the specified
1341 /// element type and size.
1343 /// \pre \p VectorType must be a built-in type.
1344 QualType getVectorType(QualType VectorType, unsigned NumElts,
1345 VectorType::VectorKind VecKind) const;
1346 /// Return the unique reference to the type for a dependently sized vector of
1347 /// the specified element type.
1348 QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr,
1349 SourceLocation AttrLoc,
1350 VectorType::VectorKind VecKind) const;
1352 /// Return the unique reference to an extended vector type
1353 /// of the specified element type and size.
1355 /// \pre \p VectorType must be a built-in type.
1356 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1358 /// \pre Return a non-unique reference to the type for a dependently-sized
1359 /// vector of the specified element type.
1361 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1363 QualType getDependentSizedExtVectorType(QualType VectorType,
1365 SourceLocation AttrLoc) const;
1367 QualType getDependentAddressSpaceType(QualType PointeeType,
1368 Expr *AddrSpaceExpr,
1369 SourceLocation AttrLoc) const;
1371 /// Return a K&R style C function type like 'int()'.
1372 QualType getFunctionNoProtoType(QualType ResultTy,
1373 const FunctionType::ExtInfo &Info) const;
1375 QualType getFunctionNoProtoType(QualType ResultTy) const {
1376 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1379 /// Return a normal function type with a typed argument list.
1380 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1381 const FunctionProtoType::ExtProtoInfo &EPI) const {
1382 return getFunctionTypeInternal(ResultTy, Args, EPI, false);
1385 QualType adjustStringLiteralBaseType(QualType StrLTy) const;
1388 /// Return a normal function type with a typed argument list.
1389 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1390 const FunctionProtoType::ExtProtoInfo &EPI,
1391 bool OnlyWantCanonical) const;
1394 /// Return the unique reference to the type for the specified type
1396 QualType getTypeDeclType(const TypeDecl *Decl,
1397 const TypeDecl *PrevDecl = nullptr) const {
1398 assert(Decl && "Passed null for Decl param");
1399 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1402 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1403 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1404 return QualType(PrevDecl->TypeForDecl, 0);
1407 return getTypeDeclTypeSlow(Decl);
1410 /// Return the unique reference to the type for the specified
1411 /// typedef-name decl.
1412 QualType getTypedefType(const TypedefNameDecl *Decl,
1413 QualType Canon = QualType()) const;
1415 QualType getRecordType(const RecordDecl *Decl) const;
1417 QualType getEnumType(const EnumDecl *Decl) const;
1419 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1421 QualType getAttributedType(attr::Kind attrKind,
1422 QualType modifiedType,
1423 QualType equivalentType);
1425 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1426 QualType Replacement) const;
1427 QualType getSubstTemplateTypeParmPackType(
1428 const TemplateTypeParmType *Replaced,
1429 const TemplateArgument &ArgPack);
1432 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1434 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1436 QualType getTemplateSpecializationType(TemplateName T,
1437 ArrayRef<TemplateArgument> Args,
1438 QualType Canon = QualType()) const;
1441 getCanonicalTemplateSpecializationType(TemplateName T,
1442 ArrayRef<TemplateArgument> Args) const;
1444 QualType getTemplateSpecializationType(TemplateName T,
1445 const TemplateArgumentListInfo &Args,
1446 QualType Canon = QualType()) const;
1449 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1450 const TemplateArgumentListInfo &Args,
1451 QualType Canon = QualType()) const;
1453 QualType getParenType(QualType NamedType) const;
1455 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1456 NestedNameSpecifier *NNS, QualType NamedType,
1457 TagDecl *OwnedTagDecl = nullptr) const;
1458 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1459 NestedNameSpecifier *NNS,
1460 const IdentifierInfo *Name,
1461 QualType Canon = QualType()) const;
1463 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1464 NestedNameSpecifier *NNS,
1465 const IdentifierInfo *Name,
1466 const TemplateArgumentListInfo &Args) const;
1467 QualType getDependentTemplateSpecializationType(
1468 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1469 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1471 TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
1473 /// Get a template argument list with one argument per template parameter
1474 /// in a template parameter list, such as for the injected class name of
1475 /// a class template.
1476 void getInjectedTemplateArgs(const TemplateParameterList *Params,
1477 SmallVectorImpl<TemplateArgument> &Args);
1479 QualType getPackExpansionType(QualType Pattern,
1480 Optional<unsigned> NumExpansions);
1482 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1483 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1485 /// Legacy interface: cannot provide type arguments or __kindof.
1486 QualType getObjCObjectType(QualType Base,
1487 ObjCProtocolDecl * const *Protocols,
1488 unsigned NumProtocols) const;
1490 QualType getObjCObjectType(QualType Base,
1491 ArrayRef<QualType> typeArgs,
1492 ArrayRef<ObjCProtocolDecl *> protocols,
1493 bool isKindOf) const;
1495 QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1496 ArrayRef<ObjCProtocolDecl *> protocols,
1497 QualType Canonical = QualType()) const;
1499 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1501 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1502 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1504 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1505 ObjCInterfaceDecl *IDecl);
1507 /// Return a ObjCObjectPointerType type for the given ObjCObjectType.
1508 QualType getObjCObjectPointerType(QualType OIT) const;
1511 QualType getTypeOfExprType(Expr *e) const;
1512 QualType getTypeOfType(QualType t) const;
1515 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1517 /// Unary type transforms
1518 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1519 UnaryTransformType::UTTKind UKind) const;
1521 /// C++11 deduced auto type.
1522 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1523 bool IsDependent) const;
1525 /// C++11 deduction pattern for 'auto' type.
1526 QualType getAutoDeductType() const;
1528 /// C++11 deduction pattern for 'auto &&' type.
1529 QualType getAutoRRefDeductType() const;
1531 /// C++17 deduced class template specialization type.
1532 QualType getDeducedTemplateSpecializationType(TemplateName Template,
1533 QualType DeducedType,
1534 bool IsDependent) const;
1536 /// Return the unique reference to the type for the specified TagDecl
1537 /// (struct/union/class/enum) decl.
1538 QualType getTagDeclType(const TagDecl *Decl) const;
1540 /// Return the unique type for "size_t" (C99 7.17), defined in
1543 /// The sizeof operator requires this (C99 6.5.3.4p4).
1544 CanQualType getSizeType() const;
1546 /// Return the unique signed counterpart of
1547 /// the integer type corresponding to size_t.
1548 CanQualType getSignedSizeType() const;
1550 /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1552 CanQualType getIntMaxType() const;
1554 /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1556 CanQualType getUIntMaxType() const;
1558 /// Return the unique wchar_t type available in C++ (and available as
1559 /// __wchar_t as a Microsoft extension).
1560 QualType getWCharType() const { return WCharTy; }
1562 /// Return the type of wide characters. In C++, this returns the
1563 /// unique wchar_t type. In C99, this returns a type compatible with the type
1564 /// defined in <stddef.h> as defined by the target.
1565 QualType getWideCharType() const { return WideCharTy; }
1567 /// Return the type of "signed wchar_t".
1569 /// Used when in C++, as a GCC extension.
1570 QualType getSignedWCharType() const;
1572 /// Return the type of "unsigned wchar_t".
1574 /// Used when in C++, as a GCC extension.
1575 QualType getUnsignedWCharType() const;
1577 /// In C99, this returns a type compatible with the type
1578 /// defined in <stddef.h> as defined by the target.
1579 QualType getWIntType() const { return WIntTy; }
1581 /// Return a type compatible with "intptr_t" (C99 7.18.1.4),
1582 /// as defined by the target.
1583 QualType getIntPtrType() const;
1585 /// Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1586 /// as defined by the target.
1587 QualType getUIntPtrType() const;
1589 /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1590 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1591 QualType getPointerDiffType() const;
1593 /// Return the unique unsigned counterpart of "ptrdiff_t"
1594 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
1595 /// in the definition of %tu format specifier.
1596 QualType getUnsignedPointerDiffType() const;
1598 /// Return the unique type for "pid_t" defined in
1599 /// <sys/types.h>. We need this to compute the correct type for vfork().
1600 QualType getProcessIDType() const;
1602 /// Return the C structure type used to represent constant CFStrings.
1603 QualType getCFConstantStringType() const;
1605 /// Returns the C struct type for objc_super
1606 QualType getObjCSuperType() const;
1607 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1609 /// Get the structure type used to representation CFStrings, or NULL
1610 /// if it hasn't yet been built.
1611 QualType getRawCFConstantStringType() const {
1612 if (CFConstantStringTypeDecl)
1613 return getTypedefType(CFConstantStringTypeDecl);
1616 void setCFConstantStringType(QualType T);
1617 TypedefDecl *getCFConstantStringDecl() const;
1618 RecordDecl *getCFConstantStringTagDecl() const;
1620 // This setter/getter represents the ObjC type for an NSConstantString.
1621 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1622 QualType getObjCConstantStringInterface() const {
1623 return ObjCConstantStringType;
1626 QualType getObjCNSStringType() const {
1627 return ObjCNSStringType;
1630 void setObjCNSStringType(QualType T) {
1631 ObjCNSStringType = T;
1634 /// Retrieve the type that \c id has been defined to, which may be
1635 /// different from the built-in \c id if \c id has been typedef'd.
1636 QualType getObjCIdRedefinitionType() const {
1637 if (ObjCIdRedefinitionType.isNull())
1638 return getObjCIdType();
1639 return ObjCIdRedefinitionType;
1642 /// Set the user-written type that redefines \c id.
1643 void setObjCIdRedefinitionType(QualType RedefType) {
1644 ObjCIdRedefinitionType = RedefType;
1647 /// Retrieve the type that \c Class has been defined to, which may be
1648 /// different from the built-in \c Class if \c Class has been typedef'd.
1649 QualType getObjCClassRedefinitionType() const {
1650 if (ObjCClassRedefinitionType.isNull())
1651 return getObjCClassType();
1652 return ObjCClassRedefinitionType;
1655 /// Set the user-written type that redefines 'SEL'.
1656 void setObjCClassRedefinitionType(QualType RedefType) {
1657 ObjCClassRedefinitionType = RedefType;
1660 /// Retrieve the type that 'SEL' has been defined to, which may be
1661 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1662 QualType getObjCSelRedefinitionType() const {
1663 if (ObjCSelRedefinitionType.isNull())
1664 return getObjCSelType();
1665 return ObjCSelRedefinitionType;
1668 /// Set the user-written type that redefines 'SEL'.
1669 void setObjCSelRedefinitionType(QualType RedefType) {
1670 ObjCSelRedefinitionType = RedefType;
1673 /// Retrieve the identifier 'NSObject'.
1674 IdentifierInfo *getNSObjectName() const {
1675 if (!NSObjectName) {
1676 NSObjectName = &Idents.get("NSObject");
1679 return NSObjectName;
1682 /// Retrieve the identifier 'NSCopying'.
1683 IdentifierInfo *getNSCopyingName() {
1684 if (!NSCopyingName) {
1685 NSCopyingName = &Idents.get("NSCopying");
1688 return NSCopyingName;
1691 CanQualType getNSUIntegerType() const {
1692 assert(Target && "Expected target to be initialized");
1693 const llvm::Triple &T = Target->getTriple();
1694 // Windows is LLP64 rather than LP64
1695 if (T.isOSWindows() && T.isArch64Bit())
1696 return UnsignedLongLongTy;
1697 return UnsignedLongTy;
1700 CanQualType getNSIntegerType() const {
1701 assert(Target && "Expected target to be initialized");
1702 const llvm::Triple &T = Target->getTriple();
1703 // Windows is LLP64 rather than LP64
1704 if (T.isOSWindows() && T.isArch64Bit())
1709 /// Retrieve the identifier 'bool'.
1710 IdentifierInfo *getBoolName() const {
1712 BoolName = &Idents.get("bool");
1716 IdentifierInfo *getMakeIntegerSeqName() const {
1717 if (!MakeIntegerSeqName)
1718 MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1719 return MakeIntegerSeqName;
1722 IdentifierInfo *getTypePackElementName() const {
1723 if (!TypePackElementName)
1724 TypePackElementName = &Idents.get("__type_pack_element");
1725 return TypePackElementName;
1728 /// Retrieve the Objective-C "instancetype" type, if already known;
1729 /// otherwise, returns a NULL type;
1730 QualType getObjCInstanceType() {
1731 return getTypeDeclType(getObjCInstanceTypeDecl());
1734 /// Retrieve the typedef declaration corresponding to the Objective-C
1735 /// "instancetype" type.
1736 TypedefDecl *getObjCInstanceTypeDecl();
1738 /// Set the type for the C FILE type.
1739 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1741 /// Retrieve the C FILE type.
1742 QualType getFILEType() const {
1744 return getTypeDeclType(FILEDecl);
1748 /// Set the type for the C jmp_buf type.
1749 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1750 this->jmp_bufDecl = jmp_bufDecl;
1753 /// Retrieve the C jmp_buf type.
1754 QualType getjmp_bufType() const {
1756 return getTypeDeclType(jmp_bufDecl);
1760 /// Set the type for the C sigjmp_buf type.
1761 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1762 this->sigjmp_bufDecl = sigjmp_bufDecl;
1765 /// Retrieve the C sigjmp_buf type.
1766 QualType getsigjmp_bufType() const {
1768 return getTypeDeclType(sigjmp_bufDecl);
1772 /// Set the type for the C ucontext_t type.
1773 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1774 this->ucontext_tDecl = ucontext_tDecl;
1777 /// Retrieve the C ucontext_t type.
1778 QualType getucontext_tType() const {
1780 return getTypeDeclType(ucontext_tDecl);
1784 /// The result type of logical operations, '<', '>', '!=', etc.
1785 QualType getLogicalOperationType() const {
1786 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1789 /// Emit the Objective-CC type encoding for the given type \p T into
1792 /// If \p Field is specified then record field names are also encoded.
1793 void getObjCEncodingForType(QualType T, std::string &S,
1794 const FieldDecl *Field=nullptr,
1795 QualType *NotEncodedT=nullptr) const;
1797 /// Emit the Objective-C property type encoding for the given
1798 /// type \p T into \p S.
1799 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1801 void getLegacyIntegralTypeEncoding(QualType &t) const;
1803 /// Put the string version of the type qualifiers \p QT into \p S.
1804 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1805 std::string &S) const;
1807 /// Emit the encoded type for the function \p Decl into \p S.
1809 /// This is in the same format as Objective-C method encodings.
1811 /// \returns true if an error occurred (e.g., because one of the parameter
1812 /// types is incomplete), false otherwise.
1813 std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
1815 /// Emit the encoded type for the method declaration \p Decl into
1817 std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1818 bool Extended = false) const;
1820 /// Return the encoded type for this block declaration.
1821 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1823 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1824 /// this method declaration. If non-NULL, Container must be either
1825 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1826 /// only be NULL when getting encodings for protocol properties.
1827 std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1828 const Decl *Container) const;
1830 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1831 ObjCProtocolDecl *rProto) const;
1833 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1834 const ObjCPropertyDecl *PD,
1835 const Decl *Container) const;
1837 /// Return the size of type \p T for Objective-C encoding purpose,
1839 CharUnits getObjCEncodingTypeSize(QualType T) const;
1841 /// Retrieve the typedef corresponding to the predefined \c id type
1843 TypedefDecl *getObjCIdDecl() const;
1845 /// Represents the Objective-CC \c id type.
1847 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1848 /// pointer type, a pointer to a struct.
1849 QualType getObjCIdType() const {
1850 return getTypeDeclType(getObjCIdDecl());
1853 /// Retrieve the typedef corresponding to the predefined 'SEL' type
1855 TypedefDecl *getObjCSelDecl() const;
1857 /// Retrieve the type that corresponds to the predefined Objective-C
1859 QualType getObjCSelType() const {
1860 return getTypeDeclType(getObjCSelDecl());
1863 /// Retrieve the typedef declaration corresponding to the predefined
1864 /// Objective-C 'Class' type.
1865 TypedefDecl *getObjCClassDecl() const;
1867 /// Represents the Objective-C \c Class type.
1869 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1870 /// pointer type, a pointer to a struct.
1871 QualType getObjCClassType() const {
1872 return getTypeDeclType(getObjCClassDecl());
1875 /// Retrieve the Objective-C class declaration corresponding to
1876 /// the predefined \c Protocol class.
1877 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1879 /// Retrieve declaration of 'BOOL' typedef
1880 TypedefDecl *getBOOLDecl() const {
1884 /// Save declaration of 'BOOL' typedef
1885 void setBOOLDecl(TypedefDecl *TD) {
1889 /// type of 'BOOL' type.
1890 QualType getBOOLType() const {
1891 return getTypeDeclType(getBOOLDecl());
1894 /// Retrieve the type of the Objective-C \c Protocol class.
1895 QualType getObjCProtoType() const {
1896 return getObjCInterfaceType(getObjCProtocolDecl());
1899 /// Retrieve the C type declaration corresponding to the predefined
1900 /// \c __builtin_va_list type.
1901 TypedefDecl *getBuiltinVaListDecl() const;
1903 /// Retrieve the type of the \c __builtin_va_list type.
1904 QualType getBuiltinVaListType() const {
1905 return getTypeDeclType(getBuiltinVaListDecl());
1908 /// Retrieve the C type declaration corresponding to the predefined
1909 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1910 /// for some targets.
1911 Decl *getVaListTagDecl() const;
1913 /// Retrieve the C type declaration corresponding to the predefined
1914 /// \c __builtin_ms_va_list type.
1915 TypedefDecl *getBuiltinMSVaListDecl() const;
1917 /// Retrieve the type of the \c __builtin_ms_va_list type.
1918 QualType getBuiltinMSVaListType() const {
1919 return getTypeDeclType(getBuiltinMSVaListDecl());
1922 /// Return whether a declaration to a builtin is allowed to be
1923 /// overloaded/redeclared.
1924 bool canBuiltinBeRedeclared(const FunctionDecl *) const;
1926 /// Return a type with additional \c const, \c volatile, or
1927 /// \c restrict qualifiers.
1928 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1929 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1932 /// Un-split a SplitQualType.
1933 QualType getQualifiedType(SplitQualType split) const {
1934 return getQualifiedType(split.Ty, split.Quals);
1937 /// Return a type with additional qualifiers.
1938 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1939 if (!Qs.hasNonFastQualifiers())
1940 return T.withFastQualifiers(Qs.getFastQualifiers());
1941 QualifierCollector Qc(Qs);
1942 const Type *Ptr = Qc.strip(T);
1943 return getExtQualType(Ptr, Qc);
1946 /// Return a type with additional qualifiers.
1947 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1948 if (!Qs.hasNonFastQualifiers())
1949 return QualType(T, Qs.getFastQualifiers());
1950 return getExtQualType(T, Qs);
1953 /// Return a type with the given lifetime qualifier.
1955 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1956 QualType getLifetimeQualifiedType(QualType type,
1957 Qualifiers::ObjCLifetime lifetime) {
1958 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1959 assert(lifetime != Qualifiers::OCL_None);
1962 qs.addObjCLifetime(lifetime);
1963 return getQualifiedType(type, qs);
1966 /// getUnqualifiedObjCPointerType - Returns version of
1967 /// Objective-C pointer type with lifetime qualifier removed.
1968 QualType getUnqualifiedObjCPointerType(QualType type) const {
1969 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1970 !type.getQualifiers().hasObjCLifetime())
1972 Qualifiers Qs = type.getQualifiers();
1973 Qs.removeObjCLifetime();
1974 return getQualifiedType(type.getUnqualifiedType(), Qs);
1977 unsigned char getFixedPointScale(QualType Ty) const;
1978 unsigned char getFixedPointIBits(QualType Ty) const;
1979 FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
1980 APFixedPoint getFixedPointMax(QualType Ty) const;
1981 APFixedPoint getFixedPointMin(QualType Ty) const;
1983 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1984 SourceLocation NameLoc) const;
1986 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1987 UnresolvedSetIterator End) const;
1989 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1990 bool TemplateKeyword,
1991 TemplateDecl *Template) const;
1993 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1994 const IdentifierInfo *Name) const;
1995 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1996 OverloadedOperatorKind Operator) const;
1997 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1998 TemplateName replacement) const;
1999 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
2000 const TemplateArgument &ArgPack) const;
2002 enum GetBuiltinTypeError {
2006 /// Missing a type from <stdio.h>
2009 /// Missing a type from <setjmp.h>
2012 /// Missing a type from <ucontext.h>
2016 /// Return the type for the specified builtin.
2018 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
2019 /// arguments to the builtin that are required to be integer constant
2021 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
2022 unsigned *IntegerConstantArgs = nullptr) const;
2024 /// Types and expressions required to build C++2a three-way comparisons
2025 /// using operator<=>, including the values return by builtin <=> operators.
2026 ComparisonCategories CompCategories;
2029 CanQualType getFromTargetType(unsigned Type) const;
2030 TypeInfo getTypeInfoImpl(const Type *T) const;
2032 //===--------------------------------------------------------------------===//
2034 //===--------------------------------------------------------------------===//
2037 /// Return one of the GCNone, Weak or Strong Objective-C garbage
2038 /// collection attributes.
2039 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
2041 /// Return true if the given vector types are of the same unqualified
2042 /// type or if they are equivalent to the same GCC vector type.
2044 /// \note This ignores whether they are target-specific (AltiVec or Neon)
2046 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
2048 /// Return true if this is an \c NSObject object with its \c NSObject
2050 static bool isObjCNSObjectType(QualType Ty) {
2051 return Ty->isObjCNSObjectType();
2054 //===--------------------------------------------------------------------===//
2055 // Type Sizing and Analysis
2056 //===--------------------------------------------------------------------===//
2058 /// Return the APFloat 'semantics' for the specified scalar floating
2060 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
2062 /// Get the size and alignment of the specified complete type in bits.
2063 TypeInfo getTypeInfo(const Type *T) const;
2064 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
2066 /// Get default simd alignment of the specified complete type in bits.
2067 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
2069 /// Return the size of the specified (complete) type \p T, in bits.
2070 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
2071 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
2073 /// Return the size of the character type, in bits.
2074 uint64_t getCharWidth() const {
2075 return getTypeSize(CharTy);
2078 /// Convert a size in bits to a size in characters.
2079 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
2081 /// Convert a size in characters to a size in bits.
2082 int64_t toBits(CharUnits CharSize) const;
2084 /// Return the size of the specified (complete) type \p T, in
2086 CharUnits getTypeSizeInChars(QualType T) const;
2087 CharUnits getTypeSizeInChars(const Type *T) const;
2089 /// Return the ABI-specified alignment of a (complete) type \p T, in
2091 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
2092 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
2094 /// Return the ABI-specified natural alignment of a (complete) type \p T,
2095 /// before alignment adjustments, in bits.
2097 /// This alignment is curently used only by ARM and AArch64 when passing
2098 /// arguments of a composite type.
2099 unsigned getTypeUnadjustedAlign(QualType T) const {
2100 return getTypeUnadjustedAlign(T.getTypePtr());
2102 unsigned getTypeUnadjustedAlign(const Type *T) const;
2104 /// Return the ABI-specified alignment of a type, in bits, or 0 if
2105 /// the type is incomplete and we cannot determine the alignment (for
2106 /// example, from alignment attributes).
2107 unsigned getTypeAlignIfKnown(QualType T) const;
2109 /// Return the ABI-specified alignment of a (complete) type \p T, in
2111 CharUnits getTypeAlignInChars(QualType T) const;
2112 CharUnits getTypeAlignInChars(const Type *T) const;
2114 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
2115 /// in characters, before alignment adjustments. This method does not work on
2116 /// incomplete types.
2117 CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
2118 CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
2120 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
2121 // type is a record, its data size is returned.
2122 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
2124 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
2125 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
2127 /// Determine if the alignment the type has was required using an
2128 /// alignment attribute.
2129 bool isAlignmentRequired(const Type *T) const;
2130 bool isAlignmentRequired(QualType T) const;
2132 /// Return the "preferred" alignment of the specified type \p T for
2133 /// the current target, in bits.
2135 /// This can be different than the ABI alignment in cases where it is
2136 /// beneficial for performance to overalign a data type.
2137 unsigned getPreferredTypeAlign(const Type *T) const;
2139 /// Return the default alignment for __attribute__((aligned)) on
2140 /// this target, to be used if no alignment value is specified.
2141 unsigned getTargetDefaultAlignForAttributeAligned() const;
2143 /// Return the alignment in bits that should be given to a
2144 /// global variable with type \p T.
2145 unsigned getAlignOfGlobalVar(QualType T) const;
2147 /// Return the alignment in characters that should be given to a
2148 /// global variable with type \p T.
2149 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
2151 /// Return a conservative estimate of the alignment of the specified
2154 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
2157 /// If \p ForAlignof, references are treated like their underlying type
2158 /// and large arrays don't get any special treatment. If not \p ForAlignof
2159 /// it computes the value expected by CodeGen: references are treated like
2160 /// pointers and large arrays get extra alignment.
2161 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2163 /// Get or compute information about the layout of the specified
2164 /// record (struct/union/class) \p D, which indicates its size and field
2165 /// position information.
2166 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2168 /// Get or compute information about the layout of the specified
2169 /// Objective-C interface.
2170 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2173 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2174 bool Simple = false) const;
2176 /// Get or compute information about the layout of the specified
2177 /// Objective-C implementation.
2179 /// This may differ from the interface if synthesized ivars are present.
2180 const ASTRecordLayout &
2181 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2183 /// Get our current best idea for the key function of the
2184 /// given record decl, or nullptr if there isn't one.
2186 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2187 /// ...the first non-pure virtual function that is not inline at the
2188 /// point of class definition.
2190 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
2191 /// virtual functions that are defined 'inline', which means that
2192 /// the result of this computation can change.
2193 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2195 /// Observe that the given method cannot be a key function.
2196 /// Checks the key-function cache for the method's class and clears it
2197 /// if matches the given declaration.
2199 /// This is used in ABIs where out-of-line definitions marked
2200 /// inline are not considered to be key functions.
2202 /// \param method should be the declaration from the class definition
2203 void setNonKeyFunction(const CXXMethodDecl *method);
2205 /// Loading virtual member pointers using the virtual inheritance model
2206 /// always results in an adjustment using the vbtable even if the index is
2209 /// This is usually OK because the first slot in the vbtable points
2210 /// backwards to the top of the MDC. However, the MDC might be reusing a
2211 /// vbptr from an nv-base. In this case, the first slot in the vbtable
2212 /// points to the start of the nv-base which introduced the vbptr and *not*
2213 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
2214 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2216 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2217 uint64_t getFieldOffset(const ValueDecl *FD) const;
2219 /// Get the offset of an ObjCIvarDecl in bits.
2220 uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2221 const ObjCImplementationDecl *ID,
2222 const ObjCIvarDecl *Ivar) const;
2224 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2226 VTableContextBase *getVTableContext();
2228 MangleContext *createMangleContext();
2230 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2231 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2233 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2234 void CollectInheritedProtocols(const Decl *CDecl,
2235 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2237 /// Return true if the specified type has unique object representations
2238 /// according to (C++17 [meta.unary.prop]p9)
2239 bool hasUniqueObjectRepresentations(QualType Ty) const;
2241 //===--------------------------------------------------------------------===//
2243 //===--------------------------------------------------------------------===//
2245 /// Return the canonical (structural) type corresponding to the
2246 /// specified potentially non-canonical type \p T.
2248 /// The non-canonical version of a type may have many "decorated" versions of
2249 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
2250 /// returned type is guaranteed to be free of any of these, allowing two
2251 /// canonical types to be compared for exact equality with a simple pointer
2253 CanQualType getCanonicalType(QualType T) const {
2254 return CanQualType::CreateUnsafe(T.getCanonicalType());
2257 const Type *getCanonicalType(const Type *T) const {
2258 return T->getCanonicalTypeInternal().getTypePtr();
2261 /// Return the canonical parameter type corresponding to the specific
2262 /// potentially non-canonical one.
2264 /// Qualifiers are stripped off, functions are turned into function
2265 /// pointers, and arrays decay one level into pointers.
2266 CanQualType getCanonicalParamType(QualType T) const;
2268 /// Determine whether the given types \p T1 and \p T2 are equivalent.
2269 bool hasSameType(QualType T1, QualType T2) const {
2270 return getCanonicalType(T1) == getCanonicalType(T2);
2272 bool hasSameType(const Type *T1, const Type *T2) const {
2273 return getCanonicalType(T1) == getCanonicalType(T2);
2276 /// Return this type as a completely-unqualified array type,
2277 /// capturing the qualifiers in \p Quals.
2279 /// This will remove the minimal amount of sugaring from the types, similar
2280 /// to the behavior of QualType::getUnqualifiedType().
2282 /// \param T is the qualified type, which may be an ArrayType
2284 /// \param Quals will receive the full set of qualifiers that were
2285 /// applied to the array.
2287 /// \returns if this is an array type, the completely unqualified array type
2288 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2289 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2291 /// Determine whether the given types are equivalent after
2292 /// cvr-qualifiers have been removed.
2293 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2294 return getCanonicalType(T1).getTypePtr() ==
2295 getCanonicalType(T2).getTypePtr();
2298 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2299 bool IsParam) const {
2300 auto SubTnullability = SubT->getNullability(*this);
2301 auto SuperTnullability = SuperT->getNullability(*this);
2302 if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
2303 // Neither has nullability; return true
2304 if (!SubTnullability)
2306 // Both have nullability qualifier.
2307 if (*SubTnullability == *SuperTnullability ||
2308 *SubTnullability == NullabilityKind::Unspecified ||
2309 *SuperTnullability == NullabilityKind::Unspecified)
2313 // Ok for the superclass method parameter to be "nonnull" and the subclass
2314 // method parameter to be "nullable"
2315 return (*SuperTnullability == NullabilityKind::NonNull &&
2316 *SubTnullability == NullabilityKind::Nullable);
2319 // For the return type, it's okay for the superclass method to specify
2320 // "nullable" and the subclass method specify "nonnull"
2321 return (*SuperTnullability == NullabilityKind::Nullable &&
2322 *SubTnullability == NullabilityKind::NonNull);
2328 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2329 const ObjCMethodDecl *MethodImp);
2331 bool UnwrapSimilarTypes(QualType &T1, QualType &T2);
2332 bool UnwrapSimilarArrayTypes(QualType &T1, QualType &T2);
2334 /// Determine if two types are similar, according to the C++ rules. That is,
2335 /// determine if they are the same other than qualifiers on the initial
2336 /// sequence of pointer / pointer-to-member / array (and in Clang, object
2337 /// pointer) types and their element types.
2339 /// Clang offers a number of qualifiers in addition to the C++ qualifiers;
2340 /// those qualifiers are also ignored in the 'similarity' check.
2341 bool hasSimilarType(QualType T1, QualType T2);
2343 /// Determine if two types are similar, ignoring only CVR qualifiers.
2344 bool hasCvrSimilarType(QualType T1, QualType T2);
2346 /// Retrieves the "canonical" nested name specifier for a
2347 /// given nested name specifier.
2349 /// The canonical nested name specifier is a nested name specifier
2350 /// that uniquely identifies a type or namespace within the type
2351 /// system. For example, given:
2356 /// template<typename T> struct X { typename T* type; };
2360 /// template<typename T> struct Y {
2361 /// typename N::S::X<T>::type member;
2365 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2366 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2367 /// by declarations in the type system and the canonical type for
2368 /// the template type parameter 'T' is template-param-0-0.
2369 NestedNameSpecifier *
2370 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2372 /// Retrieves the default calling convention for the current target.
2373 CallingConv getDefaultCallingConvention(bool IsVariadic,
2374 bool IsCXXMethod) const;
2376 /// Retrieves the "canonical" template name that refers to a
2379 /// The canonical template name is the simplest expression that can
2380 /// be used to refer to a given template. For most templates, this
2381 /// expression is just the template declaration itself. For example,
2382 /// the template std::vector can be referred to via a variety of
2383 /// names---std::vector, \::std::vector, vector (if vector is in
2384 /// scope), etc.---but all of these names map down to the same
2385 /// TemplateDecl, which is used to form the canonical template name.
2387 /// Dependent template names are more interesting. Here, the
2388 /// template name could be something like T::template apply or
2389 /// std::allocator<T>::template rebind, where the nested name
2390 /// specifier itself is dependent. In this case, the canonical
2391 /// template name uses the shortest form of the dependent
2392 /// nested-name-specifier, which itself contains all canonical
2393 /// types, values, and templates.
2394 TemplateName getCanonicalTemplateName(TemplateName Name) const;
2396 /// Determine whether the given template names refer to the same
2398 bool hasSameTemplateName(TemplateName X, TemplateName Y);
2400 /// Retrieve the "canonical" template argument.
2402 /// The canonical template argument is the simplest template argument
2403 /// (which may be a type, value, expression, or declaration) that
2404 /// expresses the value of the argument.
2405 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2408 /// Type Query functions. If the type is an instance of the specified class,
2409 /// return the Type pointer for the underlying maximally pretty type. This
2410 /// is a member of ASTContext because this may need to do some amount of
2411 /// canonicalization, e.g. to move type qualifiers into the element type.
2412 const ArrayType *getAsArrayType(QualType T) const;
2413 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2414 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2416 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2417 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2419 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2420 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2422 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2424 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2427 /// Return the innermost element type of an array type.
2429 /// For example, will return "int" for int[m][n]
2430 QualType getBaseElementType(const ArrayType *VAT) const;
2432 /// Return the innermost element type of a type (which needn't
2433 /// actually be an array type).
2434 QualType getBaseElementType(QualType QT) const;
2436 /// Return number of constant array elements.
2437 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2439 /// Perform adjustment on the parameter type of a function.
2441 /// This routine adjusts the given parameter type @p T to the actual
2442 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2443 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2444 QualType getAdjustedParameterType(QualType T) const;
2446 /// Retrieve the parameter type as adjusted for use in the signature
2447 /// of a function, decaying array and function types and removing top-level
2449 QualType getSignatureParameterType(QualType T) const;
2451 QualType getExceptionObjectType(QualType T) const;
2453 /// Return the properly qualified result of decaying the specified
2454 /// array type to a pointer.
2456 /// This operation is non-trivial when handling typedefs etc. The canonical
2457 /// type of \p T must be an array type, this returns a pointer to a properly
2458 /// qualified element of the array.
2460 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2461 QualType getArrayDecayedType(QualType T) const;
2463 /// Return the type that \p PromotableType will promote to: C99
2464 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2465 QualType getPromotedIntegerType(QualType PromotableType) const;
2467 /// Recurses in pointer/array types until it finds an Objective-C
2468 /// retainable type and returns its ownership.
2469 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2471 /// Whether this is a promotable bitfield reference according
2472 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2474 /// \returns the type this bit-field will promote to, or NULL if no
2475 /// promotion occurs.
2476 QualType isPromotableBitField(Expr *E) const;
2478 /// Return the highest ranked integer type, see C99 6.3.1.8p1.
2480 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2481 /// \p LHS < \p RHS, return -1.
2482 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2484 /// Compare the rank of the two specified floating point types,
2485 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2487 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2488 /// \p LHS < \p RHS, return -1.
2489 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2491 /// Return a real floating point or a complex type (based on
2492 /// \p typeDomain/\p typeSize).
2494 /// \param typeDomain a real floating point or complex type.
2495 /// \param typeSize a real floating point or complex type.
2496 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2497 QualType typeDomain) const;
2499 unsigned getTargetAddressSpace(QualType T) const {
2500 return getTargetAddressSpace(T.getQualifiers());
2503 unsigned getTargetAddressSpace(Qualifiers Q) const {
2504 return getTargetAddressSpace(Q.getAddressSpace());
2507 unsigned getTargetAddressSpace(LangAS AS) const;
2509 LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;
2511 /// Get target-dependent integer value for null pointer which is used for
2512 /// constant folding.
2513 uint64_t getTargetNullPointerValue(QualType QT) const;
2515 bool addressSpaceMapManglingFor(LangAS AS) const {
2516 return AddrSpaceMapMangling || isTargetAddressSpace(AS);
2520 // Helper for integer ordering
2521 unsigned getIntegerRank(const Type *T) const;
2524 //===--------------------------------------------------------------------===//
2525 // Type Compatibility Predicates
2526 //===--------------------------------------------------------------------===//
2528 /// Compatibility predicates used to check assignment expressions.
2529 bool typesAreCompatible(QualType T1, QualType T2,
2530 bool CompareUnqualified = false); // C99 6.2.7p1
2532 bool propertyTypesAreCompatible(QualType, QualType);
2533 bool typesAreBlockPointerCompatible(QualType, QualType);
2535 bool isObjCIdType(QualType T) const {
2536 return T == getObjCIdType();
2539 bool isObjCClassType(QualType T) const {
2540 return T == getObjCClassType();
2543 bool isObjCSelType(QualType T) const {
2544 return T == getObjCSelType();
2547 bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
2550 bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
2552 // Check the safety of assignment from LHS to RHS
2553 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2554 const ObjCObjectPointerType *RHSOPT);
2555 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2556 const ObjCObjectType *RHS);
2557 bool canAssignObjCInterfacesInBlockPointer(
2558 const ObjCObjectPointerType *LHSOPT,
2559 const ObjCObjectPointerType *RHSOPT,
2560 bool BlockReturnType);
2561 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2562 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2563 const ObjCObjectPointerType *RHSOPT);
2564 bool canBindObjCObjectType(QualType To, QualType From);
2566 // Functions for calculating composite types
2567 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2568 bool Unqualified = false, bool BlockReturnType = false);
2569 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2570 bool Unqualified = false);
2571 QualType mergeFunctionParameterTypes(QualType, QualType,
2572 bool OfBlockPointer = false,
2573 bool Unqualified = false);
2574 QualType mergeTransparentUnionType(QualType, QualType,
2575 bool OfBlockPointer=false,
2576 bool Unqualified = false);
2578 QualType mergeObjCGCQualifiers(QualType, QualType);
2580 /// This function merges the ExtParameterInfo lists of two functions. It
2581 /// returns true if the lists are compatible. The merged list is returned in
2584 /// \param FirstFnType The type of the first function.
2586 /// \param SecondFnType The type of the second function.
2588 /// \param CanUseFirst This flag is set to true if the first function's
2589 /// ExtParameterInfo list can be used as the composite list of
2590 /// ExtParameterInfo.
2592 /// \param CanUseSecond This flag is set to true if the second function's
2593 /// ExtParameterInfo list can be used as the composite list of
2594 /// ExtParameterInfo.
2596 /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
2597 /// empty if none of the flags are set.
2599 bool mergeExtParameterInfo(
2600 const FunctionProtoType *FirstFnType,
2601 const FunctionProtoType *SecondFnType,
2602 bool &CanUseFirst, bool &CanUseSecond,
2603 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
2605 void ResetObjCLayout(const ObjCContainerDecl *CD);
2607 //===--------------------------------------------------------------------===//
2608 // Integer Predicates
2609 //===--------------------------------------------------------------------===//
2611 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2612 // of bits in an integer type excluding any padding bits.
2613 unsigned getIntWidth(QualType T) const;
2615 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2616 // unsigned integer type. This method takes a signed type, and returns the
2617 // corresponding unsigned integer type.
2618 // With the introduction of fixed point types in ISO N1169, this method also
2619 // accepts fixed point types and returns the corresponding unsigned type for
2620 // a given fixed point type.
2621 QualType getCorrespondingUnsignedType(QualType T) const;
2623 // Per ISO N1169, this method accepts fixed point types and returns the
2624 // corresponding saturated type for a given fixed point type.
2625 QualType getCorrespondingSaturatedType(QualType Ty) const;
2627 //===--------------------------------------------------------------------===//
2629 //===--------------------------------------------------------------------===//
2631 /// Make an APSInt of the appropriate width and signedness for the
2632 /// given \p Value and integer \p Type.
2633 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2634 // If Type is a signed integer type larger than 64 bits, we need to be sure
2635 // to sign extend Res appropriately.
2636 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2638 unsigned Width = getIntWidth(Type);
2639 if (Width != Res.getBitWidth())
2640 return Res.extOrTrunc(Width);
2644 bool isSentinelNullExpr(const Expr *E);
2646 /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
2648 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2650 /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
2652 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2654 /// Return true if there is at least one \@implementation in the TU.
2655 bool AnyObjCImplementation() {
2656 return !ObjCImpls.empty();
2659 /// Set the implementation of ObjCInterfaceDecl.
2660 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2661 ObjCImplementationDecl *ImplD);
2663 /// Set the implementation of ObjCCategoryDecl.
2664 void setObjCImplementation(ObjCCategoryDecl *CatD,
2665 ObjCCategoryImplDecl *ImplD);
2667 /// Get the duplicate declaration of a ObjCMethod in the same
2668 /// interface, or null if none exists.
2669 const ObjCMethodDecl *
2670 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2672 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2673 const ObjCMethodDecl *Redecl);
2675 /// Returns the Objective-C interface that \p ND belongs to if it is
2676 /// an Objective-C method/property/ivar etc. that is part of an interface,
2677 /// otherwise returns null.
2678 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2680 /// Set the copy inialization expression of a block var decl. \p CanThrow
2681 /// indicates whether the copy expression can throw or not.
2682 void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow);
2684 /// Get the copy initialization expression of the VarDecl \p VD, or
2685 /// nullptr if none exists.
2686 BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const;
2688 /// Allocate an uninitialized TypeSourceInfo.
2690 /// The caller should initialize the memory held by TypeSourceInfo using
2691 /// the TypeLoc wrappers.
2693 /// \param T the type that will be the basis for type source info. This type
2694 /// should refer to how the declarator was written in source code, not to
2695 /// what type semantic analysis resolved the declarator to.
2697 /// \param Size the size of the type info to create, or 0 if the size
2698 /// should be calculated based on the type.
2699 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2701 /// Allocate a TypeSourceInfo where all locations have been
2702 /// initialized to a given location, which defaults to the empty
2705 getTrivialTypeSourceInfo(QualType T,
2706 SourceLocation Loc = SourceLocation()) const;
2708 /// Add a deallocation callback that will be invoked when the
2709 /// ASTContext is destroyed.
2711 /// \param Callback A callback function that will be invoked on destruction.
2713 /// \param Data Pointer data that will be provided to the callback function
2714 /// when it is called.
2715 void AddDeallocation(void (*Callback)(void*), void *Data);
2717 /// If T isn't trivially destructible, calls AddDeallocation to register it
2718 /// for destruction.
2719 template <typename T>
2720 void addDestruction(T *Ptr) {
2721 if (!std::is_trivially_destructible<T>::value) {
2722 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
2723 AddDeallocation(DestroyPtr, Ptr);
2727 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2728 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2730 /// Determines if the decl can be CodeGen'ed or deserialized from PCH
2731 /// lazily, only when used; this is only relevant for function or file scoped
2732 /// var definitions.
2734 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2736 bool DeclMustBeEmitted(const Decl *D);
2738 /// Visits all versions of a multiversioned function with the passed
2740 void forEachMultiversionedFunctionVersion(
2741 const FunctionDecl *FD,
2742 llvm::function_ref<void(FunctionDecl *)> Pred) const;
2744 const CXXConstructorDecl *
2745 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2747 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2748 CXXConstructorDecl *CD);
2750 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2752 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2754 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2756 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2758 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2759 unsigned getManglingNumber(const NamedDecl *ND) const;
2761 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2762 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2764 /// Retrieve the context for computing mangling numbers in the given
2766 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2768 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
2770 /// Used by ParmVarDecl to store on the side the
2771 /// index of the parameter when it exceeds the size of the normal bitfield.
2772 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2774 /// Used by ParmVarDecl to retrieve on the side the
2775 /// index of the parameter when it exceeds the size of the normal bitfield.
2776 unsigned getParameterIndex(const ParmVarDecl *D) const;
2778 /// Get the storage for the constant value of a materialized temporary
2779 /// of static storage duration.
2780 APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
2783 //===--------------------------------------------------------------------===//
2785 //===--------------------------------------------------------------------===//
2787 /// The number of implicitly-declared default constructors.
2788 static unsigned NumImplicitDefaultConstructors;
2790 /// The number of implicitly-declared default constructors for
2791 /// which declarations were built.
2792 static unsigned NumImplicitDefaultConstructorsDeclared;
2794 /// The number of implicitly-declared copy constructors.
2795 static unsigned NumImplicitCopyConstructors;
2797 /// The number of implicitly-declared copy constructors for
2798 /// which declarations were built.
2799 static unsigned NumImplicitCopyConstructorsDeclared;
2801 /// The number of implicitly-declared move constructors.
2802 static unsigned NumImplicitMoveConstructors;
2804 /// The number of implicitly-declared move constructors for
2805 /// which declarations were built.
2806 static unsigned NumImplicitMoveConstructorsDeclared;
2808 /// The number of implicitly-declared copy assignment operators.
2809 static unsigned NumImplicitCopyAssignmentOperators;
2811 /// The number of implicitly-declared copy assignment operators for
2812 /// which declarations were built.
2813 static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2815 /// The number of implicitly-declared move assignment operators.
2816 static unsigned NumImplicitMoveAssignmentOperators;
2818 /// The number of implicitly-declared move assignment operators for
2819 /// which declarations were built.
2820 static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2822 /// The number of implicitly-declared destructors.
2823 static unsigned NumImplicitDestructors;
2825 /// The number of implicitly-declared destructors for which
2826 /// declarations were built.
2827 static unsigned NumImplicitDestructorsDeclared;
2830 /// Initialize built-in types.
2832 /// This routine may only be invoked once for a given ASTContext object.
2833 /// It is normally invoked after ASTContext construction.
2835 /// \param Target The target
2836 void InitBuiltinTypes(const TargetInfo &Target,
2837 const TargetInfo *AuxTarget = nullptr);
2840 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2842 // Return the Objective-C type encoding for a given type.
2843 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2844 bool ExpandPointedToStructures,
2845 bool ExpandStructures,
2846 const FieldDecl *Field,
2847 bool OutermostType = false,
2848 bool EncodingProperty = false,
2849 bool StructField = false,
2850 bool EncodeBlockParameters = false,
2851 bool EncodeClassNames = false,
2852 bool EncodePointerToObjCTypedef = false,
2853 QualType *NotEncodedT=nullptr) const;
2855 // Adds the encoding of the structure's members.
2856 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2857 const FieldDecl *Field,
2858 bool includeVBases = true,
2859 QualType *NotEncodedT=nullptr) const;
2862 // Adds the encoding of a method parameter or return type.
2863 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2864 QualType T, std::string& S,
2865 bool Extended) const;
2867 /// Returns true if this is an inline-initialized static data member
2868 /// which is treated as a definition for MSVC compatibility.
2869 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2871 enum class InlineVariableDefinitionKind {
2872 /// Not an inline variable.
2875 /// Weak definition of inline variable.
2878 /// Weak for now, might become strong later in this TU.
2881 /// Strong definition.
2885 /// Determine whether a definition of this inline variable should
2886 /// be treated as a weak or strong definition. For compatibility with
2887 /// C++14 and before, for a constexpr static data member, if there is an
2888 /// out-of-line declaration of the member, we may promote it from weak to
2890 InlineVariableDefinitionKind
2891 getInlineVariableDefinitionKind(const VarDecl *VD) const;
2894 friend class DeclarationNameTable;
2895 friend class DeclContext;
2897 const ASTRecordLayout &
2898 getObjCLayout(const ObjCInterfaceDecl *D,
2899 const ObjCImplementationDecl *Impl) const;
2901 /// A set of deallocations that should be performed when the
2902 /// ASTContext is destroyed.
2903 // FIXME: We really should have a better mechanism in the ASTContext to
2904 // manage running destructors for types which do variable sized allocation
2905 // within the AST. In some places we thread the AST bump pointer allocator
2906 // into the datastructures which avoids this mess during deallocation but is
2907 // wasteful of memory, and here we require a lot of error prone book keeping
2908 // in order to track and run destructors while we're tearing things down.
2909 using DeallocationFunctionsAndArguments =
2910 llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
2911 DeallocationFunctionsAndArguments Deallocations;
2913 // FIXME: This currently contains the set of StoredDeclMaps used
2914 // by DeclContext objects. This probably should not be in ASTContext,
2915 // but we include it here so that ASTContext can quickly deallocate them.
2916 llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
2918 std::vector<Decl *> TraversalScope;
2920 std::unique_ptr<ParentMap> Parents;
2922 std::unique_ptr<VTableContextBase> VTContext;
2924 void ReleaseDeclContextMaps();
2927 enum PragmaSectionFlag : unsigned {
2933 PSF_Invalid = 0x80000000U,
2936 struct SectionInfo {
2937 DeclaratorDecl *Decl;
2938 SourceLocation PragmaSectionLocation;
2941 SectionInfo() = default;
2942 SectionInfo(DeclaratorDecl *Decl,
2943 SourceLocation PragmaSectionLocation,
2945 : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
2946 SectionFlags(SectionFlags) {}
2949 llvm::StringMap<SectionInfo> SectionInfos;
2952 /// Utility function for constructing a nullary selector.
2953 inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
2954 IdentifierInfo* II = &Ctx.Idents.get(name);
2955 return Ctx.Selectors.getSelector(0, &II);
2958 /// Utility function for constructing an unary selector.
2959 inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
2960 IdentifierInfo* II = &Ctx.Idents.get(name);
2961 return Ctx.Selectors.getSelector(1, &II);
2964 } // namespace clang
2966 // operator new and delete aren't allowed inside namespaces.
2968 /// Placement new for using the ASTContext's allocator.
2970 /// This placement form of operator new uses the ASTContext's allocator for
2971 /// obtaining memory.
2973 /// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h!
2974 /// Any changes here need to also be made there.
2976 /// We intentionally avoid using a nothrow specification here so that the calls
2977 /// to this operator will not perform a null check on the result -- the
2978 /// underlying allocator never returns null pointers.
2980 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2982 /// // Default alignment (8)
2983 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2984 /// // Specific alignment
2985 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2987 /// Memory allocated through this placement new operator does not need to be
2988 /// explicitly freed, as ASTContext will free all of this memory when it gets
2989 /// destroyed. Please note that you cannot use delete on the pointer.
2991 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2992 /// @param C The ASTContext that provides the allocator.
2993 /// @param Alignment The alignment of the allocated memory (if the underlying
2994 /// allocator supports it).
2995 /// @return The allocated memory. Could be nullptr.
2996 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2997 size_t Alignment /* = 8 */) {
2998 return C.Allocate(Bytes, Alignment);
3001 /// Placement delete companion to the new above.
3003 /// This operator is just a companion to the new above. There is no way of
3004 /// invoking it directly; see the new operator for more details. This operator
3005 /// is called implicitly by the compiler if a placement new expression using
3006 /// the ASTContext throws in the object constructor.
3007 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
3011 /// This placement form of operator new[] uses the ASTContext's allocator for
3012 /// obtaining memory.
3014 /// We intentionally avoid using a nothrow specification here so that the calls
3015 /// to this operator will not perform a null check on the result -- the
3016 /// underlying allocator never returns null pointers.
3018 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3020 /// // Default alignment (8)
3021 /// char *data = new (Context) char[10];
3022 /// // Specific alignment
3023 /// char *data = new (Context, 4) char[10];
3025 /// Memory allocated through this placement new[] operator does not need to be
3026 /// explicitly freed, as ASTContext will free all of this memory when it gets
3027 /// destroyed. Please note that you cannot use delete on the pointer.
3029 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3030 /// @param C The ASTContext that provides the allocator.
3031 /// @param Alignment The alignment of the allocated memory (if the underlying
3032 /// allocator supports it).
3033 /// @return The allocated memory. Could be nullptr.
3034 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
3035 size_t Alignment /* = 8 */) {
3036 return C.Allocate(Bytes, Alignment);
3039 /// Placement delete[] companion to the new[] above.
3041 /// This operator is just a companion to the new[] above. There is no way of
3042 /// invoking it directly; see the new[] operator for more details. This operator
3043 /// is called implicitly by the compiler if a placement new[] expression using
3044 /// the ASTContext throws in the object constructor.
3045 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
3049 /// Create the representation of a LazyGenerationalUpdatePtr.
3050 template <typename Owner, typename T,
3051 void (clang::ExternalASTSource::*Update)(Owner)>
3052 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
3053 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
3054 const clang::ASTContext &Ctx, T Value) {
3055 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
3056 // include ASTContext.h. We explicitly instantiate it for all relevant types
3057 // in ASTContext.cpp.
3058 if (auto *Source = Ctx.getExternalSource())
3059 return new (Ctx) LazyData(Source, Value);
3063 #endif // LLVM_CLANG_AST_ASTCONTEXT_H