1 //===- ASTContext.h - Context to hold long-lived AST nodes ------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// Defines the clang::ASTContext interface.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_ASTCONTEXT_H
15 #define LLVM_CLANG_AST_ASTCONTEXT_H
17 #include "clang/AST/ASTContextAllocate.h"
18 #include "clang/AST/ASTFwd.h"
19 #include "clang/AST/CanonicalType.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/ComparisonCategories.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/ExternalASTSource.h"
26 #include "clang/AST/NestedNameSpecifier.h"
27 #include "clang/AST/PrettyPrinter.h"
28 #include "clang/AST/RawCommentList.h"
29 #include "clang/AST/TemplateName.h"
30 #include "clang/AST/Type.h"
31 #include "clang/Basic/AddressSpaces.h"
32 #include "clang/Basic/AttrKinds.h"
33 #include "clang/Basic/IdentifierTable.h"
34 #include "clang/Basic/LLVM.h"
35 #include "clang/Basic/LangOptions.h"
36 #include "clang/Basic/Linkage.h"
37 #include "clang/Basic/OperatorKinds.h"
38 #include "clang/Basic/PartialDiagnostic.h"
39 #include "clang/Basic/SanitizerBlacklist.h"
40 #include "clang/Basic/SourceLocation.h"
41 #include "clang/Basic/Specifiers.h"
42 #include "clang/Basic/XRayLists.h"
43 #include "llvm/ADT/APSInt.h"
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/FoldingSet.h"
47 #include "llvm/ADT/IntrusiveRefCntPtr.h"
48 #include "llvm/ADT/MapVector.h"
49 #include "llvm/ADT/None.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/PointerIntPair.h"
52 #include "llvm/ADT/PointerUnion.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringMap.h"
55 #include "llvm/ADT/StringRef.h"
56 #include "llvm/ADT/TinyPtrVector.h"
57 #include "llvm/ADT/Triple.h"
58 #include "llvm/ADT/iterator_range.h"
59 #include "llvm/Support/AlignOf.h"
60 #include "llvm/Support/Allocator.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/Compiler.h"
63 #include "llvm/Support/TypeSize.h"
70 #include <type_traits>
77 template <typename T, unsigned N> class SmallPtrSet;
85 class ASTMutationListener;
86 class ASTRecordLayout;
89 class BuiltinTemplateDecl;
93 class CXXConstructorDecl;
96 class DiagnosticsEngine;
97 class ParentMapContext;
99 class DynTypedNodeList;
101 class FixedPointSemantics;
104 class MangleNumberingContext;
105 class MaterializeTemporaryExpr;
106 class MemberSpecializationInfo;
108 struct MSGuidDeclParts;
109 class ObjCCategoryDecl;
110 class ObjCCategoryImplDecl;
111 class ObjCContainerDecl;
113 class ObjCImplementationDecl;
114 class ObjCInterfaceDecl;
116 class ObjCMethodDecl;
117 class ObjCPropertyDecl;
118 class ObjCPropertyImplDecl;
119 class ObjCProtocolDecl;
120 class ObjCTypeParamDecl;
122 struct ParsedTargetAttr;
125 class StoredDeclsMap;
129 class TemplateParameterList;
130 class TemplateTemplateParmDecl;
131 class TemplateTypeParmDecl;
132 class UnresolvedSetIterator;
133 class UsingShadowDecl;
134 class VarTemplateDecl;
135 class VTableContextBase;
136 struct BlockVarCopyInit;
142 } // namespace Builtin
144 enum BuiltinTemplateKind : int;
145 enum OpenCLTypeKind : uint8_t;
151 } // namespace comments
157 } // namespace interp
159 namespace serialization {
160 template <class> class AbstractTypeReader;
161 } // namespace serialization
166 bool AlignIsRequired : 1;
168 TypeInfo() : AlignIsRequired(false) {}
169 TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
170 : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
173 /// Holds long-lived AST nodes (such as types and decls) that can be
174 /// referred to throughout the semantic analysis of a file.
175 class ASTContext : public RefCountedBase<ASTContext> {
176 friend class NestedNameSpecifier;
178 mutable SmallVector<Type *, 0> Types;
179 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
180 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
181 mutable llvm::FoldingSet<PointerType> PointerTypes;
182 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
183 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
184 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
185 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
186 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
187 mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &>
189 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
190 mutable std::vector<VariableArrayType*> VariableArrayTypes;
191 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
192 mutable llvm::FoldingSet<DependentSizedExtVectorType>
193 DependentSizedExtVectorTypes;
194 mutable llvm::FoldingSet<DependentAddressSpaceType>
195 DependentAddressSpaceTypes;
196 mutable llvm::FoldingSet<VectorType> VectorTypes;
197 mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes;
198 mutable llvm::FoldingSet<ConstantMatrixType> MatrixTypes;
199 mutable llvm::FoldingSet<DependentSizedMatrixType> DependentSizedMatrixTypes;
200 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
201 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
203 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
204 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
205 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
206 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
207 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
208 SubstTemplateTypeParmTypes;
209 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
210 SubstTemplateTypeParmPackTypes;
211 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
212 TemplateSpecializationTypes;
213 mutable llvm::FoldingSet<ParenType> ParenTypes;
214 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
215 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
216 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
218 DependentTemplateSpecializationTypes;
219 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
220 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
221 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
222 mutable llvm::FoldingSet<DependentUnaryTransformType>
223 DependentUnaryTransformTypes;
224 mutable llvm::ContextualFoldingSet<AutoType, ASTContext&> AutoTypes;
225 mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
226 DeducedTemplateSpecializationTypes;
227 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
228 llvm::FoldingSet<AttributedType> AttributedTypes;
229 mutable llvm::FoldingSet<PipeType> PipeTypes;
230 mutable llvm::FoldingSet<ExtIntType> ExtIntTypes;
231 mutable llvm::FoldingSet<DependentExtIntType> DependentExtIntTypes;
233 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
234 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
235 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
236 SubstTemplateTemplateParms;
237 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
239 SubstTemplateTemplateParmPacks;
241 /// The set of nested name specifiers.
243 /// This set is managed by the NestedNameSpecifier class.
244 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
245 mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
247 /// A cache mapping from RecordDecls to ASTRecordLayouts.
249 /// This is lazily created. This is intentionally not serialized.
250 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
252 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
255 /// A cache from types to size and alignment information.
256 using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
257 mutable TypeInfoMap MemoizedTypeInfo;
259 /// A cache from types to unadjusted alignment information. Only ARM and
260 /// AArch64 targets need this information, keeping it separate prevents
261 /// imposing overhead on TypeInfo size.
262 using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>;
263 mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
265 /// A cache mapping from CXXRecordDecls to key functions.
266 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
268 /// Mapping from ObjCContainers to their ObjCImplementations.
269 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
271 /// Mapping from ObjCMethod to its duplicate declaration in the same
273 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
275 /// Mapping from __block VarDecls to BlockVarCopyInit.
276 llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
278 /// Mapping from GUIDs to the corresponding MSGuidDecl.
279 mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls;
281 /// Used to cleanups APValues stored in the AST.
282 mutable llvm::SmallVector<APValue *, 0> APValueCleanups;
284 /// A cache mapping a string value to a StringLiteral object with the same
287 /// This is lazily created. This is intentionally not serialized.
288 mutable llvm::StringMap<StringLiteral *> StringLiteralCache;
290 /// Representation of a "canonical" template template parameter that
291 /// is used in canonical template names.
292 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
293 TemplateTemplateParmDecl *Parm;
296 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
299 TemplateTemplateParmDecl *getParam() const { return Parm; }
301 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) {
302 Profile(ID, C, Parm);
305 static void Profile(llvm::FoldingSetNodeID &ID,
307 TemplateTemplateParmDecl *Parm);
309 mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm,
311 CanonTemplateTemplateParms;
313 TemplateTemplateParmDecl *
314 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
316 /// The typedef for the __int128_t type.
317 mutable TypedefDecl *Int128Decl = nullptr;
319 /// The typedef for the __uint128_t type.
320 mutable TypedefDecl *UInt128Decl = nullptr;
322 /// The typedef for the target specific predefined
323 /// __builtin_va_list type.
324 mutable TypedefDecl *BuiltinVaListDecl = nullptr;
326 /// The typedef for the predefined \c __builtin_ms_va_list type.
327 mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
329 /// The typedef for the predefined \c id type.
330 mutable TypedefDecl *ObjCIdDecl = nullptr;
332 /// The typedef for the predefined \c SEL type.
333 mutable TypedefDecl *ObjCSelDecl = nullptr;
335 /// The typedef for the predefined \c Class type.
336 mutable TypedefDecl *ObjCClassDecl = nullptr;
338 /// The typedef for the predefined \c Protocol class in Objective-C.
339 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
341 /// The typedef for the predefined 'BOOL' type.
342 mutable TypedefDecl *BOOLDecl = nullptr;
344 // Typedefs which may be provided defining the structure of Objective-C
346 QualType ObjCIdRedefinitionType;
347 QualType ObjCClassRedefinitionType;
348 QualType ObjCSelRedefinitionType;
350 /// The identifier 'bool'.
351 mutable IdentifierInfo *BoolName = nullptr;
353 /// The identifier 'NSObject'.
354 mutable IdentifierInfo *NSObjectName = nullptr;
356 /// The identifier 'NSCopying'.
357 IdentifierInfo *NSCopyingName = nullptr;
359 /// The identifier '__make_integer_seq'.
360 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
362 /// The identifier '__type_pack_element'.
363 mutable IdentifierInfo *TypePackElementName = nullptr;
365 QualType ObjCConstantStringType;
366 mutable RecordDecl *CFConstantStringTagDecl = nullptr;
367 mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
369 mutable QualType ObjCSuperType;
371 QualType ObjCNSStringType;
373 /// The typedef declaration for the Objective-C "instancetype" type.
374 TypedefDecl *ObjCInstanceTypeDecl = nullptr;
376 /// The type for the C FILE type.
377 TypeDecl *FILEDecl = nullptr;
379 /// The type for the C jmp_buf type.
380 TypeDecl *jmp_bufDecl = nullptr;
382 /// The type for the C sigjmp_buf type.
383 TypeDecl *sigjmp_bufDecl = nullptr;
385 /// The type for the C ucontext_t type.
386 TypeDecl *ucontext_tDecl = nullptr;
388 /// Type for the Block descriptor for Blocks CodeGen.
390 /// Since this is only used for generation of debug info, it is not
392 mutable RecordDecl *BlockDescriptorType = nullptr;
394 /// Type for the Block descriptor for Blocks CodeGen.
396 /// Since this is only used for generation of debug info, it is not
398 mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
400 /// Declaration for the CUDA cudaConfigureCall function.
401 FunctionDecl *cudaConfigureCallDecl = nullptr;
403 /// Keeps track of all declaration attributes.
405 /// Since so few decls have attrs, we keep them in a hash map instead of
406 /// wasting space in the Decl class.
407 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
409 /// A mapping from non-redeclarable declarations in modules that were
410 /// merged with other declarations to the canonical declaration that they were
412 llvm::DenseMap<Decl*, Decl*> MergedDecls;
414 /// A mapping from a defining declaration to a list of modules (other
415 /// than the owning module of the declaration) that contain merged
416 /// definitions of that entity.
417 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
419 /// Initializers for a module, in order. Each Decl will be either
420 /// something that has a semantic effect on startup (such as a variable with
421 /// a non-constant initializer), or an ImportDecl (which recursively triggers
422 /// initialization of another module).
423 struct PerModuleInitializers {
424 llvm::SmallVector<Decl*, 4> Initializers;
425 llvm::SmallVector<uint32_t, 4> LazyInitializers;
427 void resolve(ASTContext &Ctx);
429 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
431 ASTContext &this_() { return *this; }
434 /// A type synonym for the TemplateOrInstantiation mapping.
435 using TemplateOrSpecializationInfo =
436 llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
439 friend class ASTDeclReader;
440 friend class ASTReader;
441 friend class ASTWriter;
442 template <class> friend class serialization::AbstractTypeReader;
443 friend class CXXRecordDecl;
445 /// A mapping to contain the template or declaration that
446 /// a variable declaration describes or was instantiated from,
449 /// For non-templates, this value will be NULL. For variable
450 /// declarations that describe a variable template, this will be a
451 /// pointer to a VarTemplateDecl. For static data members
452 /// of class template specializations, this will be the
453 /// MemberSpecializationInfo referring to the member variable that was
454 /// instantiated or specialized. Thus, the mapping will keep track of
455 /// the static data member templates from which static data members of
456 /// class template specializations were instantiated.
458 /// Given the following example:
461 /// template<typename T>
466 /// template<typename T>
467 /// T X<T>::value = T(17);
469 /// int *x = &X<int>::value;
472 /// This mapping will contain an entry that maps from the VarDecl for
473 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
474 /// class template X) and will be marked TSK_ImplicitInstantiation.
475 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
476 TemplateOrInstantiation;
478 /// Keeps track of the declaration from which a using declaration was
479 /// created during instantiation.
481 /// The source and target declarations are always a UsingDecl, an
482 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
486 /// template<typename T>
491 /// template<typename T>
492 /// struct B : A<T> {
496 /// template struct B<int>;
499 /// This mapping will contain an entry that maps from the UsingDecl in
500 /// B<int> to the UnresolvedUsingDecl in B<T>.
501 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
503 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
504 InstantiatedFromUsingShadowDecl;
506 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
508 /// Mapping that stores the methods overridden by a given C++
511 /// Since most C++ member functions aren't virtual and therefore
512 /// don't override anything, we store the overridden functions in
513 /// this map on the side rather than within the CXXMethodDecl structure.
514 using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
515 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
517 /// Mapping from each declaration context to its corresponding
518 /// mangling numbering context (used for constructs like lambdas which
519 /// need to be consistently numbered for the mangler).
520 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
521 MangleNumberingContexts;
522 llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>>
523 ExtraMangleNumberingContexts;
525 /// Side-table of mangling numbers for declarations which rarely
526 /// need them (like static local vars).
527 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
528 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
530 /// Mapping that stores parameterIndex values for ParmVarDecls when
531 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
532 using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
533 ParameterIndexTable ParamIndices;
535 ImportDecl *FirstLocalImport = nullptr;
536 ImportDecl *LastLocalImport = nullptr;
538 TranslationUnitDecl *TUDecl;
539 mutable ExternCContextDecl *ExternCContext = nullptr;
540 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
541 mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
543 /// The associated SourceManager object.
544 SourceManager &SourceMgr;
546 /// The language options used to create the AST associated with
547 /// this ASTContext object.
548 LangOptions &LangOpts;
550 /// Blacklist object that is used by sanitizers to decide which
551 /// entities should not be instrumented.
552 std::unique_ptr<SanitizerBlacklist> SanitizerBL;
554 /// Function filtering mechanism to determine whether a given function
555 /// should be imbued with the XRay "always" or "never" attributes.
556 std::unique_ptr<XRayFunctionFilter> XRayFilter;
558 /// The allocator used to create AST objects.
560 /// AST objects are never destructed; rather, all memory associated with the
561 /// AST objects will be released when the ASTContext itself is destroyed.
562 mutable llvm::BumpPtrAllocator BumpAlloc;
564 /// Allocator for partial diagnostics.
565 PartialDiagnostic::StorageAllocator DiagAllocator;
567 /// The current C++ ABI.
568 std::unique_ptr<CXXABI> ABI;
569 CXXABI *createCXXABI(const TargetInfo &T);
571 /// The logical -> physical address space map.
572 const LangASMap *AddrSpaceMap = nullptr;
574 /// Address space map mangling must be used with language specific
575 /// address spaces (e.g. OpenCL/CUDA)
576 bool AddrSpaceMapMangling;
578 const TargetInfo *Target = nullptr;
579 const TargetInfo *AuxTarget = nullptr;
580 clang::PrintingPolicy PrintingPolicy;
581 std::unique_ptr<interp::Context> InterpContext;
582 std::unique_ptr<ParentMapContext> ParentMapCtx;
585 IdentifierTable &Idents;
586 SelectorTable &Selectors;
587 Builtin::Context &BuiltinInfo;
588 mutable DeclarationNameTable DeclarationNames;
589 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
590 ASTMutationListener *Listener = nullptr;
592 /// Returns the clang bytecode interpreter context.
593 interp::Context &getInterpContext();
595 /// Returns the dynamic AST node parent map context.
596 ParentMapContext &getParentMapContext();
598 // A traversal scope limits the parts of the AST visible to certain analyses.
599 // RecursiveASTVisitor::TraverseAST will only visit reachable nodes, and
600 // getParents() will only observe reachable parent edges.
602 // The scope is defined by a set of "top-level" declarations.
603 // Initially, it is the entire TU: {getTranslationUnitDecl()}.
604 // Changing the scope clears the parent cache, which is expensive to rebuild.
605 std::vector<Decl *> getTraversalScope() const { return TraversalScope; }
606 void setTraversalScope(const std::vector<Decl *> &);
608 /// Forwards to get node parents from the ParentMapContext. New callers should
609 /// use ParentMapContext::getParents() directly.
610 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node);
612 const clang::PrintingPolicy &getPrintingPolicy() const {
613 return PrintingPolicy;
616 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
617 PrintingPolicy = Policy;
620 SourceManager& getSourceManager() { return SourceMgr; }
621 const SourceManager& getSourceManager() const { return SourceMgr; }
623 llvm::BumpPtrAllocator &getAllocator() const {
627 void *Allocate(size_t Size, unsigned Align = 8) const {
628 return BumpAlloc.Allocate(Size, Align);
630 template <typename T> T *Allocate(size_t Num = 1) const {
631 return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
633 void Deallocate(void *Ptr) const {}
635 /// Return the total amount of physical memory allocated for representing
636 /// AST nodes and type information.
637 size_t getASTAllocatedMemory() const {
638 return BumpAlloc.getTotalMemory();
641 /// Return the total memory used for various side tables.
642 size_t getSideTableAllocatedMemory() const;
644 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
645 return DiagAllocator;
648 const TargetInfo &getTargetInfo() const { return *Target; }
649 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
651 /// getIntTypeForBitwidth -
652 /// sets integer QualTy according to specified details:
653 /// bitwidth, signed/unsigned.
654 /// Returns empty type if there is no appropriate target types.
655 QualType getIntTypeForBitwidth(unsigned DestWidth,
656 unsigned Signed) const;
658 /// getRealTypeForBitwidth -
659 /// sets floating point QualTy according to specified bitwidth.
660 /// Returns empty type if there is no appropriate target types.
661 QualType getRealTypeForBitwidth(unsigned DestWidth, bool ExplicitIEEE) const;
663 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
665 const LangOptions& getLangOpts() const { return LangOpts; }
667 const SanitizerBlacklist &getSanitizerBlacklist() const {
671 const XRayFunctionFilter &getXRayFilter() const {
675 DiagnosticsEngine &getDiagnostics() const;
677 FullSourceLoc getFullLoc(SourceLocation Loc) const {
678 return FullSourceLoc(Loc,SourceMgr);
681 /// All comments in this translation unit.
682 RawCommentList Comments;
684 /// True if comments are already loaded from ExternalASTSource.
685 mutable bool CommentsLoaded = false;
687 /// Mapping from declaration to directly attached comment.
689 /// Raw comments are owned by Comments list. This mapping is populated
691 mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments;
693 /// Mapping from canonical declaration to the first redeclaration in chain
694 /// that has a comment attached.
696 /// Raw comments are owned by Comments list. This mapping is populated
698 mutable llvm::DenseMap<const Decl *, const Decl *> RedeclChainComments;
700 /// Keeps track of redeclaration chains that don't have any comment attached.
701 /// Mapping from canonical declaration to redeclaration chain that has no
702 /// comments attached to any redeclaration. Specifically it's mapping to
703 /// the last redeclaration we've checked.
705 /// Shall not contain declarations that have comments attached to any
706 /// redeclaration in their chain.
707 mutable llvm::DenseMap<const Decl *, const Decl *> CommentlessRedeclChains;
709 /// Mapping from declarations to parsed comments attached to any
711 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
713 /// Attaches \p Comment to \p OriginalD and to its redeclaration chain
714 /// and removes the redeclaration chain from the set of commentless chains.
716 /// Don't do anything if a comment has already been attached to \p OriginalD
717 /// or its redeclaration chain.
718 void cacheRawCommentForDecl(const Decl &OriginalD,
719 const RawComment &Comment) const;
721 /// \returns searches \p CommentsInFile for doc comment for \p D.
723 /// \p RepresentativeLocForDecl is used as a location for searching doc
724 /// comments. \p CommentsInFile is a mapping offset -> comment of files in the
725 /// same file where \p RepresentativeLocForDecl is.
726 RawComment *getRawCommentForDeclNoCacheImpl(
727 const Decl *D, const SourceLocation RepresentativeLocForDecl,
728 const std::map<unsigned, RawComment *> &CommentsInFile) const;
730 /// Return the documentation comment attached to a given declaration,
731 /// without looking into cache.
732 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
735 void addComment(const RawComment &RC);
737 /// Return the documentation comment attached to a given declaration.
738 /// Returns nullptr if no comment is attached.
740 /// \param OriginalDecl if not nullptr, is set to declaration AST node that
741 /// had the comment, if the comment we found comes from a redeclaration.
743 getRawCommentForAnyRedecl(const Decl *D,
744 const Decl **OriginalDecl = nullptr) const;
746 /// Searches existing comments for doc comments that should be attached to \p
747 /// Decls. If any doc comment is found, it is parsed.
749 /// Requirement: All \p Decls are in the same file.
751 /// If the last comment in the file is already attached we assume
752 /// there are not comments left to be attached to \p Decls.
753 void attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
754 const Preprocessor *PP);
756 /// Return parsed documentation comment attached to a given declaration.
757 /// Returns nullptr if no comment is attached.
759 /// \param PP the Preprocessor used with this TU. Could be nullptr if
760 /// preprocessor is not available.
761 comments::FullComment *getCommentForDecl(const Decl *D,
762 const Preprocessor *PP) const;
764 /// Return parsed documentation comment attached to a given declaration.
765 /// Returns nullptr if no comment is attached. Does not look at any
766 /// redeclarations of the declaration.
767 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
769 comments::FullComment *cloneFullComment(comments::FullComment *FC,
770 const Decl *D) const;
773 mutable comments::CommandTraits CommentCommandTraits;
775 /// Iterator that visits import declarations.
776 class import_iterator {
777 ImportDecl *Import = nullptr;
780 using value_type = ImportDecl *;
781 using reference = ImportDecl *;
782 using pointer = ImportDecl *;
783 using difference_type = int;
784 using iterator_category = std::forward_iterator_tag;
786 import_iterator() = default;
787 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
789 reference operator*() const { return Import; }
790 pointer operator->() const { return Import; }
792 import_iterator &operator++() {
793 Import = ASTContext::getNextLocalImport(Import);
797 import_iterator operator++(int) {
798 import_iterator Other(*this);
803 friend bool operator==(import_iterator X, import_iterator Y) {
804 return X.Import == Y.Import;
807 friend bool operator!=(import_iterator X, import_iterator Y) {
808 return X.Import != Y.Import;
813 comments::CommandTraits &getCommentCommandTraits() const {
814 return CommentCommandTraits;
817 /// Retrieve the attributes for the given declaration.
818 AttrVec& getDeclAttrs(const Decl *D);
820 /// Erase the attributes corresponding to the given declaration.
821 void eraseDeclAttrs(const Decl *D);
823 /// If this variable is an instantiated static data member of a
824 /// class template specialization, returns the templated static data member
825 /// from which it was instantiated.
827 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
830 TemplateOrSpecializationInfo
831 getTemplateOrSpecializationInfo(const VarDecl *Var);
833 /// Note that the static data member \p Inst is an instantiation of
834 /// the static data member template \p Tmpl of a class template.
835 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
836 TemplateSpecializationKind TSK,
837 SourceLocation PointOfInstantiation = SourceLocation());
839 void setTemplateOrSpecializationInfo(VarDecl *Inst,
840 TemplateOrSpecializationInfo TSI);
842 /// If the given using decl \p Inst is an instantiation of a
843 /// (possibly unresolved) using decl from a template instantiation,
845 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
847 /// Remember that the using decl \p Inst is an instantiation
848 /// of the using decl \p Pattern of a class template.
849 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
851 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
852 UsingShadowDecl *Pattern);
853 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
855 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
857 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
859 // Access to the set of methods overridden by the given C++ method.
860 using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
861 overridden_cxx_method_iterator
862 overridden_methods_begin(const CXXMethodDecl *Method) const;
864 overridden_cxx_method_iterator
865 overridden_methods_end(const CXXMethodDecl *Method) const;
867 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
869 using overridden_method_range =
870 llvm::iterator_range<overridden_cxx_method_iterator>;
872 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
874 /// Note that the given C++ \p Method overrides the given \p
875 /// Overridden method.
876 void addOverriddenMethod(const CXXMethodDecl *Method,
877 const CXXMethodDecl *Overridden);
879 /// Return C++ or ObjC overridden methods for the given \p Method.
881 /// An ObjC method is considered to override any method in the class's
882 /// base classes, its protocols, or its categories' protocols, that has
883 /// the same selector and is of the same kind (class or instance).
884 /// A method in an implementation is not considered as overriding the same
885 /// method in the interface or its categories.
886 void getOverriddenMethods(
887 const NamedDecl *Method,
888 SmallVectorImpl<const NamedDecl *> &Overridden) const;
890 /// Notify the AST context that a new import declaration has been
891 /// parsed or implicitly created within this translation unit.
892 void addedLocalImportDecl(ImportDecl *Import);
894 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
895 return Import->getNextLocalImport();
898 using import_range = llvm::iterator_range<import_iterator>;
900 import_range local_imports() const {
901 return import_range(import_iterator(FirstLocalImport), import_iterator());
904 Decl *getPrimaryMergedDecl(Decl *D) {
905 Decl *Result = MergedDecls.lookup(D);
906 return Result ? Result : D;
908 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
909 MergedDecls[D] = Primary;
912 /// Note that the definition \p ND has been merged into module \p M,
913 /// and should be visible whenever \p M is visible.
914 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
915 bool NotifyListeners = true);
917 /// Clean up the merged definition list. Call this if you might have
918 /// added duplicates into the list.
919 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
921 /// Get the additional modules in which the definition \p Def has
923 ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def);
925 /// Add a declaration to the list of declarations that are initialized
926 /// for a module. This will typically be a global variable (with internal
927 /// linkage) that runs module initializers, such as the iostream initializer,
928 /// or an ImportDecl nominating another module that has initializers.
929 void addModuleInitializer(Module *M, Decl *Init);
931 void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs);
933 /// Get the initializations to perform when importing a module, if any.
934 ArrayRef<Decl*> getModuleInitializers(Module *M);
936 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
938 ExternCContextDecl *getExternCContextDecl() const;
939 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
940 BuiltinTemplateDecl *getTypePackElementDecl() const;
946 CanQualType WCharTy; // [C++ 3.9.1p5].
947 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
948 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
949 CanQualType Char8Ty; // [C++20 proposal]
950 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
951 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
952 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
953 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
954 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
955 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty;
956 CanQualType ShortAccumTy, AccumTy,
957 LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension
958 CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
959 CanQualType ShortFractTy, FractTy, LongFractTy;
960 CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
961 CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy;
962 CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy,
963 SatUnsignedLongAccumTy;
964 CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
965 CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
966 SatUnsignedLongFractTy;
967 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
968 CanQualType BFloat16Ty;
969 CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
970 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
971 CanQualType Float128ComplexTy;
972 CanQualType VoidPtrTy, NullPtrTy;
973 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
974 CanQualType BuiltinFnTy;
975 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
976 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
977 CanQualType ObjCBuiltinBoolTy;
978 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
979 CanQualType SingletonId;
980 #include "clang/Basic/OpenCLImageTypes.def"
981 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
982 CanQualType OCLQueueTy, OCLReserveIDTy;
983 CanQualType IncompleteMatrixIdxTy;
984 CanQualType OMPArraySectionTy, OMPArrayShapingTy, OMPIteratorTy;
985 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
987 #include "clang/Basic/OpenCLExtensionTypes.def"
988 #define SVE_TYPE(Name, Id, SingletonId) \
989 CanQualType SingletonId;
990 #include "clang/Basic/AArch64SVEACLETypes.def"
992 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
993 mutable QualType AutoDeductTy; // Deduction against 'auto'.
994 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
996 // Decl used to help define __builtin_va_list for some targets.
997 // The decl is built when constructing 'BuiltinVaListDecl'.
998 mutable Decl *VaListTagDecl = nullptr;
1000 // Implicitly-declared type 'struct _GUID'.
1001 mutable TagDecl *MSGuidTagDecl = nullptr;
1003 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1004 SelectorTable &sels, Builtin::Context &builtins);
1005 ASTContext(const ASTContext &) = delete;
1006 ASTContext &operator=(const ASTContext &) = delete;
1009 /// Attach an external AST source to the AST context.
1011 /// The external AST source provides the ability to load parts of
1012 /// the abstract syntax tree as needed from some external storage,
1013 /// e.g., a precompiled header.
1014 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1016 /// Retrieve a pointer to the external AST source associated
1017 /// with this AST context, if any.
1018 ExternalASTSource *getExternalSource() const {
1019 return ExternalSource.get();
1022 /// Attach an AST mutation listener to the AST context.
1024 /// The AST mutation listener provides the ability to track modifications to
1025 /// the abstract syntax tree entities committed after they were initially
1027 void setASTMutationListener(ASTMutationListener *Listener) {
1028 this->Listener = Listener;
1031 /// Retrieve a pointer to the AST mutation listener associated
1032 /// with this AST context, if any.
1033 ASTMutationListener *getASTMutationListener() const { return Listener; }
1035 void PrintStats() const;
1036 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1038 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1039 const IdentifierInfo *II) const;
1041 /// Create a new implicit TU-level CXXRecordDecl or RecordDecl
1043 RecordDecl *buildImplicitRecord(StringRef Name,
1044 RecordDecl::TagKind TK = TTK_Struct) const;
1046 /// Create a new implicit TU-level typedef declaration.
1047 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1049 /// Retrieve the declaration for the 128-bit signed integer type.
1050 TypedefDecl *getInt128Decl() const;
1052 /// Retrieve the declaration for the 128-bit unsigned integer type.
1053 TypedefDecl *getUInt128Decl() const;
1055 //===--------------------------------------------------------------------===//
1056 // Type Constructors
1057 //===--------------------------------------------------------------------===//
1060 /// Return a type with extended qualifiers.
1061 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1063 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1065 QualType getPipeType(QualType T, bool ReadOnly) const;
1068 /// Return the uniqued reference to the type for an address space
1069 /// qualified type with the specified type and address space.
1071 /// The resulting type has a union of the qualifiers from T and the address
1072 /// space. If T already has an address space specifier, it is silently
1074 QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
1076 /// Remove any existing address space on the type and returns the type
1077 /// with qualifiers intact (or that's the idea anyway)
1079 /// The return type should be T with all prior qualifiers minus the address
1081 QualType removeAddrSpaceQualType(QualType T) const;
1083 /// Apply Objective-C protocol qualifiers to the given type.
1084 /// \param allowOnPointerType specifies if we can apply protocol
1085 /// qualifiers on ObjCObjectPointerType. It can be set to true when
1086 /// constructing the canonical type of a Objective-C type parameter.
1087 QualType applyObjCProtocolQualifiers(QualType type,
1088 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1089 bool allowOnPointerType = false) const;
1091 /// Return the uniqued reference to the type for an Objective-C
1092 /// gc-qualified type.
1094 /// The resulting type has a union of the qualifiers from T and the gc
1096 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1098 /// Remove the existing address space on the type if it is a pointer size
1099 /// address space and return the type with qualifiers intact.
1100 QualType removePtrSizeAddrSpace(QualType T) const;
1102 /// Return the uniqued reference to the type for a \c restrict
1105 /// The resulting type has a union of the qualifiers from \p T and
1107 QualType getRestrictType(QualType T) const {
1108 return T.withFastQualifiers(Qualifiers::Restrict);
1111 /// Return the uniqued reference to the type for a \c volatile
1114 /// The resulting type has a union of the qualifiers from \p T and
1116 QualType getVolatileType(QualType T) const {
1117 return T.withFastQualifiers(Qualifiers::Volatile);
1120 /// Return the uniqued reference to the type for a \c const
1123 /// The resulting type has a union of the qualifiers from \p T and \c const.
1125 /// It can be reasonably expected that this will always be equivalent to
1126 /// calling T.withConst().
1127 QualType getConstType(QualType T) const { return T.withConst(); }
1129 /// Change the ExtInfo on a function type.
1130 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1131 FunctionType::ExtInfo EInfo);
1133 /// Adjust the given function result type.
1134 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1136 /// Change the result type of a function type once it is deduced.
1137 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1139 /// Get a function type and produce the equivalent function type with the
1140 /// specified exception specification. Type sugar that can be present on a
1141 /// declaration of a function with an exception specification is permitted
1142 /// and preserved. Other type sugar (for instance, typedefs) is not.
1143 QualType getFunctionTypeWithExceptionSpec(
1144 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI);
1146 /// Determine whether two function types are the same, ignoring
1147 /// exception specifications in cases where they're part of the type.
1148 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U);
1150 /// Change the exception specification on a function once it is
1151 /// delay-parsed, instantiated, or computed.
1152 void adjustExceptionSpec(FunctionDecl *FD,
1153 const FunctionProtoType::ExceptionSpecInfo &ESI,
1154 bool AsWritten = false);
1156 /// Get a function type and produce the equivalent function type where
1157 /// pointer size address spaces in the return type and parameter tyeps are
1158 /// replaced with the default address space.
1159 QualType getFunctionTypeWithoutPtrSizes(QualType T);
1161 /// Determine whether two function types are the same, ignoring pointer sizes
1162 /// in the return type and parameter types.
1163 bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U);
1165 /// Return the uniqued reference to the type for a complex
1166 /// number with the specified element type.
1167 QualType getComplexType(QualType T) const;
1168 CanQualType getComplexType(CanQualType T) const {
1169 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1172 /// Return the uniqued reference to the type for a pointer to
1173 /// the specified type.
1174 QualType getPointerType(QualType T) const;
1175 CanQualType getPointerType(CanQualType T) const {
1176 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1179 /// Return the uniqued reference to a type adjusted from the original
1180 /// type to a new type.
1181 QualType getAdjustedType(QualType Orig, QualType New) const;
1182 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1183 return CanQualType::CreateUnsafe(
1184 getAdjustedType((QualType)Orig, (QualType)New));
1187 /// Return the uniqued reference to the decayed version of the given
1188 /// type. Can only be called on array and function types which decay to
1190 QualType getDecayedType(QualType T) const;
1191 CanQualType getDecayedType(CanQualType T) const {
1192 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1195 /// Return the uniqued reference to the atomic type for the specified
1197 QualType getAtomicType(QualType T) const;
1199 /// Return the uniqued reference to the type for a block of the
1201 QualType getBlockPointerType(QualType T) const;
1203 /// Gets the struct used to keep track of the descriptor for pointer to
1205 QualType getBlockDescriptorType() const;
1207 /// Return a read_only pipe type for the specified type.
1208 QualType getReadPipeType(QualType T) const;
1210 /// Return a write_only pipe type for the specified type.
1211 QualType getWritePipeType(QualType T) const;
1213 /// Return an extended integer type with the specified signedness and bit
1215 QualType getExtIntType(bool Unsigned, unsigned NumBits) const;
1217 /// Return a dependent extended integer type with the specified signedness and
1219 QualType getDependentExtIntType(bool Unsigned, Expr *BitsExpr) const;
1221 /// Gets the struct used to keep track of the extended descriptor for
1222 /// pointer to blocks.
1223 QualType getBlockDescriptorExtendedType() const;
1225 /// Map an AST Type to an OpenCLTypeKind enum value.
1226 OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
1228 /// Get address space for OpenCL type.
1229 LangAS getOpenCLTypeAddrSpace(const Type *T) const;
1231 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1232 cudaConfigureCallDecl = FD;
1235 FunctionDecl *getcudaConfigureCallDecl() {
1236 return cudaConfigureCallDecl;
1239 /// Returns true iff we need copy/dispose helpers for the given type.
1240 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1242 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
1243 /// is set to false in this case. If HasByrefExtendedLayout returns true,
1244 /// byref variable has extended lifetime.
1245 bool getByrefLifetime(QualType Ty,
1246 Qualifiers::ObjCLifetime &Lifetime,
1247 bool &HasByrefExtendedLayout) const;
1249 /// Return the uniqued reference to the type for an lvalue reference
1250 /// to the specified type.
1251 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1254 /// Return the uniqued reference to the type for an rvalue reference
1255 /// to the specified type.
1256 QualType getRValueReferenceType(QualType T) const;
1258 /// Return the uniqued reference to the type for a member pointer to
1259 /// the specified type in the specified class.
1261 /// The class \p Cls is a \c Type because it could be a dependent name.
1262 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1264 /// Return a non-unique reference to the type for a variable array of
1265 /// the specified element type.
1266 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1267 ArrayType::ArraySizeModifier ASM,
1268 unsigned IndexTypeQuals,
1269 SourceRange Brackets) const;
1271 /// Return a non-unique reference to the type for a dependently-sized
1272 /// array of the specified element type.
1274 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1276 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1277 ArrayType::ArraySizeModifier ASM,
1278 unsigned IndexTypeQuals,
1279 SourceRange Brackets) const;
1281 /// Return a unique reference to the type for an incomplete array of
1282 /// the specified element type.
1283 QualType getIncompleteArrayType(QualType EltTy,
1284 ArrayType::ArraySizeModifier ASM,
1285 unsigned IndexTypeQuals) const;
1287 /// Return the unique reference to the type for a constant array of
1288 /// the specified element type.
1289 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1290 const Expr *SizeExpr,
1291 ArrayType::ArraySizeModifier ASM,
1292 unsigned IndexTypeQuals) const;
1294 /// Return a type for a constant array for a string literal of the
1295 /// specified element type and length.
1296 QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const;
1298 /// Returns a vla type where known sizes are replaced with [*].
1299 QualType getVariableArrayDecayedType(QualType Ty) const;
1301 // Convenience struct to return information about a builtin vector type.
1302 struct BuiltinVectorTypeInfo {
1303 QualType ElementType;
1304 llvm::ElementCount EC;
1305 unsigned NumVectors;
1306 BuiltinVectorTypeInfo(QualType ElementType, llvm::ElementCount EC,
1307 unsigned NumVectors)
1308 : ElementType(ElementType), EC(EC), NumVectors(NumVectors) {}
1311 /// Returns the element type, element count and number of vectors
1312 /// (in case of tuple) for a builtin vector type.
1313 BuiltinVectorTypeInfo
1314 getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const;
1316 /// Return the unique reference to a scalable vector type of the specified
1317 /// element type and scalable number of elements.
1319 /// \pre \p EltTy must be a built-in type.
1320 QualType getScalableVectorType(QualType EltTy, unsigned NumElts) const;
1322 /// Return the unique reference to a vector type of the specified
1323 /// element type and size.
1325 /// \pre \p VectorType must be a built-in type.
1326 QualType getVectorType(QualType VectorType, unsigned NumElts,
1327 VectorType::VectorKind VecKind) const;
1328 /// Return the unique reference to the type for a dependently sized vector of
1329 /// the specified element type.
1330 QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr,
1331 SourceLocation AttrLoc,
1332 VectorType::VectorKind VecKind) const;
1334 /// Return the unique reference to an extended vector type
1335 /// of the specified element type and size.
1337 /// \pre \p VectorType must be a built-in type.
1338 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1340 /// \pre Return a non-unique reference to the type for a dependently-sized
1341 /// vector of the specified element type.
1343 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1345 QualType getDependentSizedExtVectorType(QualType VectorType,
1347 SourceLocation AttrLoc) const;
1349 /// Return the unique reference to the matrix type of the specified element
1352 /// \pre \p ElementType must be a valid matrix element type (see
1353 /// MatrixType::isValidElementType).
1354 QualType getConstantMatrixType(QualType ElementType, unsigned NumRows,
1355 unsigned NumColumns) const;
1357 /// Return the unique reference to the matrix type of the specified element
1359 QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
1361 SourceLocation AttrLoc) const;
1363 QualType getDependentAddressSpaceType(QualType PointeeType,
1364 Expr *AddrSpaceExpr,
1365 SourceLocation AttrLoc) const;
1367 /// Return a K&R style C function type like 'int()'.
1368 QualType getFunctionNoProtoType(QualType ResultTy,
1369 const FunctionType::ExtInfo &Info) const;
1371 QualType getFunctionNoProtoType(QualType ResultTy) const {
1372 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1375 /// Return a normal function type with a typed argument list.
1376 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1377 const FunctionProtoType::ExtProtoInfo &EPI) const {
1378 return getFunctionTypeInternal(ResultTy, Args, EPI, false);
1381 QualType adjustStringLiteralBaseType(QualType StrLTy) const;
1384 /// Return a normal function type with a typed argument list.
1385 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1386 const FunctionProtoType::ExtProtoInfo &EPI,
1387 bool OnlyWantCanonical) const;
1390 /// Return the unique reference to the type for the specified type
1392 QualType getTypeDeclType(const TypeDecl *Decl,
1393 const TypeDecl *PrevDecl = nullptr) const {
1394 assert(Decl && "Passed null for Decl param");
1395 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1398 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1399 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1400 return QualType(PrevDecl->TypeForDecl, 0);
1403 return getTypeDeclTypeSlow(Decl);
1406 /// Return the unique reference to the type for the specified
1407 /// typedef-name decl.
1408 QualType getTypedefType(const TypedefNameDecl *Decl,
1409 QualType Canon = QualType()) const;
1411 QualType getRecordType(const RecordDecl *Decl) const;
1413 QualType getEnumType(const EnumDecl *Decl) const;
1415 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1417 QualType getAttributedType(attr::Kind attrKind,
1418 QualType modifiedType,
1419 QualType equivalentType);
1421 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1422 QualType Replacement) const;
1423 QualType getSubstTemplateTypeParmPackType(
1424 const TemplateTypeParmType *Replaced,
1425 const TemplateArgument &ArgPack);
1428 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1430 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1432 QualType getTemplateSpecializationType(TemplateName T,
1433 ArrayRef<TemplateArgument> Args,
1434 QualType Canon = QualType()) const;
1437 getCanonicalTemplateSpecializationType(TemplateName T,
1438 ArrayRef<TemplateArgument> Args) const;
1440 QualType getTemplateSpecializationType(TemplateName T,
1441 const TemplateArgumentListInfo &Args,
1442 QualType Canon = QualType()) const;
1445 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1446 const TemplateArgumentListInfo &Args,
1447 QualType Canon = QualType()) const;
1449 QualType getParenType(QualType NamedType) const;
1451 QualType getMacroQualifiedType(QualType UnderlyingTy,
1452 const IdentifierInfo *MacroII) const;
1454 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1455 NestedNameSpecifier *NNS, QualType NamedType,
1456 TagDecl *OwnedTagDecl = nullptr) const;
1457 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1458 NestedNameSpecifier *NNS,
1459 const IdentifierInfo *Name,
1460 QualType Canon = QualType()) const;
1462 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1463 NestedNameSpecifier *NNS,
1464 const IdentifierInfo *Name,
1465 const TemplateArgumentListInfo &Args) const;
1466 QualType getDependentTemplateSpecializationType(
1467 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1468 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1470 TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
1472 /// Get a template argument list with one argument per template parameter
1473 /// in a template parameter list, such as for the injected class name of
1474 /// a class template.
1475 void getInjectedTemplateArgs(const TemplateParameterList *Params,
1476 SmallVectorImpl<TemplateArgument> &Args);
1478 QualType getPackExpansionType(QualType Pattern,
1479 Optional<unsigned> NumExpansions);
1481 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1482 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1484 /// Legacy interface: cannot provide type arguments or __kindof.
1485 QualType getObjCObjectType(QualType Base,
1486 ObjCProtocolDecl * const *Protocols,
1487 unsigned NumProtocols) const;
1489 QualType getObjCObjectType(QualType Base,
1490 ArrayRef<QualType> typeArgs,
1491 ArrayRef<ObjCProtocolDecl *> protocols,
1492 bool isKindOf) const;
1494 QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1495 ArrayRef<ObjCProtocolDecl *> protocols) const;
1496 void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
1497 ObjCTypeParamDecl *New) 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, bool IsPack = false,
1524 ConceptDecl *TypeConstraintConcept = nullptr,
1525 ArrayRef<TemplateArgument> TypeConstraintArgs ={}) const;
1527 /// C++11 deduction pattern for 'auto' type.
1528 QualType getAutoDeductType() const;
1530 /// C++11 deduction pattern for 'auto &&' type.
1531 QualType getAutoRRefDeductType() const;
1533 /// C++17 deduced class template specialization type.
1534 QualType getDeducedTemplateSpecializationType(TemplateName Template,
1535 QualType DeducedType,
1536 bool IsDependent) const;
1538 /// Return the unique reference to the type for the specified TagDecl
1539 /// (struct/union/class/enum) decl.
1540 QualType getTagDeclType(const TagDecl *Decl) const;
1542 /// Return the unique type for "size_t" (C99 7.17), defined in
1545 /// The sizeof operator requires this (C99 6.5.3.4p4).
1546 CanQualType getSizeType() const;
1548 /// Return the unique signed counterpart of
1549 /// the integer type corresponding to size_t.
1550 CanQualType getSignedSizeType() const;
1552 /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1554 CanQualType getIntMaxType() const;
1556 /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1558 CanQualType getUIntMaxType() const;
1560 /// Return the unique wchar_t type available in C++ (and available as
1561 /// __wchar_t as a Microsoft extension).
1562 QualType getWCharType() const { return WCharTy; }
1564 /// Return the type of wide characters. In C++, this returns the
1565 /// unique wchar_t type. In C99, this returns a type compatible with the type
1566 /// defined in <stddef.h> as defined by the target.
1567 QualType getWideCharType() const { return WideCharTy; }
1569 /// Return the type of "signed wchar_t".
1571 /// Used when in C++, as a GCC extension.
1572 QualType getSignedWCharType() const;
1574 /// Return the type of "unsigned wchar_t".
1576 /// Used when in C++, as a GCC extension.
1577 QualType getUnsignedWCharType() const;
1579 /// In C99, this returns a type compatible with the type
1580 /// defined in <stddef.h> as defined by the target.
1581 QualType getWIntType() const { return WIntTy; }
1583 /// Return a type compatible with "intptr_t" (C99 7.18.1.4),
1584 /// as defined by the target.
1585 QualType getIntPtrType() const;
1587 /// Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1588 /// as defined by the target.
1589 QualType getUIntPtrType() const;
1591 /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1592 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1593 QualType getPointerDiffType() const;
1595 /// Return the unique unsigned counterpart of "ptrdiff_t"
1596 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
1597 /// in the definition of %tu format specifier.
1598 QualType getUnsignedPointerDiffType() const;
1600 /// Return the unique type for "pid_t" defined in
1601 /// <sys/types.h>. We need this to compute the correct type for vfork().
1602 QualType getProcessIDType() const;
1604 /// Return the C structure type used to represent constant CFStrings.
1605 QualType getCFConstantStringType() const;
1607 /// Returns the C struct type for objc_super
1608 QualType getObjCSuperType() const;
1609 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1611 /// Get the structure type used to representation CFStrings, or NULL
1612 /// if it hasn't yet been built.
1613 QualType getRawCFConstantStringType() const {
1614 if (CFConstantStringTypeDecl)
1615 return getTypedefType(CFConstantStringTypeDecl);
1618 void setCFConstantStringType(QualType T);
1619 TypedefDecl *getCFConstantStringDecl() const;
1620 RecordDecl *getCFConstantStringTagDecl() const;
1622 // This setter/getter represents the ObjC type for an NSConstantString.
1623 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1624 QualType getObjCConstantStringInterface() const {
1625 return ObjCConstantStringType;
1628 QualType getObjCNSStringType() const {
1629 return ObjCNSStringType;
1632 void setObjCNSStringType(QualType T) {
1633 ObjCNSStringType = T;
1636 /// Retrieve the type that \c id has been defined to, which may be
1637 /// different from the built-in \c id if \c id has been typedef'd.
1638 QualType getObjCIdRedefinitionType() const {
1639 if (ObjCIdRedefinitionType.isNull())
1640 return getObjCIdType();
1641 return ObjCIdRedefinitionType;
1644 /// Set the user-written type that redefines \c id.
1645 void setObjCIdRedefinitionType(QualType RedefType) {
1646 ObjCIdRedefinitionType = RedefType;
1649 /// Retrieve the type that \c Class has been defined to, which may be
1650 /// different from the built-in \c Class if \c Class has been typedef'd.
1651 QualType getObjCClassRedefinitionType() const {
1652 if (ObjCClassRedefinitionType.isNull())
1653 return getObjCClassType();
1654 return ObjCClassRedefinitionType;
1657 /// Set the user-written type that redefines 'SEL'.
1658 void setObjCClassRedefinitionType(QualType RedefType) {
1659 ObjCClassRedefinitionType = RedefType;
1662 /// Retrieve the type that 'SEL' has been defined to, which may be
1663 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1664 QualType getObjCSelRedefinitionType() const {
1665 if (ObjCSelRedefinitionType.isNull())
1666 return getObjCSelType();
1667 return ObjCSelRedefinitionType;
1670 /// Set the user-written type that redefines 'SEL'.
1671 void setObjCSelRedefinitionType(QualType RedefType) {
1672 ObjCSelRedefinitionType = RedefType;
1675 /// Retrieve the identifier 'NSObject'.
1676 IdentifierInfo *getNSObjectName() const {
1677 if (!NSObjectName) {
1678 NSObjectName = &Idents.get("NSObject");
1681 return NSObjectName;
1684 /// Retrieve the identifier 'NSCopying'.
1685 IdentifierInfo *getNSCopyingName() {
1686 if (!NSCopyingName) {
1687 NSCopyingName = &Idents.get("NSCopying");
1690 return NSCopyingName;
1693 CanQualType getNSUIntegerType() const;
1695 CanQualType getNSIntegerType() const;
1697 /// Retrieve the identifier 'bool'.
1698 IdentifierInfo *getBoolName() const {
1700 BoolName = &Idents.get("bool");
1704 IdentifierInfo *getMakeIntegerSeqName() const {
1705 if (!MakeIntegerSeqName)
1706 MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1707 return MakeIntegerSeqName;
1710 IdentifierInfo *getTypePackElementName() const {
1711 if (!TypePackElementName)
1712 TypePackElementName = &Idents.get("__type_pack_element");
1713 return TypePackElementName;
1716 /// Retrieve the Objective-C "instancetype" type, if already known;
1717 /// otherwise, returns a NULL type;
1718 QualType getObjCInstanceType() {
1719 return getTypeDeclType(getObjCInstanceTypeDecl());
1722 /// Retrieve the typedef declaration corresponding to the Objective-C
1723 /// "instancetype" type.
1724 TypedefDecl *getObjCInstanceTypeDecl();
1726 /// Set the type for the C FILE type.
1727 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1729 /// Retrieve the C FILE type.
1730 QualType getFILEType() const {
1732 return getTypeDeclType(FILEDecl);
1736 /// Set the type for the C jmp_buf type.
1737 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1738 this->jmp_bufDecl = jmp_bufDecl;
1741 /// Retrieve the C jmp_buf type.
1742 QualType getjmp_bufType() const {
1744 return getTypeDeclType(jmp_bufDecl);
1748 /// Set the type for the C sigjmp_buf type.
1749 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1750 this->sigjmp_bufDecl = sigjmp_bufDecl;
1753 /// Retrieve the C sigjmp_buf type.
1754 QualType getsigjmp_bufType() const {
1756 return getTypeDeclType(sigjmp_bufDecl);
1760 /// Set the type for the C ucontext_t type.
1761 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1762 this->ucontext_tDecl = ucontext_tDecl;
1765 /// Retrieve the C ucontext_t type.
1766 QualType getucontext_tType() const {
1768 return getTypeDeclType(ucontext_tDecl);
1772 /// The result type of logical operations, '<', '>', '!=', etc.
1773 QualType getLogicalOperationType() const {
1774 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1777 /// Emit the Objective-CC type encoding for the given type \p T into
1780 /// If \p Field is specified then record field names are also encoded.
1781 void getObjCEncodingForType(QualType T, std::string &S,
1782 const FieldDecl *Field=nullptr,
1783 QualType *NotEncodedT=nullptr) const;
1785 /// Emit the Objective-C property type encoding for the given
1786 /// type \p T into \p S.
1787 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1789 void getLegacyIntegralTypeEncoding(QualType &t) const;
1791 /// Put the string version of the type qualifiers \p QT into \p S.
1792 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1793 std::string &S) const;
1795 /// Emit the encoded type for the function \p Decl into \p S.
1797 /// This is in the same format as Objective-C method encodings.
1799 /// \returns true if an error occurred (e.g., because one of the parameter
1800 /// types is incomplete), false otherwise.
1801 std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
1803 /// Emit the encoded type for the method declaration \p Decl into
1805 std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1806 bool Extended = false) const;
1808 /// Return the encoded type for this block declaration.
1809 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1811 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1812 /// this method declaration. If non-NULL, Container must be either
1813 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1814 /// only be NULL when getting encodings for protocol properties.
1815 std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1816 const Decl *Container) const;
1818 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1819 ObjCProtocolDecl *rProto) const;
1821 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1822 const ObjCPropertyDecl *PD,
1823 const Decl *Container) const;
1825 /// Return the size of type \p T for Objective-C encoding purpose,
1827 CharUnits getObjCEncodingTypeSize(QualType T) const;
1829 /// Retrieve the typedef corresponding to the predefined \c id type
1831 TypedefDecl *getObjCIdDecl() const;
1833 /// Represents the Objective-CC \c id type.
1835 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1836 /// pointer type, a pointer to a struct.
1837 QualType getObjCIdType() const {
1838 return getTypeDeclType(getObjCIdDecl());
1841 /// Retrieve the typedef corresponding to the predefined 'SEL' type
1843 TypedefDecl *getObjCSelDecl() const;
1845 /// Retrieve the type that corresponds to the predefined Objective-C
1847 QualType getObjCSelType() const {
1848 return getTypeDeclType(getObjCSelDecl());
1851 /// Retrieve the typedef declaration corresponding to the predefined
1852 /// Objective-C 'Class' type.
1853 TypedefDecl *getObjCClassDecl() const;
1855 /// Represents the Objective-C \c Class type.
1857 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1858 /// pointer type, a pointer to a struct.
1859 QualType getObjCClassType() const {
1860 return getTypeDeclType(getObjCClassDecl());
1863 /// Retrieve the Objective-C class declaration corresponding to
1864 /// the predefined \c Protocol class.
1865 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1867 /// Retrieve declaration of 'BOOL' typedef
1868 TypedefDecl *getBOOLDecl() const {
1872 /// Save declaration of 'BOOL' typedef
1873 void setBOOLDecl(TypedefDecl *TD) {
1877 /// type of 'BOOL' type.
1878 QualType getBOOLType() const {
1879 return getTypeDeclType(getBOOLDecl());
1882 /// Retrieve the type of the Objective-C \c Protocol class.
1883 QualType getObjCProtoType() const {
1884 return getObjCInterfaceType(getObjCProtocolDecl());
1887 /// Retrieve the C type declaration corresponding to the predefined
1888 /// \c __builtin_va_list type.
1889 TypedefDecl *getBuiltinVaListDecl() const;
1891 /// Retrieve the type of the \c __builtin_va_list type.
1892 QualType getBuiltinVaListType() const {
1893 return getTypeDeclType(getBuiltinVaListDecl());
1896 /// Retrieve the C type declaration corresponding to the predefined
1897 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1898 /// for some targets.
1899 Decl *getVaListTagDecl() const;
1901 /// Retrieve the C type declaration corresponding to the predefined
1902 /// \c __builtin_ms_va_list type.
1903 TypedefDecl *getBuiltinMSVaListDecl() const;
1905 /// Retrieve the type of the \c __builtin_ms_va_list type.
1906 QualType getBuiltinMSVaListType() const {
1907 return getTypeDeclType(getBuiltinMSVaListDecl());
1910 /// Retrieve the implicitly-predeclared 'struct _GUID' declaration.
1911 TagDecl *getMSGuidTagDecl() const { return MSGuidTagDecl; }
1913 /// Retrieve the implicitly-predeclared 'struct _GUID' type.
1914 QualType getMSGuidType() const {
1915 assert(MSGuidTagDecl && "asked for GUID type but MS extensions disabled");
1916 return getTagDeclType(MSGuidTagDecl);
1919 /// Return whether a declaration to a builtin is allowed to be
1920 /// overloaded/redeclared.
1921 bool canBuiltinBeRedeclared(const FunctionDecl *) const;
1923 /// Return a type with additional \c const, \c volatile, or
1924 /// \c restrict qualifiers.
1925 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1926 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1929 /// Un-split a SplitQualType.
1930 QualType getQualifiedType(SplitQualType split) const {
1931 return getQualifiedType(split.Ty, split.Quals);
1934 /// Return a type with additional qualifiers.
1935 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1936 if (!Qs.hasNonFastQualifiers())
1937 return T.withFastQualifiers(Qs.getFastQualifiers());
1938 QualifierCollector Qc(Qs);
1939 const Type *Ptr = Qc.strip(T);
1940 return getExtQualType(Ptr, Qc);
1943 /// Return a type with additional qualifiers.
1944 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1945 if (!Qs.hasNonFastQualifiers())
1946 return QualType(T, Qs.getFastQualifiers());
1947 return getExtQualType(T, Qs);
1950 /// Return a type with the given lifetime qualifier.
1952 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1953 QualType getLifetimeQualifiedType(QualType type,
1954 Qualifiers::ObjCLifetime lifetime) {
1955 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1956 assert(lifetime != Qualifiers::OCL_None);
1959 qs.addObjCLifetime(lifetime);
1960 return getQualifiedType(type, qs);
1963 /// getUnqualifiedObjCPointerType - Returns version of
1964 /// Objective-C pointer type with lifetime qualifier removed.
1965 QualType getUnqualifiedObjCPointerType(QualType type) const {
1966 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1967 !type.getQualifiers().hasObjCLifetime())
1969 Qualifiers Qs = type.getQualifiers();
1970 Qs.removeObjCLifetime();
1971 return getQualifiedType(type.getUnqualifiedType(), Qs);
1974 unsigned char getFixedPointScale(QualType Ty) const;
1975 unsigned char getFixedPointIBits(QualType Ty) const;
1976 FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
1977 APFixedPoint getFixedPointMax(QualType Ty) const;
1978 APFixedPoint getFixedPointMin(QualType Ty) const;
1980 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1981 SourceLocation NameLoc) const;
1983 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1984 UnresolvedSetIterator End) const;
1985 TemplateName getAssumedTemplateName(DeclarationName Name) const;
1987 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1988 bool TemplateKeyword,
1989 TemplateDecl *Template) const;
1991 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1992 const IdentifierInfo *Name) const;
1993 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1994 OverloadedOperatorKind Operator) const;
1995 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1996 TemplateName replacement) const;
1997 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1998 const TemplateArgument &ArgPack) const;
2000 enum GetBuiltinTypeError {
2007 /// Missing a type from <stdio.h>
2010 /// Missing a type from <setjmp.h>
2013 /// Missing a type from <ucontext.h>
2017 /// Return the type for the specified builtin.
2019 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
2020 /// arguments to the builtin that are required to be integer constant
2022 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
2023 unsigned *IntegerConstantArgs = nullptr) const;
2025 /// Types and expressions required to build C++2a three-way comparisons
2026 /// using operator<=>, including the values return by builtin <=> operators.
2027 ComparisonCategories CompCategories;
2030 CanQualType getFromTargetType(unsigned Type) const;
2031 TypeInfo getTypeInfoImpl(const Type *T) const;
2033 //===--------------------------------------------------------------------===//
2035 //===--------------------------------------------------------------------===//
2038 /// Return one of the GCNone, Weak or Strong Objective-C garbage
2039 /// collection attributes.
2040 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
2042 /// Return true if the given vector types are of the same unqualified
2043 /// type or if they are equivalent to the same GCC vector type.
2045 /// \note This ignores whether they are target-specific (AltiVec or Neon)
2047 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
2049 /// Return true if the type has been explicitly qualified with ObjC ownership.
2050 /// A type may be implicitly qualified with ownership under ObjC ARC, and in
2051 /// some cases the compiler treats these differently.
2052 bool hasDirectOwnershipQualifier(QualType Ty) const;
2054 /// Return true if this is an \c NSObject object with its \c NSObject
2056 static bool isObjCNSObjectType(QualType Ty) {
2057 return Ty->isObjCNSObjectType();
2060 //===--------------------------------------------------------------------===//
2061 // Type Sizing and Analysis
2062 //===--------------------------------------------------------------------===//
2064 /// Return the APFloat 'semantics' for the specified scalar floating
2066 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
2068 /// Get the size and alignment of the specified complete type in bits.
2069 TypeInfo getTypeInfo(const Type *T) const;
2070 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
2072 /// Get default simd alignment of the specified complete type in bits.
2073 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
2075 /// Return the size of the specified (complete) type \p T, in bits.
2076 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
2077 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
2079 /// Return the size of the character type, in bits.
2080 uint64_t getCharWidth() const {
2081 return getTypeSize(CharTy);
2084 /// Convert a size in bits to a size in characters.
2085 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
2087 /// Convert a size in characters to a size in bits.
2088 int64_t toBits(CharUnits CharSize) const;
2090 /// Return the size of the specified (complete) type \p T, in
2092 CharUnits getTypeSizeInChars(QualType T) const;
2093 CharUnits getTypeSizeInChars(const Type *T) const;
2095 Optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const {
2096 if (Ty->isIncompleteType() || Ty->isDependentType())
2098 return getTypeSizeInChars(Ty);
2101 Optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const {
2102 return getTypeSizeInCharsIfKnown(QualType(Ty, 0));
2105 /// Return the ABI-specified alignment of a (complete) type \p T, in
2107 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
2108 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
2110 /// Return the ABI-specified natural alignment of a (complete) type \p T,
2111 /// before alignment adjustments, in bits.
2113 /// This alignment is curently used only by ARM and AArch64 when passing
2114 /// arguments of a composite type.
2115 unsigned getTypeUnadjustedAlign(QualType T) const {
2116 return getTypeUnadjustedAlign(T.getTypePtr());
2118 unsigned getTypeUnadjustedAlign(const Type *T) const;
2120 /// Return the ABI-specified alignment of a type, in bits, or 0 if
2121 /// the type is incomplete and we cannot determine the alignment (for
2122 /// example, from alignment attributes).
2123 unsigned getTypeAlignIfKnown(QualType T) const;
2125 /// Return the ABI-specified alignment of a (complete) type \p T, in
2127 CharUnits getTypeAlignInChars(QualType T) const;
2128 CharUnits getTypeAlignInChars(const Type *T) const;
2130 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
2131 /// in characters, before alignment adjustments. This method does not work on
2132 /// incomplete types.
2133 CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
2134 CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
2136 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
2137 // type is a record, its data size is returned.
2138 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
2140 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
2141 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
2143 /// Determine if the alignment the type has was required using an
2144 /// alignment attribute.
2145 bool isAlignmentRequired(const Type *T) const;
2146 bool isAlignmentRequired(QualType T) const;
2148 /// Return the "preferred" alignment of the specified type \p T for
2149 /// the current target, in bits.
2151 /// This can be different than the ABI alignment in cases where it is
2152 /// beneficial for performance to overalign a data type.
2153 unsigned getPreferredTypeAlign(const Type *T) const;
2155 /// Return the default alignment for __attribute__((aligned)) on
2156 /// this target, to be used if no alignment value is specified.
2157 unsigned getTargetDefaultAlignForAttributeAligned() const;
2159 /// Return the alignment in bits that should be given to a
2160 /// global variable with type \p T.
2161 unsigned getAlignOfGlobalVar(QualType T) const;
2163 /// Return the alignment in characters that should be given to a
2164 /// global variable with type \p T.
2165 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
2167 /// Return a conservative estimate of the alignment of the specified
2170 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
2173 /// If \p ForAlignof, references are treated like their underlying type
2174 /// and large arrays don't get any special treatment. If not \p ForAlignof
2175 /// it computes the value expected by CodeGen: references are treated like
2176 /// pointers and large arrays get extra alignment.
2177 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2179 /// Return the alignment (in bytes) of the thrown exception object. This is
2180 /// only meaningful for targets that allocate C++ exceptions in a system
2181 /// runtime, such as those using the Itanium C++ ABI.
2182 CharUnits getExnObjectAlignment() const;
2184 /// Get or compute information about the layout of the specified
2185 /// record (struct/union/class) \p D, which indicates its size and field
2186 /// position information.
2187 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2189 /// Get or compute information about the layout of the specified
2190 /// Objective-C interface.
2191 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2194 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2195 bool Simple = false) const;
2197 /// Get or compute information about the layout of the specified
2198 /// Objective-C implementation.
2200 /// This may differ from the interface if synthesized ivars are present.
2201 const ASTRecordLayout &
2202 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2204 /// Get our current best idea for the key function of the
2205 /// given record decl, or nullptr if there isn't one.
2207 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2208 /// ...the first non-pure virtual function that is not inline at the
2209 /// point of class definition.
2211 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
2212 /// virtual functions that are defined 'inline', which means that
2213 /// the result of this computation can change.
2214 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2216 /// Observe that the given method cannot be a key function.
2217 /// Checks the key-function cache for the method's class and clears it
2218 /// if matches the given declaration.
2220 /// This is used in ABIs where out-of-line definitions marked
2221 /// inline are not considered to be key functions.
2223 /// \param method should be the declaration from the class definition
2224 void setNonKeyFunction(const CXXMethodDecl *method);
2226 /// Loading virtual member pointers using the virtual inheritance model
2227 /// always results in an adjustment using the vbtable even if the index is
2230 /// This is usually OK because the first slot in the vbtable points
2231 /// backwards to the top of the MDC. However, the MDC might be reusing a
2232 /// vbptr from an nv-base. In this case, the first slot in the vbtable
2233 /// points to the start of the nv-base which introduced the vbptr and *not*
2234 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
2235 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2237 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2238 uint64_t getFieldOffset(const ValueDecl *FD) const;
2240 /// Get the offset of an ObjCIvarDecl in bits.
2241 uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2242 const ObjCImplementationDecl *ID,
2243 const ObjCIvarDecl *Ivar) const;
2245 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2247 VTableContextBase *getVTableContext();
2249 /// If \p T is null pointer, assume the target in ASTContext.
2250 MangleContext *createMangleContext(const TargetInfo *T = nullptr);
2252 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2253 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2255 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2256 void CollectInheritedProtocols(const Decl *CDecl,
2257 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2259 /// Return true if the specified type has unique object representations
2260 /// according to (C++17 [meta.unary.prop]p9)
2261 bool hasUniqueObjectRepresentations(QualType Ty) const;
2263 //===--------------------------------------------------------------------===//
2265 //===--------------------------------------------------------------------===//
2267 /// Return the canonical (structural) type corresponding to the
2268 /// specified potentially non-canonical type \p T.
2270 /// The non-canonical version of a type may have many "decorated" versions of
2271 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
2272 /// returned type is guaranteed to be free of any of these, allowing two
2273 /// canonical types to be compared for exact equality with a simple pointer
2275 CanQualType getCanonicalType(QualType T) const {
2276 return CanQualType::CreateUnsafe(T.getCanonicalType());
2279 const Type *getCanonicalType(const Type *T) const {
2280 return T->getCanonicalTypeInternal().getTypePtr();
2283 /// Return the canonical parameter type corresponding to the specific
2284 /// potentially non-canonical one.
2286 /// Qualifiers are stripped off, functions are turned into function
2287 /// pointers, and arrays decay one level into pointers.
2288 CanQualType getCanonicalParamType(QualType T) const;
2290 /// Determine whether the given types \p T1 and \p T2 are equivalent.
2291 bool hasSameType(QualType T1, QualType T2) const {
2292 return getCanonicalType(T1) == getCanonicalType(T2);
2294 bool hasSameType(const Type *T1, const Type *T2) const {
2295 return getCanonicalType(T1) == getCanonicalType(T2);
2298 /// Return this type as a completely-unqualified array type,
2299 /// capturing the qualifiers in \p Quals.
2301 /// This will remove the minimal amount of sugaring from the types, similar
2302 /// to the behavior of QualType::getUnqualifiedType().
2304 /// \param T is the qualified type, which may be an ArrayType
2306 /// \param Quals will receive the full set of qualifiers that were
2307 /// applied to the array.
2309 /// \returns if this is an array type, the completely unqualified array type
2310 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2311 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2313 /// Determine whether the given types are equivalent after
2314 /// cvr-qualifiers have been removed.
2315 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2316 return getCanonicalType(T1).getTypePtr() ==
2317 getCanonicalType(T2).getTypePtr();
2320 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2321 bool IsParam) const {
2322 auto SubTnullability = SubT->getNullability(*this);
2323 auto SuperTnullability = SuperT->getNullability(*this);
2324 if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
2325 // Neither has nullability; return true
2326 if (!SubTnullability)
2328 // Both have nullability qualifier.
2329 if (*SubTnullability == *SuperTnullability ||
2330 *SubTnullability == NullabilityKind::Unspecified ||
2331 *SuperTnullability == NullabilityKind::Unspecified)
2335 // Ok for the superclass method parameter to be "nonnull" and the subclass
2336 // method parameter to be "nullable"
2337 return (*SuperTnullability == NullabilityKind::NonNull &&
2338 *SubTnullability == NullabilityKind::Nullable);
2341 // For the return type, it's okay for the superclass method to specify
2342 // "nullable" and the subclass method specify "nonnull"
2343 return (*SuperTnullability == NullabilityKind::Nullable &&
2344 *SubTnullability == NullabilityKind::NonNull);
2350 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2351 const ObjCMethodDecl *MethodImp);
2353 bool UnwrapSimilarTypes(QualType &T1, QualType &T2);
2354 bool UnwrapSimilarArrayTypes(QualType &T1, QualType &T2);
2356 /// Determine if two types are similar, according to the C++ rules. That is,
2357 /// determine if they are the same other than qualifiers on the initial
2358 /// sequence of pointer / pointer-to-member / array (and in Clang, object
2359 /// pointer) types and their element types.
2361 /// Clang offers a number of qualifiers in addition to the C++ qualifiers;
2362 /// those qualifiers are also ignored in the 'similarity' check.
2363 bool hasSimilarType(QualType T1, QualType T2);
2365 /// Determine if two types are similar, ignoring only CVR qualifiers.
2366 bool hasCvrSimilarType(QualType T1, QualType T2);
2368 /// Retrieves the "canonical" nested name specifier for a
2369 /// given nested name specifier.
2371 /// The canonical nested name specifier is a nested name specifier
2372 /// that uniquely identifies a type or namespace within the type
2373 /// system. For example, given:
2378 /// template<typename T> struct X { typename T* type; };
2382 /// template<typename T> struct Y {
2383 /// typename N::S::X<T>::type member;
2387 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2388 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2389 /// by declarations in the type system and the canonical type for
2390 /// the template type parameter 'T' is template-param-0-0.
2391 NestedNameSpecifier *
2392 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2394 /// Retrieves the default calling convention for the current target.
2395 CallingConv getDefaultCallingConvention(bool IsVariadic,
2397 bool IsBuiltin = false) const;
2399 /// Retrieves the "canonical" template name that refers to a
2402 /// The canonical template name is the simplest expression that can
2403 /// be used to refer to a given template. For most templates, this
2404 /// expression is just the template declaration itself. For example,
2405 /// the template std::vector can be referred to via a variety of
2406 /// names---std::vector, \::std::vector, vector (if vector is in
2407 /// scope), etc.---but all of these names map down to the same
2408 /// TemplateDecl, which is used to form the canonical template name.
2410 /// Dependent template names are more interesting. Here, the
2411 /// template name could be something like T::template apply or
2412 /// std::allocator<T>::template rebind, where the nested name
2413 /// specifier itself is dependent. In this case, the canonical
2414 /// template name uses the shortest form of the dependent
2415 /// nested-name-specifier, which itself contains all canonical
2416 /// types, values, and templates.
2417 TemplateName getCanonicalTemplateName(TemplateName Name) const;
2419 /// Determine whether the given template names refer to the same
2421 bool hasSameTemplateName(TemplateName X, TemplateName Y);
2423 /// Retrieve the "canonical" template argument.
2425 /// The canonical template argument is the simplest template argument
2426 /// (which may be a type, value, expression, or declaration) that
2427 /// expresses the value of the argument.
2428 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2431 /// Type Query functions. If the type is an instance of the specified class,
2432 /// return the Type pointer for the underlying maximally pretty type. This
2433 /// is a member of ASTContext because this may need to do some amount of
2434 /// canonicalization, e.g. to move type qualifiers into the element type.
2435 const ArrayType *getAsArrayType(QualType T) const;
2436 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2437 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2439 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2440 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2442 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2443 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2445 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2447 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2450 /// Return the innermost element type of an array type.
2452 /// For example, will return "int" for int[m][n]
2453 QualType getBaseElementType(const ArrayType *VAT) const;
2455 /// Return the innermost element type of a type (which needn't
2456 /// actually be an array type).
2457 QualType getBaseElementType(QualType QT) const;
2459 /// Return number of constant array elements.
2460 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2462 /// Perform adjustment on the parameter type of a function.
2464 /// This routine adjusts the given parameter type @p T to the actual
2465 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2466 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2467 QualType getAdjustedParameterType(QualType T) const;
2469 /// Retrieve the parameter type as adjusted for use in the signature
2470 /// of a function, decaying array and function types and removing top-level
2472 QualType getSignatureParameterType(QualType T) const;
2474 QualType getExceptionObjectType(QualType T) const;
2476 /// Return the properly qualified result of decaying the specified
2477 /// array type to a pointer.
2479 /// This operation is non-trivial when handling typedefs etc. The canonical
2480 /// type of \p T must be an array type, this returns a pointer to a properly
2481 /// qualified element of the array.
2483 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2484 QualType getArrayDecayedType(QualType T) const;
2486 /// Return the type that \p PromotableType will promote to: C99
2487 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2488 QualType getPromotedIntegerType(QualType PromotableType) const;
2490 /// Recurses in pointer/array types until it finds an Objective-C
2491 /// retainable type and returns its ownership.
2492 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2494 /// Whether this is a promotable bitfield reference according
2495 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2497 /// \returns the type this bit-field will promote to, or NULL if no
2498 /// promotion occurs.
2499 QualType isPromotableBitField(Expr *E) const;
2501 /// Return the highest ranked integer type, see C99 6.3.1.8p1.
2503 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2504 /// \p LHS < \p RHS, return -1.
2505 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2507 /// Compare the rank of the two specified floating point types,
2508 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2510 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2511 /// \p LHS < \p RHS, return -1.
2512 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2514 /// Compare the rank of two floating point types as above, but compare equal
2515 /// if both types have the same floating-point semantics on the target (i.e.
2516 /// long double and double on AArch64 will return 0).
2517 int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const;
2519 /// Return a real floating point or a complex type (based on
2520 /// \p typeDomain/\p typeSize).
2522 /// \param typeDomain a real floating point or complex type.
2523 /// \param typeSize a real floating point or complex type.
2524 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2525 QualType typeDomain) const;
2527 unsigned getTargetAddressSpace(QualType T) const {
2528 return getTargetAddressSpace(T.getQualifiers());
2531 unsigned getTargetAddressSpace(Qualifiers Q) const {
2532 return getTargetAddressSpace(Q.getAddressSpace());
2535 unsigned getTargetAddressSpace(LangAS AS) const;
2537 LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;
2539 /// Get target-dependent integer value for null pointer which is used for
2540 /// constant folding.
2541 uint64_t getTargetNullPointerValue(QualType QT) const;
2543 bool addressSpaceMapManglingFor(LangAS AS) const {
2544 return AddrSpaceMapMangling || isTargetAddressSpace(AS);
2548 // Helper for integer ordering
2549 unsigned getIntegerRank(const Type *T) const;
2552 //===--------------------------------------------------------------------===//
2553 // Type Compatibility Predicates
2554 //===--------------------------------------------------------------------===//
2556 /// Compatibility predicates used to check assignment expressions.
2557 bool typesAreCompatible(QualType T1, QualType T2,
2558 bool CompareUnqualified = false); // C99 6.2.7p1
2560 bool propertyTypesAreCompatible(QualType, QualType);
2561 bool typesAreBlockPointerCompatible(QualType, QualType);
2563 bool isObjCIdType(QualType T) const {
2564 return T == getObjCIdType();
2567 bool isObjCClassType(QualType T) const {
2568 return T == getObjCClassType();
2571 bool isObjCSelType(QualType T) const {
2572 return T == getObjCSelType();
2575 bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS,
2576 const ObjCObjectPointerType *RHS,
2579 bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS,
2580 const ObjCObjectPointerType *RHS);
2582 // Check the safety of assignment from LHS to RHS
2583 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2584 const ObjCObjectPointerType *RHSOPT);
2585 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2586 const ObjCObjectType *RHS);
2587 bool canAssignObjCInterfacesInBlockPointer(
2588 const ObjCObjectPointerType *LHSOPT,
2589 const ObjCObjectPointerType *RHSOPT,
2590 bool BlockReturnType);
2591 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2592 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2593 const ObjCObjectPointerType *RHSOPT);
2594 bool canBindObjCObjectType(QualType To, QualType From);
2596 // Functions for calculating composite types
2597 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2598 bool Unqualified = false, bool BlockReturnType = false);
2599 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2600 bool Unqualified = false, bool AllowCXX = false);
2601 QualType mergeFunctionParameterTypes(QualType, QualType,
2602 bool OfBlockPointer = false,
2603 bool Unqualified = false);
2604 QualType mergeTransparentUnionType(QualType, QualType,
2605 bool OfBlockPointer=false,
2606 bool Unqualified = false);
2608 QualType mergeObjCGCQualifiers(QualType, QualType);
2610 /// This function merges the ExtParameterInfo lists of two functions. It
2611 /// returns true if the lists are compatible. The merged list is returned in
2614 /// \param FirstFnType The type of the first function.
2616 /// \param SecondFnType The type of the second function.
2618 /// \param CanUseFirst This flag is set to true if the first function's
2619 /// ExtParameterInfo list can be used as the composite list of
2620 /// ExtParameterInfo.
2622 /// \param CanUseSecond This flag is set to true if the second function's
2623 /// ExtParameterInfo list can be used as the composite list of
2624 /// ExtParameterInfo.
2626 /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
2627 /// empty if none of the flags are set.
2629 bool mergeExtParameterInfo(
2630 const FunctionProtoType *FirstFnType,
2631 const FunctionProtoType *SecondFnType,
2632 bool &CanUseFirst, bool &CanUseSecond,
2633 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
2635 void ResetObjCLayout(const ObjCContainerDecl *CD);
2637 //===--------------------------------------------------------------------===//
2638 // Integer Predicates
2639 //===--------------------------------------------------------------------===//
2641 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2642 // of bits in an integer type excluding any padding bits.
2643 unsigned getIntWidth(QualType T) const;
2645 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2646 // unsigned integer type. This method takes a signed type, and returns the
2647 // corresponding unsigned integer type.
2648 // With the introduction of fixed point types in ISO N1169, this method also
2649 // accepts fixed point types and returns the corresponding unsigned type for
2650 // a given fixed point type.
2651 QualType getCorrespondingUnsignedType(QualType T) const;
2653 // Per ISO N1169, this method accepts fixed point types and returns the
2654 // corresponding saturated type for a given fixed point type.
2655 QualType getCorrespondingSaturatedType(QualType Ty) const;
2657 // This method accepts fixed point types and returns the corresponding signed
2658 // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned
2659 // fixed point types because there are unsigned integer types like bool and
2660 // char8_t that don't have signed equivalents.
2661 QualType getCorrespondingSignedFixedPointType(QualType Ty) const;
2663 //===--------------------------------------------------------------------===//
2665 //===--------------------------------------------------------------------===//
2667 /// Make an APSInt of the appropriate width and signedness for the
2668 /// given \p Value and integer \p Type.
2669 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2670 // If Type is a signed integer type larger than 64 bits, we need to be sure
2671 // to sign extend Res appropriately.
2672 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2674 unsigned Width = getIntWidth(Type);
2675 if (Width != Res.getBitWidth())
2676 return Res.extOrTrunc(Width);
2680 bool isSentinelNullExpr(const Expr *E);
2682 /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
2684 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2686 /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
2688 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2690 /// Return true if there is at least one \@implementation in the TU.
2691 bool AnyObjCImplementation() {
2692 return !ObjCImpls.empty();
2695 /// Set the implementation of ObjCInterfaceDecl.
2696 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2697 ObjCImplementationDecl *ImplD);
2699 /// Set the implementation of ObjCCategoryDecl.
2700 void setObjCImplementation(ObjCCategoryDecl *CatD,
2701 ObjCCategoryImplDecl *ImplD);
2703 /// Get the duplicate declaration of a ObjCMethod in the same
2704 /// interface, or null if none exists.
2705 const ObjCMethodDecl *
2706 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2708 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2709 const ObjCMethodDecl *Redecl);
2711 /// Returns the Objective-C interface that \p ND belongs to if it is
2712 /// an Objective-C method/property/ivar etc. that is part of an interface,
2713 /// otherwise returns null.
2714 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2716 /// Set the copy initialization expression of a block var decl. \p CanThrow
2717 /// indicates whether the copy expression can throw or not.
2718 void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow);
2720 /// Get the copy initialization expression of the VarDecl \p VD, or
2721 /// nullptr if none exists.
2722 BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const;
2724 /// Allocate an uninitialized TypeSourceInfo.
2726 /// The caller should initialize the memory held by TypeSourceInfo using
2727 /// the TypeLoc wrappers.
2729 /// \param T the type that will be the basis for type source info. This type
2730 /// should refer to how the declarator was written in source code, not to
2731 /// what type semantic analysis resolved the declarator to.
2733 /// \param Size the size of the type info to create, or 0 if the size
2734 /// should be calculated based on the type.
2735 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2737 /// Allocate a TypeSourceInfo where all locations have been
2738 /// initialized to a given location, which defaults to the empty
2741 getTrivialTypeSourceInfo(QualType T,
2742 SourceLocation Loc = SourceLocation()) const;
2744 /// Add a deallocation callback that will be invoked when the
2745 /// ASTContext is destroyed.
2747 /// \param Callback A callback function that will be invoked on destruction.
2749 /// \param Data Pointer data that will be provided to the callback function
2750 /// when it is called.
2751 void AddDeallocation(void (*Callback)(void *), void *Data) const;
2753 /// If T isn't trivially destructible, calls AddDeallocation to register it
2754 /// for destruction.
2755 template <typename T> void addDestruction(T *Ptr) const {
2756 if (!std::is_trivially_destructible<T>::value) {
2757 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
2758 AddDeallocation(DestroyPtr, Ptr);
2762 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2763 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2765 /// Determines if the decl can be CodeGen'ed or deserialized from PCH
2766 /// lazily, only when used; this is only relevant for function or file scoped
2767 /// var definitions.
2769 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2771 bool DeclMustBeEmitted(const Decl *D);
2773 /// Visits all versions of a multiversioned function with the passed
2775 void forEachMultiversionedFunctionVersion(
2776 const FunctionDecl *FD,
2777 llvm::function_ref<void(FunctionDecl *)> Pred) const;
2779 const CXXConstructorDecl *
2780 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2782 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2783 CXXConstructorDecl *CD);
2785 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2787 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2789 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2791 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2793 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2794 unsigned getManglingNumber(const NamedDecl *ND) const;
2796 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2797 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2799 /// Retrieve the context for computing mangling numbers in the given
2801 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2802 enum NeedExtraManglingDecl_t { NeedExtraManglingDecl };
2803 MangleNumberingContext &getManglingNumberContext(NeedExtraManglingDecl_t,
2806 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
2808 /// Used by ParmVarDecl to store on the side the
2809 /// index of the parameter when it exceeds the size of the normal bitfield.
2810 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2812 /// Used by ParmVarDecl to retrieve on the side the
2813 /// index of the parameter when it exceeds the size of the normal bitfield.
2814 unsigned getParameterIndex(const ParmVarDecl *D) const;
2816 /// Return a string representing the human readable name for the specified
2817 /// function declaration or file name. Used by SourceLocExpr and
2818 /// PredefinedExpr to cache evaluated results.
2819 StringLiteral *getPredefinedStringLiteralFromCache(StringRef Key) const;
2821 /// Return a declaration for the global GUID object representing the given
2823 MSGuidDecl *getMSGuidDecl(MSGuidDeclParts Parts) const;
2825 /// Parses the target attributes passed in, and returns only the ones that are
2826 /// valid feature names.
2827 ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const;
2829 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
2830 const FunctionDecl *) const;
2831 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
2832 GlobalDecl GD) const;
2834 //===--------------------------------------------------------------------===//
2836 //===--------------------------------------------------------------------===//
2838 /// The number of implicitly-declared default constructors.
2839 unsigned NumImplicitDefaultConstructors = 0;
2841 /// The number of implicitly-declared default constructors for
2842 /// which declarations were built.
2843 unsigned NumImplicitDefaultConstructorsDeclared = 0;
2845 /// The number of implicitly-declared copy constructors.
2846 unsigned NumImplicitCopyConstructors = 0;
2848 /// The number of implicitly-declared copy constructors for
2849 /// which declarations were built.
2850 unsigned NumImplicitCopyConstructorsDeclared = 0;
2852 /// The number of implicitly-declared move constructors.
2853 unsigned NumImplicitMoveConstructors = 0;
2855 /// The number of implicitly-declared move constructors for
2856 /// which declarations were built.
2857 unsigned NumImplicitMoveConstructorsDeclared = 0;
2859 /// The number of implicitly-declared copy assignment operators.
2860 unsigned NumImplicitCopyAssignmentOperators = 0;
2862 /// The number of implicitly-declared copy assignment operators for
2863 /// which declarations were built.
2864 unsigned NumImplicitCopyAssignmentOperatorsDeclared = 0;
2866 /// The number of implicitly-declared move assignment operators.
2867 unsigned NumImplicitMoveAssignmentOperators = 0;
2869 /// The number of implicitly-declared move assignment operators for
2870 /// which declarations were built.
2871 unsigned NumImplicitMoveAssignmentOperatorsDeclared = 0;
2873 /// The number of implicitly-declared destructors.
2874 unsigned NumImplicitDestructors = 0;
2876 /// The number of implicitly-declared destructors for which
2877 /// declarations were built.
2878 unsigned NumImplicitDestructorsDeclared = 0;
2881 /// Initialize built-in types.
2883 /// This routine may only be invoked once for a given ASTContext object.
2884 /// It is normally invoked after ASTContext construction.
2886 /// \param Target The target
2887 void InitBuiltinTypes(const TargetInfo &Target,
2888 const TargetInfo *AuxTarget = nullptr);
2891 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2893 class ObjCEncOptions {
2896 ObjCEncOptions(unsigned Bits) : Bits(Bits) {}
2899 ObjCEncOptions() : Bits(0) {}
2900 ObjCEncOptions(const ObjCEncOptions &RHS) : Bits(RHS.Bits) {}
2902 #define OPT_LIST(V) \
2903 V(ExpandPointedToStructures, 0) \
2904 V(ExpandStructures, 1) \
2905 V(IsOutermostType, 2) \
2906 V(EncodingProperty, 3) \
2907 V(IsStructField, 4) \
2908 V(EncodeBlockParameters, 5) \
2909 V(EncodeClassNames, 6) \
2911 #define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; }
2915 #define V(N,I) bool N() const { return Bits & 1 << I; }
2921 LLVM_NODISCARD ObjCEncOptions keepingOnly(ObjCEncOptions Mask) const {
2922 return Bits & Mask.Bits;
2925 LLVM_NODISCARD ObjCEncOptions forComponentType() const {
2926 ObjCEncOptions Mask = ObjCEncOptions()
2927 .setIsOutermostType()
2928 .setIsStructField();
2929 return Bits & ~Mask.Bits;
2933 // Return the Objective-C type encoding for a given type.
2934 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2935 ObjCEncOptions Options,
2936 const FieldDecl *Field,
2937 QualType *NotEncodedT = nullptr) const;
2939 // Adds the encoding of the structure's members.
2940 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2941 const FieldDecl *Field,
2942 bool includeVBases = true,
2943 QualType *NotEncodedT=nullptr) const;
2946 // Adds the encoding of a method parameter or return type.
2947 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2948 QualType T, std::string& S,
2949 bool Extended) const;
2951 /// Returns true if this is an inline-initialized static data member
2952 /// which is treated as a definition for MSVC compatibility.
2953 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2955 enum class InlineVariableDefinitionKind {
2956 /// Not an inline variable.
2959 /// Weak definition of inline variable.
2962 /// Weak for now, might become strong later in this TU.
2965 /// Strong definition.
2969 /// Determine whether a definition of this inline variable should
2970 /// be treated as a weak or strong definition. For compatibility with
2971 /// C++14 and before, for a constexpr static data member, if there is an
2972 /// out-of-line declaration of the member, we may promote it from weak to
2974 InlineVariableDefinitionKind
2975 getInlineVariableDefinitionKind(const VarDecl *VD) const;
2978 friend class DeclarationNameTable;
2979 friend class DeclContext;
2981 const ASTRecordLayout &
2982 getObjCLayout(const ObjCInterfaceDecl *D,
2983 const ObjCImplementationDecl *Impl) const;
2985 /// A set of deallocations that should be performed when the
2986 /// ASTContext is destroyed.
2987 // FIXME: We really should have a better mechanism in the ASTContext to
2988 // manage running destructors for types which do variable sized allocation
2989 // within the AST. In some places we thread the AST bump pointer allocator
2990 // into the datastructures which avoids this mess during deallocation but is
2991 // wasteful of memory, and here we require a lot of error prone book keeping
2992 // in order to track and run destructors while we're tearing things down.
2993 using DeallocationFunctionsAndArguments =
2994 llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
2995 mutable DeallocationFunctionsAndArguments Deallocations;
2997 // FIXME: This currently contains the set of StoredDeclMaps used
2998 // by DeclContext objects. This probably should not be in ASTContext,
2999 // but we include it here so that ASTContext can quickly deallocate them.
3000 llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
3002 std::vector<Decl *> TraversalScope;
3004 std::unique_ptr<VTableContextBase> VTContext;
3006 void ReleaseDeclContextMaps();
3009 enum PragmaSectionFlag : unsigned {
3015 PSF_ZeroInit = 0x10,
3016 PSF_Invalid = 0x80000000U,
3019 struct SectionInfo {
3020 DeclaratorDecl *Decl;
3021 SourceLocation PragmaSectionLocation;
3024 SectionInfo() = default;
3025 SectionInfo(DeclaratorDecl *Decl,
3026 SourceLocation PragmaSectionLocation,
3028 : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
3029 SectionFlags(SectionFlags) {}
3032 llvm::StringMap<SectionInfo> SectionInfos;
3034 /// Return a new OMPTraitInfo object owned by this context.
3035 OMPTraitInfo &getNewOMPTraitInfo();
3038 /// All OMPTraitInfo objects live in this collection, one per
3039 /// `pragma omp [begin] declare variant` directive.
3040 SmallVector<std::unique_ptr<OMPTraitInfo>, 4> OMPTraitInfoVector;
3043 /// Insertion operator for diagnostics.
3044 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3045 const ASTContext::SectionInfo &Section);
3047 /// Utility function for constructing a nullary selector.
3048 inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
3049 IdentifierInfo* II = &Ctx.Idents.get(name);
3050 return Ctx.Selectors.getSelector(0, &II);
3053 /// Utility function for constructing an unary selector.
3054 inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
3055 IdentifierInfo* II = &Ctx.Idents.get(name);
3056 return Ctx.Selectors.getSelector(1, &II);
3059 } // namespace clang
3061 // operator new and delete aren't allowed inside namespaces.
3063 /// Placement new for using the ASTContext's allocator.
3065 /// This placement form of operator new uses the ASTContext's allocator for
3066 /// obtaining memory.
3068 /// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h!
3069 /// Any changes here need to also be made there.
3071 /// We intentionally avoid using a nothrow specification here so that the calls
3072 /// to this operator will not perform a null check on the result -- the
3073 /// underlying allocator never returns null pointers.
3075 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3077 /// // Default alignment (8)
3078 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
3079 /// // Specific alignment
3080 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
3082 /// Memory allocated through this placement new operator does not need to be
3083 /// explicitly freed, as ASTContext will free all of this memory when it gets
3084 /// destroyed. Please note that you cannot use delete on the pointer.
3086 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3087 /// @param C The ASTContext that provides the allocator.
3088 /// @param Alignment The alignment of the allocated memory (if the underlying
3089 /// allocator supports it).
3090 /// @return The allocated memory. Could be nullptr.
3091 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
3092 size_t Alignment /* = 8 */) {
3093 return C.Allocate(Bytes, Alignment);
3096 /// Placement delete companion to the new above.
3098 /// This operator is just a companion to the new above. There is no way of
3099 /// invoking it directly; see the new operator for more details. This operator
3100 /// is called implicitly by the compiler if a placement new expression using
3101 /// the ASTContext throws in the object constructor.
3102 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
3106 /// This placement form of operator new[] uses the ASTContext's allocator for
3107 /// obtaining memory.
3109 /// We intentionally avoid using a nothrow specification here so that the calls
3110 /// to this operator will not perform a null check on the result -- the
3111 /// underlying allocator never returns null pointers.
3113 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3115 /// // Default alignment (8)
3116 /// char *data = new (Context) char[10];
3117 /// // Specific alignment
3118 /// char *data = new (Context, 4) char[10];
3120 /// Memory allocated through this placement new[] operator does not need to be
3121 /// explicitly freed, as ASTContext will free all of this memory when it gets
3122 /// destroyed. Please note that you cannot use delete on the pointer.
3124 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3125 /// @param C The ASTContext that provides the allocator.
3126 /// @param Alignment The alignment of the allocated memory (if the underlying
3127 /// allocator supports it).
3128 /// @return The allocated memory. Could be nullptr.
3129 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
3130 size_t Alignment /* = 8 */) {
3131 return C.Allocate(Bytes, Alignment);
3134 /// Placement delete[] companion to the new[] above.
3136 /// This operator is just a companion to the new[] above. There is no way of
3137 /// invoking it directly; see the new[] operator for more details. This operator
3138 /// is called implicitly by the compiler if a placement new[] expression using
3139 /// the ASTContext throws in the object constructor.
3140 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
3144 /// Create the representation of a LazyGenerationalUpdatePtr.
3145 template <typename Owner, typename T,
3146 void (clang::ExternalASTSource::*Update)(Owner)>
3147 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
3148 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
3149 const clang::ASTContext &Ctx, T Value) {
3150 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
3151 // include ASTContext.h. We explicitly instantiate it for all relevant types
3152 // in ASTContext.cpp.
3153 if (auto *Source = Ctx.getExternalSource())
3154 return new (Ctx) LazyData(Source, Value);
3158 #endif // LLVM_CLANG_AST_ASTCONTEXT_H