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/ASTTypeTraits.h"
19 #include "clang/AST/CanonicalType.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/ComparisonCategories.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/NestedNameSpecifier.h"
28 #include "clang/AST/PrettyPrinter.h"
29 #include "clang/AST/RawCommentList.h"
30 #include "clang/AST/TemplateBase.h"
31 #include "clang/AST/TemplateName.h"
32 #include "clang/AST/Type.h"
33 #include "clang/Basic/AddressSpaces.h"
34 #include "clang/Basic/AttrKinds.h"
35 #include "clang/Basic/IdentifierTable.h"
36 #include "clang/Basic/LLVM.h"
37 #include "clang/Basic/LangOptions.h"
38 #include "clang/Basic/Linkage.h"
39 #include "clang/Basic/OperatorKinds.h"
40 #include "clang/Basic/PartialDiagnostic.h"
41 #include "clang/Basic/SanitizerBlacklist.h"
42 #include "clang/Basic/SourceLocation.h"
43 #include "clang/Basic/Specifiers.h"
44 #include "clang/Basic/TargetInfo.h"
45 #include "clang/Basic/XRayLists.h"
46 #include "llvm/ADT/APSInt.h"
47 #include "llvm/ADT/ArrayRef.h"
48 #include "llvm/ADT/DenseMap.h"
49 #include "llvm/ADT/FoldingSet.h"
50 #include "llvm/ADT/IntrusiveRefCntPtr.h"
51 #include "llvm/ADT/MapVector.h"
52 #include "llvm/ADT/None.h"
53 #include "llvm/ADT/Optional.h"
54 #include "llvm/ADT/PointerIntPair.h"
55 #include "llvm/ADT/PointerUnion.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/StringMap.h"
58 #include "llvm/ADT/StringRef.h"
59 #include "llvm/ADT/TinyPtrVector.h"
60 #include "llvm/ADT/Triple.h"
61 #include "llvm/ADT/iterator_range.h"
62 #include "llvm/Support/AlignOf.h"
63 #include "llvm/Support/Allocator.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/Compiler.h"
72 #include <type_traits>
86 class ASTMutationListener;
87 class ASTRecordLayout;
90 class BuiltinTemplateDecl;
93 class CXXConstructorDecl;
96 class DiagnosticsEngine;
98 class FixedPointSemantics;
100 class MangleNumberingContext;
101 class MaterializeTemporaryExpr;
102 class MemberSpecializationInfo;
104 class ObjCCategoryDecl;
105 class ObjCCategoryImplDecl;
106 class ObjCContainerDecl;
108 class ObjCImplementationDecl;
109 class ObjCInterfaceDecl;
111 class ObjCMethodDecl;
112 class ObjCPropertyDecl;
113 class ObjCPropertyImplDecl;
114 class ObjCProtocolDecl;
115 class ObjCTypeParamDecl;
118 class StoredDeclsMap;
120 class TemplateParameterList;
121 class TemplateTemplateParmDecl;
122 class TemplateTypeParmDecl;
123 class UnresolvedSetIterator;
124 class UsingShadowDecl;
125 class VarTemplateDecl;
126 class VTableContextBase;
132 } // namespace Builtin
134 enum BuiltinTemplateKind : int;
140 } // namespace comments
146 } // namespace interp
151 bool AlignIsRequired : 1;
153 TypeInfo() : AlignIsRequired(false) {}
154 TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
155 : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
158 /// Holds long-lived AST nodes (such as types and decls) that can be
159 /// referred to throughout the semantic analysis of a file.
160 class ASTContext : public RefCountedBase<ASTContext> {
162 /// Copy initialization expr of a __block variable and a boolean flag that
163 /// indicates whether the expression can throw.
164 struct BlockVarCopyInit {
165 BlockVarCopyInit() = default;
166 BlockVarCopyInit(Expr *CopyExpr, bool CanThrow)
167 : ExprAndFlag(CopyExpr, CanThrow) {}
168 void setExprAndFlag(Expr *CopyExpr, bool CanThrow) {
169 ExprAndFlag.setPointerAndInt(CopyExpr, CanThrow);
171 Expr *getCopyExpr() const { return ExprAndFlag.getPointer(); }
172 bool canThrow() const { return ExprAndFlag.getInt(); }
173 llvm::PointerIntPair<Expr *, 1, bool> ExprAndFlag;
177 friend class NestedNameSpecifier;
179 mutable SmallVector<Type *, 0> Types;
180 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
181 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
182 mutable llvm::FoldingSet<PointerType> PointerTypes;
183 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
184 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
185 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
186 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
187 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
188 mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &>
190 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
191 mutable std::vector<VariableArrayType*> VariableArrayTypes;
192 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
193 mutable llvm::FoldingSet<DependentSizedExtVectorType>
194 DependentSizedExtVectorTypes;
195 mutable llvm::FoldingSet<DependentAddressSpaceType>
196 DependentAddressSpaceTypes;
197 mutable llvm::FoldingSet<VectorType> VectorTypes;
198 mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes;
199 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
200 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
202 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
203 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
204 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
205 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
206 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
207 SubstTemplateTypeParmTypes;
208 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
209 SubstTemplateTypeParmPackTypes;
210 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
211 TemplateSpecializationTypes;
212 mutable llvm::FoldingSet<ParenType> ParenTypes;
213 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
214 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
215 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
217 DependentTemplateSpecializationTypes;
218 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
219 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
220 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
221 mutable llvm::FoldingSet<DependentUnaryTransformType>
222 DependentUnaryTransformTypes;
223 mutable llvm::FoldingSet<AutoType> AutoTypes;
224 mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
225 DeducedTemplateSpecializationTypes;
226 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
227 llvm::FoldingSet<AttributedType> AttributedTypes;
228 mutable llvm::FoldingSet<PipeType> PipeTypes;
230 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
231 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
232 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
233 SubstTemplateTemplateParms;
234 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
236 SubstTemplateTemplateParmPacks;
238 /// The set of nested name specifiers.
240 /// This set is managed by the NestedNameSpecifier class.
241 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
242 mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
244 /// A cache mapping from RecordDecls to ASTRecordLayouts.
246 /// This is lazily created. This is intentionally not serialized.
247 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
249 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
252 /// A cache from types to size and alignment information.
253 using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
254 mutable TypeInfoMap MemoizedTypeInfo;
256 /// A cache from types to unadjusted alignment information. Only ARM and
257 /// AArch64 targets need this information, keeping it separate prevents
258 /// imposing overhead on TypeInfo size.
259 using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>;
260 mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
262 /// A cache mapping from CXXRecordDecls to key functions.
263 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
265 /// Mapping from ObjCContainers to their ObjCImplementations.
266 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
268 /// Mapping from ObjCMethod to its duplicate declaration in the same
270 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
272 /// Mapping from __block VarDecls to BlockVarCopyInit.
273 llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
275 /// Mapping from materialized temporaries with static storage duration
276 /// that appear in constant initializers to their evaluated values. These are
277 /// allocated in a std::map because their address must be stable.
278 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue *>
279 MaterializedTemporaryValues;
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) { Profile(ID, Parm); }
303 static void Profile(llvm::FoldingSetNodeID &ID,
304 TemplateTemplateParmDecl *Parm);
306 mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
307 CanonTemplateTemplateParms;
309 TemplateTemplateParmDecl *
310 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
312 /// The typedef for the __int128_t type.
313 mutable TypedefDecl *Int128Decl = nullptr;
315 /// The typedef for the __uint128_t type.
316 mutable TypedefDecl *UInt128Decl = nullptr;
318 /// The typedef for the target specific predefined
319 /// __builtin_va_list type.
320 mutable TypedefDecl *BuiltinVaListDecl = nullptr;
322 /// The typedef for the predefined \c __builtin_ms_va_list type.
323 mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
325 /// The typedef for the predefined \c id type.
326 mutable TypedefDecl *ObjCIdDecl = nullptr;
328 /// The typedef for the predefined \c SEL type.
329 mutable TypedefDecl *ObjCSelDecl = nullptr;
331 /// The typedef for the predefined \c Class type.
332 mutable TypedefDecl *ObjCClassDecl = nullptr;
334 /// The typedef for the predefined \c Protocol class in Objective-C.
335 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
337 /// The typedef for the predefined 'BOOL' type.
338 mutable TypedefDecl *BOOLDecl = nullptr;
340 // Typedefs which may be provided defining the structure of Objective-C
342 QualType ObjCIdRedefinitionType;
343 QualType ObjCClassRedefinitionType;
344 QualType ObjCSelRedefinitionType;
346 /// The identifier 'bool'.
347 mutable IdentifierInfo *BoolName = nullptr;
349 /// The identifier 'NSObject'.
350 mutable IdentifierInfo *NSObjectName = nullptr;
352 /// The identifier 'NSCopying'.
353 IdentifierInfo *NSCopyingName = nullptr;
355 /// The identifier '__make_integer_seq'.
356 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
358 /// The identifier '__type_pack_element'.
359 mutable IdentifierInfo *TypePackElementName = nullptr;
361 QualType ObjCConstantStringType;
362 mutable RecordDecl *CFConstantStringTagDecl = nullptr;
363 mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
365 mutable QualType ObjCSuperType;
367 QualType ObjCNSStringType;
369 /// The typedef declaration for the Objective-C "instancetype" type.
370 TypedefDecl *ObjCInstanceTypeDecl = nullptr;
372 /// The type for the C FILE type.
373 TypeDecl *FILEDecl = nullptr;
375 /// The type for the C jmp_buf type.
376 TypeDecl *jmp_bufDecl = nullptr;
378 /// The type for the C sigjmp_buf type.
379 TypeDecl *sigjmp_bufDecl = nullptr;
381 /// The type for the C ucontext_t type.
382 TypeDecl *ucontext_tDecl = nullptr;
384 /// Type for the Block descriptor for Blocks CodeGen.
386 /// Since this is only used for generation of debug info, it is not
388 mutable RecordDecl *BlockDescriptorType = nullptr;
390 /// Type for the Block descriptor for Blocks CodeGen.
392 /// Since this is only used for generation of debug info, it is not
394 mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
396 /// Declaration for the CUDA cudaConfigureCall function.
397 FunctionDecl *cudaConfigureCallDecl = nullptr;
399 /// Keeps track of all declaration attributes.
401 /// Since so few decls have attrs, we keep them in a hash map instead of
402 /// wasting space in the Decl class.
403 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
405 /// A mapping from non-redeclarable declarations in modules that were
406 /// merged with other declarations to the canonical declaration that they were
408 llvm::DenseMap<Decl*, Decl*> MergedDecls;
410 /// A mapping from a defining declaration to a list of modules (other
411 /// than the owning module of the declaration) that contain merged
412 /// definitions of that entity.
413 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
415 /// Initializers for a module, in order. Each Decl will be either
416 /// something that has a semantic effect on startup (such as a variable with
417 /// a non-constant initializer), or an ImportDecl (which recursively triggers
418 /// initialization of another module).
419 struct PerModuleInitializers {
420 llvm::SmallVector<Decl*, 4> Initializers;
421 llvm::SmallVector<uint32_t, 4> LazyInitializers;
423 void resolve(ASTContext &Ctx);
425 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
427 ASTContext &this_() { return *this; }
430 /// A type synonym for the TemplateOrInstantiation mapping.
431 using TemplateOrSpecializationInfo =
432 llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
435 friend class ASTDeclReader;
436 friend class ASTReader;
437 friend class ASTWriter;
438 friend class CXXRecordDecl;
440 /// A mapping to contain the template or declaration that
441 /// a variable declaration describes or was instantiated from,
444 /// For non-templates, this value will be NULL. For variable
445 /// declarations that describe a variable template, this will be a
446 /// pointer to a VarTemplateDecl. For static data members
447 /// of class template specializations, this will be the
448 /// MemberSpecializationInfo referring to the member variable that was
449 /// instantiated or specialized. Thus, the mapping will keep track of
450 /// the static data member templates from which static data members of
451 /// class template specializations were instantiated.
453 /// Given the following example:
456 /// template<typename T>
461 /// template<typename T>
462 /// T X<T>::value = T(17);
464 /// int *x = &X<int>::value;
467 /// This mapping will contain an entry that maps from the VarDecl for
468 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
469 /// class template X) and will be marked TSK_ImplicitInstantiation.
470 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
471 TemplateOrInstantiation;
473 /// Keeps track of the declaration from which a using declaration was
474 /// created during instantiation.
476 /// The source and target declarations are always a UsingDecl, an
477 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
481 /// template<typename T>
486 /// template<typename T>
487 /// struct B : A<T> {
491 /// template struct B<int>;
494 /// This mapping will contain an entry that maps from the UsingDecl in
495 /// B<int> to the UnresolvedUsingDecl in B<T>.
496 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
498 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
499 InstantiatedFromUsingShadowDecl;
501 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
503 /// Mapping that stores the methods overridden by a given C++
506 /// Since most C++ member functions aren't virtual and therefore
507 /// don't override anything, we store the overridden functions in
508 /// this map on the side rather than within the CXXMethodDecl structure.
509 using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
510 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
512 /// Mapping from each declaration context to its corresponding
513 /// mangling numbering context (used for constructs like lambdas which
514 /// need to be consistently numbered for the mangler).
515 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
516 MangleNumberingContexts;
517 llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>>
518 ExtraMangleNumberingContexts;
520 /// Side-table of mangling numbers for declarations which rarely
521 /// need them (like static local vars).
522 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
523 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
525 /// Mapping that stores parameterIndex values for ParmVarDecls when
526 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
527 using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
528 ParameterIndexTable ParamIndices;
530 ImportDecl *FirstLocalImport = nullptr;
531 ImportDecl *LastLocalImport = nullptr;
533 TranslationUnitDecl *TUDecl;
534 mutable ExternCContextDecl *ExternCContext = nullptr;
535 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
536 mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
538 /// The associated SourceManager object.
539 SourceManager &SourceMgr;
541 /// The language options used to create the AST associated with
542 /// this ASTContext object.
543 LangOptions &LangOpts;
545 /// Blacklist object that is used by sanitizers to decide which
546 /// entities should not be instrumented.
547 std::unique_ptr<SanitizerBlacklist> SanitizerBL;
549 /// Function filtering mechanism to determine whether a given function
550 /// should be imbued with the XRay "always" or "never" attributes.
551 std::unique_ptr<XRayFunctionFilter> XRayFilter;
553 /// The allocator used to create AST objects.
555 /// AST objects are never destructed; rather, all memory associated with the
556 /// AST objects will be released when the ASTContext itself is destroyed.
557 mutable llvm::BumpPtrAllocator BumpAlloc;
559 /// Allocator for partial diagnostics.
560 PartialDiagnostic::StorageAllocator DiagAllocator;
562 /// The current C++ ABI.
563 std::unique_ptr<CXXABI> ABI;
564 CXXABI *createCXXABI(const TargetInfo &T);
566 /// The logical -> physical address space map.
567 const LangASMap *AddrSpaceMap = nullptr;
569 /// Address space map mangling must be used with language specific
570 /// address spaces (e.g. OpenCL/CUDA)
571 bool AddrSpaceMapMangling;
573 const TargetInfo *Target = nullptr;
574 const TargetInfo *AuxTarget = nullptr;
575 clang::PrintingPolicy PrintingPolicy;
576 std::unique_ptr<interp::Context> InterpContext;
579 IdentifierTable &Idents;
580 SelectorTable &Selectors;
581 Builtin::Context &BuiltinInfo;
582 mutable DeclarationNameTable DeclarationNames;
583 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
584 ASTMutationListener *Listener = nullptr;
586 /// Returns the clang bytecode interpreter context.
587 interp::Context &getInterpContext();
589 /// Container for either a single DynTypedNode or for an ArrayRef to
590 /// DynTypedNode. For use with ParentMap.
591 class DynTypedNodeList {
592 using DynTypedNode = ast_type_traits::DynTypedNode;
594 llvm::AlignedCharArrayUnion<ast_type_traits::DynTypedNode,
595 ArrayRef<DynTypedNode>> Storage;
599 DynTypedNodeList(const DynTypedNode &N) : IsSingleNode(true) {
600 new (Storage.buffer) DynTypedNode(N);
603 DynTypedNodeList(ArrayRef<DynTypedNode> A) : IsSingleNode(false) {
604 new (Storage.buffer) ArrayRef<DynTypedNode>(A);
607 const ast_type_traits::DynTypedNode *begin() const {
609 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
611 return reinterpret_cast<const DynTypedNode *>(Storage.buffer);
614 const ast_type_traits::DynTypedNode *end() const {
616 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
618 return reinterpret_cast<const DynTypedNode *>(Storage.buffer) + 1;
621 size_t size() const { return end() - begin(); }
622 bool empty() const { return begin() == end(); }
624 const DynTypedNode &operator[](size_t N) const {
625 assert(N < size() && "Out of bounds!");
626 return *(begin() + N);
630 // A traversal scope limits the parts of the AST visible to certain analyses.
631 // RecursiveASTVisitor::TraverseAST will only visit reachable nodes, and
632 // getParents() will only observe reachable parent edges.
634 // The scope is defined by a set of "top-level" declarations.
635 // Initially, it is the entire TU: {getTranslationUnitDecl()}.
636 // Changing the scope clears the parent cache, which is expensive to rebuild.
637 std::vector<Decl *> getTraversalScope() const { return TraversalScope; }
638 void setTraversalScope(const std::vector<Decl *> &);
640 /// Returns the parents of the given node (within the traversal scope).
642 /// Note that this will lazily compute the parents of all nodes
643 /// and store them for later retrieval. Thus, the first call is O(n)
644 /// in the number of AST nodes.
646 /// Caveats and FIXMEs:
647 /// Calculating the parent map over all AST nodes will need to load the
648 /// full AST. This can be undesirable in the case where the full AST is
649 /// expensive to create (for example, when using precompiled header
650 /// preambles). Thus, there are good opportunities for optimization here.
651 /// One idea is to walk the given node downwards, looking for references
652 /// to declaration contexts - once a declaration context is found, compute
653 /// the parent map for the declaration context; if that can satisfy the
654 /// request, loading the whole AST can be avoided. Note that this is made
655 /// more complex by statements in templates having multiple parents - those
656 /// problems can be solved by building closure over the templated parts of
657 /// the AST, which also avoids touching large parts of the AST.
658 /// Additionally, we will want to add an interface to already give a hint
659 /// where to search for the parents, for example when looking at a statement
660 /// inside a certain function.
662 /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
663 /// NestedNameSpecifier or NestedNameSpecifierLoc.
664 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node) {
665 return getParents(ast_type_traits::DynTypedNode::create(Node));
668 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node);
670 const clang::PrintingPolicy &getPrintingPolicy() const {
671 return PrintingPolicy;
674 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
675 PrintingPolicy = Policy;
678 SourceManager& getSourceManager() { return SourceMgr; }
679 const SourceManager& getSourceManager() const { return SourceMgr; }
681 llvm::BumpPtrAllocator &getAllocator() const {
685 void *Allocate(size_t Size, unsigned Align = 8) const {
686 return BumpAlloc.Allocate(Size, Align);
688 template <typename T> T *Allocate(size_t Num = 1) const {
689 return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
691 void Deallocate(void *Ptr) const {}
693 /// Return the total amount of physical memory allocated for representing
694 /// AST nodes and type information.
695 size_t getASTAllocatedMemory() const {
696 return BumpAlloc.getTotalMemory();
699 /// Return the total memory used for various side tables.
700 size_t getSideTableAllocatedMemory() const;
702 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
703 return DiagAllocator;
706 const TargetInfo &getTargetInfo() const { return *Target; }
707 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
709 /// getIntTypeForBitwidth -
710 /// sets integer QualTy according to specified details:
711 /// bitwidth, signed/unsigned.
712 /// Returns empty type if there is no appropriate target types.
713 QualType getIntTypeForBitwidth(unsigned DestWidth,
714 unsigned Signed) const;
716 /// getRealTypeForBitwidth -
717 /// sets floating point QualTy according to specified bitwidth.
718 /// Returns empty type if there is no appropriate target types.
719 QualType getRealTypeForBitwidth(unsigned DestWidth) const;
721 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
723 const LangOptions& getLangOpts() const { return LangOpts; }
725 const SanitizerBlacklist &getSanitizerBlacklist() const {
729 const XRayFunctionFilter &getXRayFilter() const {
733 DiagnosticsEngine &getDiagnostics() const;
735 FullSourceLoc getFullLoc(SourceLocation Loc) const {
736 return FullSourceLoc(Loc,SourceMgr);
739 /// All comments in this translation unit.
740 RawCommentList Comments;
742 /// True if comments are already loaded from ExternalASTSource.
743 mutable bool CommentsLoaded = false;
745 /// Mapping from declaration to directly attached comment.
747 /// Raw comments are owned by Comments list. This mapping is populated
749 mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments;
751 /// Mapping from canonical declaration to the first redeclaration in chain
752 /// that has a comment attached.
754 /// Raw comments are owned by Comments list. This mapping is populated
756 mutable llvm::DenseMap<const Decl *, const Decl *> RedeclChainComments;
758 /// Keeps track of redeclaration chains that don't have any comment attached.
759 /// Mapping from canonical declaration to redeclaration chain that has no
760 /// comments attached to any redeclaration. Specifically it's mapping to
761 /// the last redeclaration we've checked.
763 /// Shall not contain declarations that have comments attached to any
764 /// redeclaration in their chain.
765 mutable llvm::DenseMap<const Decl *, const Decl *> CommentlessRedeclChains;
767 /// Mapping from declarations to parsed comments attached to any
769 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
771 /// Attaches \p Comment to \p OriginalD and to its redeclaration chain
772 /// and removes the redeclaration chain from the set of commentless chains.
774 /// Don't do anything if a comment has already been attached to \p OriginalD
775 /// or its redeclaration chain.
776 void cacheRawCommentForDecl(const Decl &OriginalD,
777 const RawComment &Comment) const;
779 /// \returns searches \p CommentsInFile for doc comment for \p D.
781 /// \p RepresentativeLocForDecl is used as a location for searching doc
782 /// comments. \p CommentsInFile is a mapping offset -> comment of files in the
783 /// same file where \p RepresentativeLocForDecl is.
784 RawComment *getRawCommentForDeclNoCacheImpl(
785 const Decl *D, const SourceLocation RepresentativeLocForDecl,
786 const std::map<unsigned, RawComment *> &CommentsInFile) const;
788 /// Return the documentation comment attached to a given declaration,
789 /// without looking into cache.
790 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
793 RawCommentList &getRawCommentList() {
797 void addComment(const RawComment &RC) {
798 assert(LangOpts.RetainCommentsFromSystemHeaders ||
799 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
800 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
803 /// Return the documentation comment attached to a given declaration.
804 /// Returns nullptr if no comment is attached.
806 /// \param OriginalDecl if not nullptr, is set to declaration AST node that
807 /// had the comment, if the comment we found comes from a redeclaration.
809 getRawCommentForAnyRedecl(const Decl *D,
810 const Decl **OriginalDecl = nullptr) const;
812 /// Searches existing comments for doc comments that should be attached to \p
813 /// Decls. If any doc comment is found, it is parsed.
815 /// Requirement: All \p Decls are in the same file.
817 /// If the last comment in the file is already attached we assume
818 /// there are not comments left to be attached to \p Decls.
819 void attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
820 const Preprocessor *PP);
822 /// Return parsed documentation comment attached to a given declaration.
823 /// Returns nullptr if no comment is attached.
825 /// \param PP the Preprocessor used with this TU. Could be nullptr if
826 /// preprocessor is not available.
827 comments::FullComment *getCommentForDecl(const Decl *D,
828 const Preprocessor *PP) const;
830 /// Return parsed documentation comment attached to a given declaration.
831 /// Returns nullptr if no comment is attached. Does not look at any
832 /// redeclarations of the declaration.
833 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
835 comments::FullComment *cloneFullComment(comments::FullComment *FC,
836 const Decl *D) const;
839 mutable comments::CommandTraits CommentCommandTraits;
841 /// Iterator that visits import declarations.
842 class import_iterator {
843 ImportDecl *Import = nullptr;
846 using value_type = ImportDecl *;
847 using reference = ImportDecl *;
848 using pointer = ImportDecl *;
849 using difference_type = int;
850 using iterator_category = std::forward_iterator_tag;
852 import_iterator() = default;
853 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
855 reference operator*() const { return Import; }
856 pointer operator->() const { return Import; }
858 import_iterator &operator++() {
859 Import = ASTContext::getNextLocalImport(Import);
863 import_iterator operator++(int) {
864 import_iterator Other(*this);
869 friend bool operator==(import_iterator X, import_iterator Y) {
870 return X.Import == Y.Import;
873 friend bool operator!=(import_iterator X, import_iterator Y) {
874 return X.Import != Y.Import;
879 comments::CommandTraits &getCommentCommandTraits() const {
880 return CommentCommandTraits;
883 /// Retrieve the attributes for the given declaration.
884 AttrVec& getDeclAttrs(const Decl *D);
886 /// Erase the attributes corresponding to the given declaration.
887 void eraseDeclAttrs(const Decl *D);
889 /// If this variable is an instantiated static data member of a
890 /// class template specialization, returns the templated static data member
891 /// from which it was instantiated.
893 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
896 TemplateOrSpecializationInfo
897 getTemplateOrSpecializationInfo(const VarDecl *Var);
899 /// Note that the static data member \p Inst is an instantiation of
900 /// the static data member template \p Tmpl of a class template.
901 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
902 TemplateSpecializationKind TSK,
903 SourceLocation PointOfInstantiation = SourceLocation());
905 void setTemplateOrSpecializationInfo(VarDecl *Inst,
906 TemplateOrSpecializationInfo TSI);
908 /// If the given using decl \p Inst is an instantiation of a
909 /// (possibly unresolved) using decl from a template instantiation,
911 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
913 /// Remember that the using decl \p Inst is an instantiation
914 /// of the using decl \p Pattern of a class template.
915 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
917 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
918 UsingShadowDecl *Pattern);
919 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
921 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
923 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
925 // Access to the set of methods overridden by the given C++ method.
926 using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
927 overridden_cxx_method_iterator
928 overridden_methods_begin(const CXXMethodDecl *Method) const;
930 overridden_cxx_method_iterator
931 overridden_methods_end(const CXXMethodDecl *Method) const;
933 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
935 using overridden_method_range =
936 llvm::iterator_range<overridden_cxx_method_iterator>;
938 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
940 /// Note that the given C++ \p Method overrides the given \p
941 /// Overridden method.
942 void addOverriddenMethod(const CXXMethodDecl *Method,
943 const CXXMethodDecl *Overridden);
945 /// Return C++ or ObjC overridden methods for the given \p Method.
947 /// An ObjC method is considered to override any method in the class's
948 /// base classes, its protocols, or its categories' protocols, that has
949 /// the same selector and is of the same kind (class or instance).
950 /// A method in an implementation is not considered as overriding the same
951 /// method in the interface or its categories.
952 void getOverriddenMethods(
953 const NamedDecl *Method,
954 SmallVectorImpl<const NamedDecl *> &Overridden) const;
956 /// Notify the AST context that a new import declaration has been
957 /// parsed or implicitly created within this translation unit.
958 void addedLocalImportDecl(ImportDecl *Import);
960 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
961 return Import->NextLocalImport;
964 using import_range = llvm::iterator_range<import_iterator>;
966 import_range local_imports() const {
967 return import_range(import_iterator(FirstLocalImport), import_iterator());
970 Decl *getPrimaryMergedDecl(Decl *D) {
971 Decl *Result = MergedDecls.lookup(D);
972 return Result ? Result : D;
974 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
975 MergedDecls[D] = Primary;
978 /// Note that the definition \p ND has been merged into module \p M,
979 /// and should be visible whenever \p M is visible.
980 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
981 bool NotifyListeners = true);
983 /// Clean up the merged definition list. Call this if you might have
984 /// added duplicates into the list.
985 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
987 /// Get the additional modules in which the definition \p Def has
989 ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def) {
991 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
992 if (MergedIt == MergedDefModules.end())
994 return MergedIt->second;
997 /// Add a declaration to the list of declarations that are initialized
998 /// for a module. This will typically be a global variable (with internal
999 /// linkage) that runs module initializers, such as the iostream initializer,
1000 /// or an ImportDecl nominating another module that has initializers.
1001 void addModuleInitializer(Module *M, Decl *Init);
1003 void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs);
1005 /// Get the initializations to perform when importing a module, if any.
1006 ArrayRef<Decl*> getModuleInitializers(Module *M);
1008 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
1010 ExternCContextDecl *getExternCContextDecl() const;
1011 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
1012 BuiltinTemplateDecl *getTypePackElementDecl() const;
1018 CanQualType WCharTy; // [C++ 3.9.1p5].
1019 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
1020 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
1021 CanQualType Char8Ty; // [C++20 proposal]
1022 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
1023 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
1024 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
1025 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
1026 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
1027 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty;
1028 CanQualType ShortAccumTy, AccumTy,
1029 LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1030 CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
1031 CanQualType ShortFractTy, FractTy, LongFractTy;
1032 CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
1033 CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy;
1034 CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy,
1035 SatUnsignedLongAccumTy;
1036 CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
1037 CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
1038 SatUnsignedLongFractTy;
1039 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
1040 CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
1041 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
1042 CanQualType Float128ComplexTy;
1043 CanQualType VoidPtrTy, NullPtrTy;
1044 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
1045 CanQualType BuiltinFnTy;
1046 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
1047 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
1048 CanQualType ObjCBuiltinBoolTy;
1049 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1050 CanQualType SingletonId;
1051 #include "clang/Basic/OpenCLImageTypes.def"
1052 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
1053 CanQualType OCLQueueTy, OCLReserveIDTy;
1054 CanQualType OMPArraySectionTy;
1055 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1057 #include "clang/Basic/OpenCLExtensionTypes.def"
1058 #define SVE_TYPE(Name, Id, SingletonId) \
1059 CanQualType SingletonId;
1060 #include "clang/Basic/AArch64SVEACLETypes.def"
1062 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
1063 mutable QualType AutoDeductTy; // Deduction against 'auto'.
1064 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
1066 // Decl used to help define __builtin_va_list for some targets.
1067 // The decl is built when constructing 'BuiltinVaListDecl'.
1068 mutable Decl *VaListTagDecl;
1070 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1071 SelectorTable &sels, Builtin::Context &builtins);
1072 ASTContext(const ASTContext &) = delete;
1073 ASTContext &operator=(const ASTContext &) = delete;
1076 /// Attach an external AST source to the AST context.
1078 /// The external AST source provides the ability to load parts of
1079 /// the abstract syntax tree as needed from some external storage,
1080 /// e.g., a precompiled header.
1081 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1083 /// Retrieve a pointer to the external AST source associated
1084 /// with this AST context, if any.
1085 ExternalASTSource *getExternalSource() const {
1086 return ExternalSource.get();
1089 /// Attach an AST mutation listener to the AST context.
1091 /// The AST mutation listener provides the ability to track modifications to
1092 /// the abstract syntax tree entities committed after they were initially
1094 void setASTMutationListener(ASTMutationListener *Listener) {
1095 this->Listener = Listener;
1098 /// Retrieve a pointer to the AST mutation listener associated
1099 /// with this AST context, if any.
1100 ASTMutationListener *getASTMutationListener() const { return Listener; }
1102 void PrintStats() const;
1103 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1105 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1106 const IdentifierInfo *II) const;
1108 /// Create a new implicit TU-level CXXRecordDecl or RecordDecl
1110 RecordDecl *buildImplicitRecord(StringRef Name,
1111 RecordDecl::TagKind TK = TTK_Struct) const;
1113 /// Create a new implicit TU-level typedef declaration.
1114 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1116 /// Retrieve the declaration for the 128-bit signed integer type.
1117 TypedefDecl *getInt128Decl() const;
1119 /// Retrieve the declaration for the 128-bit unsigned integer type.
1120 TypedefDecl *getUInt128Decl() const;
1122 //===--------------------------------------------------------------------===//
1123 // Type Constructors
1124 //===--------------------------------------------------------------------===//
1127 /// Return a type with extended qualifiers.
1128 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1130 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1132 QualType getPipeType(QualType T, bool ReadOnly) const;
1135 /// Return the uniqued reference to the type for an address space
1136 /// qualified type with the specified type and address space.
1138 /// The resulting type has a union of the qualifiers from T and the address
1139 /// space. If T already has an address space specifier, it is silently
1141 QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
1143 /// Remove any existing address space on the type and returns the type
1144 /// with qualifiers intact (or that's the idea anyway)
1146 /// The return type should be T with all prior qualifiers minus the address
1148 QualType removeAddrSpaceQualType(QualType T) const;
1150 /// Apply Objective-C protocol qualifiers to the given type.
1151 /// \param allowOnPointerType specifies if we can apply protocol
1152 /// qualifiers on ObjCObjectPointerType. It can be set to true when
1153 /// constructing the canonical type of a Objective-C type parameter.
1154 QualType applyObjCProtocolQualifiers(QualType type,
1155 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1156 bool allowOnPointerType = false) const;
1158 /// Return the uniqued reference to the type for an Objective-C
1159 /// gc-qualified type.
1161 /// The resulting type has a union of the qualifiers from T and the gc
1163 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1165 /// Return the uniqued reference to the type for a \c restrict
1168 /// The resulting type has a union of the qualifiers from \p T and
1170 QualType getRestrictType(QualType T) const {
1171 return T.withFastQualifiers(Qualifiers::Restrict);
1174 /// Return the uniqued reference to the type for a \c volatile
1177 /// The resulting type has a union of the qualifiers from \p T and
1179 QualType getVolatileType(QualType T) const {
1180 return T.withFastQualifiers(Qualifiers::Volatile);
1183 /// Return the uniqued reference to the type for a \c const
1186 /// The resulting type has a union of the qualifiers from \p T and \c const.
1188 /// It can be reasonably expected that this will always be equivalent to
1189 /// calling T.withConst().
1190 QualType getConstType(QualType T) const { return T.withConst(); }
1192 /// Change the ExtInfo on a function type.
1193 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1194 FunctionType::ExtInfo EInfo);
1196 /// Adjust the given function result type.
1197 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1199 /// Change the result type of a function type once it is deduced.
1200 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1202 /// Get a function type and produce the equivalent function type with the
1203 /// specified exception specification. Type sugar that can be present on a
1204 /// declaration of a function with an exception specification is permitted
1205 /// and preserved. Other type sugar (for instance, typedefs) is not.
1206 QualType getFunctionTypeWithExceptionSpec(
1207 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI);
1209 /// Determine whether two function types are the same, ignoring
1210 /// exception specifications in cases where they're part of the type.
1211 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U);
1213 /// Change the exception specification on a function once it is
1214 /// delay-parsed, instantiated, or computed.
1215 void adjustExceptionSpec(FunctionDecl *FD,
1216 const FunctionProtoType::ExceptionSpecInfo &ESI,
1217 bool AsWritten = false);
1219 /// Return the uniqued reference to the type for a complex
1220 /// number with the specified element type.
1221 QualType getComplexType(QualType T) const;
1222 CanQualType getComplexType(CanQualType T) const {
1223 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1226 /// Return the uniqued reference to the type for a pointer to
1227 /// the specified type.
1228 QualType getPointerType(QualType T) const;
1229 CanQualType getPointerType(CanQualType T) const {
1230 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1233 /// Return the uniqued reference to a type adjusted from the original
1234 /// type to a new type.
1235 QualType getAdjustedType(QualType Orig, QualType New) const;
1236 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1237 return CanQualType::CreateUnsafe(
1238 getAdjustedType((QualType)Orig, (QualType)New));
1241 /// Return the uniqued reference to the decayed version of the given
1242 /// type. Can only be called on array and function types which decay to
1244 QualType getDecayedType(QualType T) const;
1245 CanQualType getDecayedType(CanQualType T) const {
1246 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1249 /// Return the uniqued reference to the atomic type for the specified
1251 QualType getAtomicType(QualType T) const;
1253 /// Return the uniqued reference to the type for a block of the
1255 QualType getBlockPointerType(QualType T) const;
1257 /// Gets the struct used to keep track of the descriptor for pointer to
1259 QualType getBlockDescriptorType() const;
1261 /// Return a read_only pipe type for the specified type.
1262 QualType getReadPipeType(QualType T) const;
1264 /// Return a write_only pipe type for the specified type.
1265 QualType getWritePipeType(QualType T) const;
1267 /// Gets the struct used to keep track of the extended descriptor for
1268 /// pointer to blocks.
1269 QualType getBlockDescriptorExtendedType() const;
1271 /// Map an AST Type to an OpenCLTypeKind enum value.
1272 TargetInfo::OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
1274 /// Get address space for OpenCL type.
1275 LangAS getOpenCLTypeAddrSpace(const Type *T) const;
1277 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1278 cudaConfigureCallDecl = FD;
1281 FunctionDecl *getcudaConfigureCallDecl() {
1282 return cudaConfigureCallDecl;
1285 /// Returns true iff we need copy/dispose helpers for the given type.
1286 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1288 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
1289 /// is set to false in this case. If HasByrefExtendedLayout returns true,
1290 /// byref variable has extended lifetime.
1291 bool getByrefLifetime(QualType Ty,
1292 Qualifiers::ObjCLifetime &Lifetime,
1293 bool &HasByrefExtendedLayout) const;
1295 /// Return the uniqued reference to the type for an lvalue reference
1296 /// to the specified type.
1297 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1300 /// Return the uniqued reference to the type for an rvalue reference
1301 /// to the specified type.
1302 QualType getRValueReferenceType(QualType T) const;
1304 /// Return the uniqued reference to the type for a member pointer to
1305 /// the specified type in the specified class.
1307 /// The class \p Cls is a \c Type because it could be a dependent name.
1308 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1310 /// Return a non-unique reference to the type for a variable array of
1311 /// the specified element type.
1312 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1313 ArrayType::ArraySizeModifier ASM,
1314 unsigned IndexTypeQuals,
1315 SourceRange Brackets) const;
1317 /// Return a non-unique reference to the type for a dependently-sized
1318 /// array of the specified element type.
1320 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1322 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1323 ArrayType::ArraySizeModifier ASM,
1324 unsigned IndexTypeQuals,
1325 SourceRange Brackets) const;
1327 /// Return a unique reference to the type for an incomplete array of
1328 /// the specified element type.
1329 QualType getIncompleteArrayType(QualType EltTy,
1330 ArrayType::ArraySizeModifier ASM,
1331 unsigned IndexTypeQuals) const;
1333 /// Return the unique reference to the type for a constant array of
1334 /// the specified element type.
1335 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1336 const Expr *SizeExpr,
1337 ArrayType::ArraySizeModifier ASM,
1338 unsigned IndexTypeQuals) const;
1340 /// Return a type for a constant array for a string literal of the
1341 /// specified element type and length.
1342 QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const;
1344 /// Returns a vla type where known sizes are replaced with [*].
1345 QualType getVariableArrayDecayedType(QualType Ty) const;
1347 /// Return the unique reference to a vector type of the specified
1348 /// element type and size.
1350 /// \pre \p VectorType must be a built-in type.
1351 QualType getVectorType(QualType VectorType, unsigned NumElts,
1352 VectorType::VectorKind VecKind) const;
1353 /// Return the unique reference to the type for a dependently sized vector of
1354 /// the specified element type.
1355 QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr,
1356 SourceLocation AttrLoc,
1357 VectorType::VectorKind VecKind) const;
1359 /// Return the unique reference to an extended vector type
1360 /// of the specified element type and size.
1362 /// \pre \p VectorType must be a built-in type.
1363 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1365 /// \pre Return a non-unique reference to the type for a dependently-sized
1366 /// vector of the specified element type.
1368 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1370 QualType getDependentSizedExtVectorType(QualType VectorType,
1372 SourceLocation AttrLoc) const;
1374 QualType getDependentAddressSpaceType(QualType PointeeType,
1375 Expr *AddrSpaceExpr,
1376 SourceLocation AttrLoc) const;
1378 /// Return a K&R style C function type like 'int()'.
1379 QualType getFunctionNoProtoType(QualType ResultTy,
1380 const FunctionType::ExtInfo &Info) const;
1382 QualType getFunctionNoProtoType(QualType ResultTy) const {
1383 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1386 /// Return a normal function type with a typed argument list.
1387 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1388 const FunctionProtoType::ExtProtoInfo &EPI) const {
1389 return getFunctionTypeInternal(ResultTy, Args, EPI, false);
1392 QualType adjustStringLiteralBaseType(QualType StrLTy) const;
1395 /// Return a normal function type with a typed argument list.
1396 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1397 const FunctionProtoType::ExtProtoInfo &EPI,
1398 bool OnlyWantCanonical) const;
1401 /// Return the unique reference to the type for the specified type
1403 QualType getTypeDeclType(const TypeDecl *Decl,
1404 const TypeDecl *PrevDecl = nullptr) const {
1405 assert(Decl && "Passed null for Decl param");
1406 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1409 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1410 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1411 return QualType(PrevDecl->TypeForDecl, 0);
1414 return getTypeDeclTypeSlow(Decl);
1417 /// Return the unique reference to the type for the specified
1418 /// typedef-name decl.
1419 QualType getTypedefType(const TypedefNameDecl *Decl,
1420 QualType Canon = QualType()) const;
1422 QualType getRecordType(const RecordDecl *Decl) const;
1424 QualType getEnumType(const EnumDecl *Decl) const;
1426 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1428 QualType getAttributedType(attr::Kind attrKind,
1429 QualType modifiedType,
1430 QualType equivalentType);
1432 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1433 QualType Replacement) const;
1434 QualType getSubstTemplateTypeParmPackType(
1435 const TemplateTypeParmType *Replaced,
1436 const TemplateArgument &ArgPack);
1439 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1441 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1443 QualType getTemplateSpecializationType(TemplateName T,
1444 ArrayRef<TemplateArgument> Args,
1445 QualType Canon = QualType()) const;
1448 getCanonicalTemplateSpecializationType(TemplateName T,
1449 ArrayRef<TemplateArgument> Args) const;
1451 QualType getTemplateSpecializationType(TemplateName T,
1452 const TemplateArgumentListInfo &Args,
1453 QualType Canon = QualType()) const;
1456 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1457 const TemplateArgumentListInfo &Args,
1458 QualType Canon = QualType()) const;
1460 QualType getParenType(QualType NamedType) const;
1462 QualType getMacroQualifiedType(QualType UnderlyingTy,
1463 const IdentifierInfo *MacroII) const;
1465 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1466 NestedNameSpecifier *NNS, QualType NamedType,
1467 TagDecl *OwnedTagDecl = nullptr) const;
1468 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1469 NestedNameSpecifier *NNS,
1470 const IdentifierInfo *Name,
1471 QualType Canon = QualType()) const;
1473 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1474 NestedNameSpecifier *NNS,
1475 const IdentifierInfo *Name,
1476 const TemplateArgumentListInfo &Args) const;
1477 QualType getDependentTemplateSpecializationType(
1478 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1479 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1481 TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
1483 /// Get a template argument list with one argument per template parameter
1484 /// in a template parameter list, such as for the injected class name of
1485 /// a class template.
1486 void getInjectedTemplateArgs(const TemplateParameterList *Params,
1487 SmallVectorImpl<TemplateArgument> &Args);
1489 QualType getPackExpansionType(QualType Pattern,
1490 Optional<unsigned> NumExpansions);
1492 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1493 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1495 /// Legacy interface: cannot provide type arguments or __kindof.
1496 QualType getObjCObjectType(QualType Base,
1497 ObjCProtocolDecl * const *Protocols,
1498 unsigned NumProtocols) const;
1500 QualType getObjCObjectType(QualType Base,
1501 ArrayRef<QualType> typeArgs,
1502 ArrayRef<ObjCProtocolDecl *> protocols,
1503 bool isKindOf) const;
1505 QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1506 ArrayRef<ObjCProtocolDecl *> protocols) const;
1508 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1510 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1511 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1513 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1514 ObjCInterfaceDecl *IDecl);
1516 /// Return a ObjCObjectPointerType type for the given ObjCObjectType.
1517 QualType getObjCObjectPointerType(QualType OIT) const;
1520 QualType getTypeOfExprType(Expr *e) const;
1521 QualType getTypeOfType(QualType t) const;
1524 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1526 /// Unary type transforms
1527 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1528 UnaryTransformType::UTTKind UKind) const;
1530 /// C++11 deduced auto type.
1531 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1532 bool IsDependent, bool IsPack = false) const;
1534 /// C++11 deduction pattern for 'auto' type.
1535 QualType getAutoDeductType() const;
1537 /// C++11 deduction pattern for 'auto &&' type.
1538 QualType getAutoRRefDeductType() const;
1540 /// C++17 deduced class template specialization type.
1541 QualType getDeducedTemplateSpecializationType(TemplateName Template,
1542 QualType DeducedType,
1543 bool IsDependent) const;
1545 /// Return the unique reference to the type for the specified TagDecl
1546 /// (struct/union/class/enum) decl.
1547 QualType getTagDeclType(const TagDecl *Decl) const;
1549 /// Return the unique type for "size_t" (C99 7.17), defined in
1552 /// The sizeof operator requires this (C99 6.5.3.4p4).
1553 CanQualType getSizeType() const;
1555 /// Return the unique signed counterpart of
1556 /// the integer type corresponding to size_t.
1557 CanQualType getSignedSizeType() const;
1559 /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1561 CanQualType getIntMaxType() const;
1563 /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1565 CanQualType getUIntMaxType() const;
1567 /// Return the unique wchar_t type available in C++ (and available as
1568 /// __wchar_t as a Microsoft extension).
1569 QualType getWCharType() const { return WCharTy; }
1571 /// Return the type of wide characters. In C++, this returns the
1572 /// unique wchar_t type. In C99, this returns a type compatible with the type
1573 /// defined in <stddef.h> as defined by the target.
1574 QualType getWideCharType() const { return WideCharTy; }
1576 /// Return the type of "signed wchar_t".
1578 /// Used when in C++, as a GCC extension.
1579 QualType getSignedWCharType() const;
1581 /// Return the type of "unsigned wchar_t".
1583 /// Used when in C++, as a GCC extension.
1584 QualType getUnsignedWCharType() const;
1586 /// In C99, this returns a type compatible with the type
1587 /// defined in <stddef.h> as defined by the target.
1588 QualType getWIntType() const { return WIntTy; }
1590 /// Return a type compatible with "intptr_t" (C99 7.18.1.4),
1591 /// as defined by the target.
1592 QualType getIntPtrType() const;
1594 /// Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1595 /// as defined by the target.
1596 QualType getUIntPtrType() const;
1598 /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1599 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1600 QualType getPointerDiffType() const;
1602 /// Return the unique unsigned counterpart of "ptrdiff_t"
1603 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
1604 /// in the definition of %tu format specifier.
1605 QualType getUnsignedPointerDiffType() const;
1607 /// Return the unique type for "pid_t" defined in
1608 /// <sys/types.h>. We need this to compute the correct type for vfork().
1609 QualType getProcessIDType() const;
1611 /// Return the C structure type used to represent constant CFStrings.
1612 QualType getCFConstantStringType() const;
1614 /// Returns the C struct type for objc_super
1615 QualType getObjCSuperType() const;
1616 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1618 /// Get the structure type used to representation CFStrings, or NULL
1619 /// if it hasn't yet been built.
1620 QualType getRawCFConstantStringType() const {
1621 if (CFConstantStringTypeDecl)
1622 return getTypedefType(CFConstantStringTypeDecl);
1625 void setCFConstantStringType(QualType T);
1626 TypedefDecl *getCFConstantStringDecl() const;
1627 RecordDecl *getCFConstantStringTagDecl() const;
1629 // This setter/getter represents the ObjC type for an NSConstantString.
1630 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1631 QualType getObjCConstantStringInterface() const {
1632 return ObjCConstantStringType;
1635 QualType getObjCNSStringType() const {
1636 return ObjCNSStringType;
1639 void setObjCNSStringType(QualType T) {
1640 ObjCNSStringType = T;
1643 /// Retrieve the type that \c id has been defined to, which may be
1644 /// different from the built-in \c id if \c id has been typedef'd.
1645 QualType getObjCIdRedefinitionType() const {
1646 if (ObjCIdRedefinitionType.isNull())
1647 return getObjCIdType();
1648 return ObjCIdRedefinitionType;
1651 /// Set the user-written type that redefines \c id.
1652 void setObjCIdRedefinitionType(QualType RedefType) {
1653 ObjCIdRedefinitionType = RedefType;
1656 /// Retrieve the type that \c Class has been defined to, which may be
1657 /// different from the built-in \c Class if \c Class has been typedef'd.
1658 QualType getObjCClassRedefinitionType() const {
1659 if (ObjCClassRedefinitionType.isNull())
1660 return getObjCClassType();
1661 return ObjCClassRedefinitionType;
1664 /// Set the user-written type that redefines 'SEL'.
1665 void setObjCClassRedefinitionType(QualType RedefType) {
1666 ObjCClassRedefinitionType = RedefType;
1669 /// Retrieve the type that 'SEL' has been defined to, which may be
1670 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1671 QualType getObjCSelRedefinitionType() const {
1672 if (ObjCSelRedefinitionType.isNull())
1673 return getObjCSelType();
1674 return ObjCSelRedefinitionType;
1677 /// Set the user-written type that redefines 'SEL'.
1678 void setObjCSelRedefinitionType(QualType RedefType) {
1679 ObjCSelRedefinitionType = RedefType;
1682 /// Retrieve the identifier 'NSObject'.
1683 IdentifierInfo *getNSObjectName() const {
1684 if (!NSObjectName) {
1685 NSObjectName = &Idents.get("NSObject");
1688 return NSObjectName;
1691 /// Retrieve the identifier 'NSCopying'.
1692 IdentifierInfo *getNSCopyingName() {
1693 if (!NSCopyingName) {
1694 NSCopyingName = &Idents.get("NSCopying");
1697 return NSCopyingName;
1700 CanQualType getNSUIntegerType() const {
1701 assert(Target && "Expected target to be initialized");
1702 const llvm::Triple &T = Target->getTriple();
1703 // Windows is LLP64 rather than LP64
1704 if (T.isOSWindows() && T.isArch64Bit())
1705 return UnsignedLongLongTy;
1706 return UnsignedLongTy;
1709 CanQualType getNSIntegerType() const {
1710 assert(Target && "Expected target to be initialized");
1711 const llvm::Triple &T = Target->getTriple();
1712 // Windows is LLP64 rather than LP64
1713 if (T.isOSWindows() && T.isArch64Bit())
1718 /// Retrieve the identifier 'bool'.
1719 IdentifierInfo *getBoolName() const {
1721 BoolName = &Idents.get("bool");
1725 IdentifierInfo *getMakeIntegerSeqName() const {
1726 if (!MakeIntegerSeqName)
1727 MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1728 return MakeIntegerSeqName;
1731 IdentifierInfo *getTypePackElementName() const {
1732 if (!TypePackElementName)
1733 TypePackElementName = &Idents.get("__type_pack_element");
1734 return TypePackElementName;
1737 /// Retrieve the Objective-C "instancetype" type, if already known;
1738 /// otherwise, returns a NULL type;
1739 QualType getObjCInstanceType() {
1740 return getTypeDeclType(getObjCInstanceTypeDecl());
1743 /// Retrieve the typedef declaration corresponding to the Objective-C
1744 /// "instancetype" type.
1745 TypedefDecl *getObjCInstanceTypeDecl();
1747 /// Set the type for the C FILE type.
1748 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1750 /// Retrieve the C FILE type.
1751 QualType getFILEType() const {
1753 return getTypeDeclType(FILEDecl);
1757 /// Set the type for the C jmp_buf type.
1758 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1759 this->jmp_bufDecl = jmp_bufDecl;
1762 /// Retrieve the C jmp_buf type.
1763 QualType getjmp_bufType() const {
1765 return getTypeDeclType(jmp_bufDecl);
1769 /// Set the type for the C sigjmp_buf type.
1770 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1771 this->sigjmp_bufDecl = sigjmp_bufDecl;
1774 /// Retrieve the C sigjmp_buf type.
1775 QualType getsigjmp_bufType() const {
1777 return getTypeDeclType(sigjmp_bufDecl);
1781 /// Set the type for the C ucontext_t type.
1782 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1783 this->ucontext_tDecl = ucontext_tDecl;
1786 /// Retrieve the C ucontext_t type.
1787 QualType getucontext_tType() const {
1789 return getTypeDeclType(ucontext_tDecl);
1793 /// The result type of logical operations, '<', '>', '!=', etc.
1794 QualType getLogicalOperationType() const {
1795 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1798 /// Emit the Objective-CC type encoding for the given type \p T into
1801 /// If \p Field is specified then record field names are also encoded.
1802 void getObjCEncodingForType(QualType T, std::string &S,
1803 const FieldDecl *Field=nullptr,
1804 QualType *NotEncodedT=nullptr) const;
1806 /// Emit the Objective-C property type encoding for the given
1807 /// type \p T into \p S.
1808 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1810 void getLegacyIntegralTypeEncoding(QualType &t) const;
1812 /// Put the string version of the type qualifiers \p QT into \p S.
1813 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1814 std::string &S) const;
1816 /// Emit the encoded type for the function \p Decl into \p S.
1818 /// This is in the same format as Objective-C method encodings.
1820 /// \returns true if an error occurred (e.g., because one of the parameter
1821 /// types is incomplete), false otherwise.
1822 std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
1824 /// Emit the encoded type for the method declaration \p Decl into
1826 std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1827 bool Extended = false) const;
1829 /// Return the encoded type for this block declaration.
1830 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1832 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1833 /// this method declaration. If non-NULL, Container must be either
1834 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1835 /// only be NULL when getting encodings for protocol properties.
1836 std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1837 const Decl *Container) const;
1839 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1840 ObjCProtocolDecl *rProto) const;
1842 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1843 const ObjCPropertyDecl *PD,
1844 const Decl *Container) const;
1846 /// Return the size of type \p T for Objective-C encoding purpose,
1848 CharUnits getObjCEncodingTypeSize(QualType T) const;
1850 /// Retrieve the typedef corresponding to the predefined \c id type
1852 TypedefDecl *getObjCIdDecl() const;
1854 /// Represents the Objective-CC \c id type.
1856 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1857 /// pointer type, a pointer to a struct.
1858 QualType getObjCIdType() const {
1859 return getTypeDeclType(getObjCIdDecl());
1862 /// Retrieve the typedef corresponding to the predefined 'SEL' type
1864 TypedefDecl *getObjCSelDecl() const;
1866 /// Retrieve the type that corresponds to the predefined Objective-C
1868 QualType getObjCSelType() const {
1869 return getTypeDeclType(getObjCSelDecl());
1872 /// Retrieve the typedef declaration corresponding to the predefined
1873 /// Objective-C 'Class' type.
1874 TypedefDecl *getObjCClassDecl() const;
1876 /// Represents the Objective-C \c Class type.
1878 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1879 /// pointer type, a pointer to a struct.
1880 QualType getObjCClassType() const {
1881 return getTypeDeclType(getObjCClassDecl());
1884 /// Retrieve the Objective-C class declaration corresponding to
1885 /// the predefined \c Protocol class.
1886 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1888 /// Retrieve declaration of 'BOOL' typedef
1889 TypedefDecl *getBOOLDecl() const {
1893 /// Save declaration of 'BOOL' typedef
1894 void setBOOLDecl(TypedefDecl *TD) {
1898 /// type of 'BOOL' type.
1899 QualType getBOOLType() const {
1900 return getTypeDeclType(getBOOLDecl());
1903 /// Retrieve the type of the Objective-C \c Protocol class.
1904 QualType getObjCProtoType() const {
1905 return getObjCInterfaceType(getObjCProtocolDecl());
1908 /// Retrieve the C type declaration corresponding to the predefined
1909 /// \c __builtin_va_list type.
1910 TypedefDecl *getBuiltinVaListDecl() const;
1912 /// Retrieve the type of the \c __builtin_va_list type.
1913 QualType getBuiltinVaListType() const {
1914 return getTypeDeclType(getBuiltinVaListDecl());
1917 /// Retrieve the C type declaration corresponding to the predefined
1918 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1919 /// for some targets.
1920 Decl *getVaListTagDecl() const;
1922 /// Retrieve the C type declaration corresponding to the predefined
1923 /// \c __builtin_ms_va_list type.
1924 TypedefDecl *getBuiltinMSVaListDecl() const;
1926 /// Retrieve the type of the \c __builtin_ms_va_list type.
1927 QualType getBuiltinMSVaListType() const {
1928 return getTypeDeclType(getBuiltinMSVaListDecl());
1931 /// Return whether a declaration to a builtin is allowed to be
1932 /// overloaded/redeclared.
1933 bool canBuiltinBeRedeclared(const FunctionDecl *) const;
1935 /// Return a type with additional \c const, \c volatile, or
1936 /// \c restrict qualifiers.
1937 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1938 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1941 /// Un-split a SplitQualType.
1942 QualType getQualifiedType(SplitQualType split) const {
1943 return getQualifiedType(split.Ty, split.Quals);
1946 /// Return a type with additional qualifiers.
1947 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1948 if (!Qs.hasNonFastQualifiers())
1949 return T.withFastQualifiers(Qs.getFastQualifiers());
1950 QualifierCollector Qc(Qs);
1951 const Type *Ptr = Qc.strip(T);
1952 return getExtQualType(Ptr, Qc);
1955 /// Return a type with additional qualifiers.
1956 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1957 if (!Qs.hasNonFastQualifiers())
1958 return QualType(T, Qs.getFastQualifiers());
1959 return getExtQualType(T, Qs);
1962 /// Return a type with the given lifetime qualifier.
1964 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1965 QualType getLifetimeQualifiedType(QualType type,
1966 Qualifiers::ObjCLifetime lifetime) {
1967 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1968 assert(lifetime != Qualifiers::OCL_None);
1971 qs.addObjCLifetime(lifetime);
1972 return getQualifiedType(type, qs);
1975 /// getUnqualifiedObjCPointerType - Returns version of
1976 /// Objective-C pointer type with lifetime qualifier removed.
1977 QualType getUnqualifiedObjCPointerType(QualType type) const {
1978 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1979 !type.getQualifiers().hasObjCLifetime())
1981 Qualifiers Qs = type.getQualifiers();
1982 Qs.removeObjCLifetime();
1983 return getQualifiedType(type.getUnqualifiedType(), Qs);
1986 unsigned char getFixedPointScale(QualType Ty) const;
1987 unsigned char getFixedPointIBits(QualType Ty) const;
1988 FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
1989 APFixedPoint getFixedPointMax(QualType Ty) const;
1990 APFixedPoint getFixedPointMin(QualType Ty) const;
1992 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1993 SourceLocation NameLoc) const;
1995 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1996 UnresolvedSetIterator End) const;
1997 TemplateName getAssumedTemplateName(DeclarationName Name) const;
1999 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
2000 bool TemplateKeyword,
2001 TemplateDecl *Template) const;
2003 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
2004 const IdentifierInfo *Name) const;
2005 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
2006 OverloadedOperatorKind Operator) const;
2007 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
2008 TemplateName replacement) const;
2009 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
2010 const TemplateArgument &ArgPack) const;
2012 enum GetBuiltinTypeError {
2019 /// Missing a type from <stdio.h>
2022 /// Missing a type from <setjmp.h>
2025 /// Missing a type from <ucontext.h>
2029 /// Return the type for the specified builtin.
2031 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
2032 /// arguments to the builtin that are required to be integer constant
2034 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
2035 unsigned *IntegerConstantArgs = nullptr) const;
2037 /// Types and expressions required to build C++2a three-way comparisons
2038 /// using operator<=>, including the values return by builtin <=> operators.
2039 ComparisonCategories CompCategories;
2042 CanQualType getFromTargetType(unsigned Type) const;
2043 TypeInfo getTypeInfoImpl(const Type *T) const;
2045 //===--------------------------------------------------------------------===//
2047 //===--------------------------------------------------------------------===//
2050 /// Return one of the GCNone, Weak or Strong Objective-C garbage
2051 /// collection attributes.
2052 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
2054 /// Return true if the given vector types are of the same unqualified
2055 /// type or if they are equivalent to the same GCC vector type.
2057 /// \note This ignores whether they are target-specific (AltiVec or Neon)
2059 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
2061 /// Return true if the type has been explicitly qualified with ObjC ownership.
2062 /// A type may be implicitly qualified with ownership under ObjC ARC, and in
2063 /// some cases the compiler treats these differently.
2064 bool hasDirectOwnershipQualifier(QualType Ty) const;
2066 /// Return true if this is an \c NSObject object with its \c NSObject
2068 static bool isObjCNSObjectType(QualType Ty) {
2069 return Ty->isObjCNSObjectType();
2072 //===--------------------------------------------------------------------===//
2073 // Type Sizing and Analysis
2074 //===--------------------------------------------------------------------===//
2076 /// Return the APFloat 'semantics' for the specified scalar floating
2078 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
2080 /// Get the size and alignment of the specified complete type in bits.
2081 TypeInfo getTypeInfo(const Type *T) const;
2082 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
2084 /// Get default simd alignment of the specified complete type in bits.
2085 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
2087 /// Return the size of the specified (complete) type \p T, in bits.
2088 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
2089 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
2091 /// Return the size of the character type, in bits.
2092 uint64_t getCharWidth() const {
2093 return getTypeSize(CharTy);
2096 /// Convert a size in bits to a size in characters.
2097 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
2099 /// Convert a size in characters to a size in bits.
2100 int64_t toBits(CharUnits CharSize) const;
2102 /// Return the size of the specified (complete) type \p T, in
2104 CharUnits getTypeSizeInChars(QualType T) const;
2105 CharUnits getTypeSizeInChars(const Type *T) const;
2107 Optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const {
2108 if (Ty->isIncompleteType() || Ty->isDependentType())
2110 return getTypeSizeInChars(Ty);
2113 Optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const {
2114 return getTypeSizeInCharsIfKnown(QualType(Ty, 0));
2117 /// Return the ABI-specified alignment of a (complete) type \p T, in
2119 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
2120 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
2122 /// Return the ABI-specified natural alignment of a (complete) type \p T,
2123 /// before alignment adjustments, in bits.
2125 /// This alignment is curently used only by ARM and AArch64 when passing
2126 /// arguments of a composite type.
2127 unsigned getTypeUnadjustedAlign(QualType T) const {
2128 return getTypeUnadjustedAlign(T.getTypePtr());
2130 unsigned getTypeUnadjustedAlign(const Type *T) const;
2132 /// Return the ABI-specified alignment of a type, in bits, or 0 if
2133 /// the type is incomplete and we cannot determine the alignment (for
2134 /// example, from alignment attributes).
2135 unsigned getTypeAlignIfKnown(QualType T) const;
2137 /// Return the ABI-specified alignment of a (complete) type \p T, in
2139 CharUnits getTypeAlignInChars(QualType T) const;
2140 CharUnits getTypeAlignInChars(const Type *T) const;
2142 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
2143 /// in characters, before alignment adjustments. This method does not work on
2144 /// incomplete types.
2145 CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
2146 CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
2148 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
2149 // type is a record, its data size is returned.
2150 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
2152 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
2153 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
2155 /// Determine if the alignment the type has was required using an
2156 /// alignment attribute.
2157 bool isAlignmentRequired(const Type *T) const;
2158 bool isAlignmentRequired(QualType T) const;
2160 /// Return the "preferred" alignment of the specified type \p T for
2161 /// the current target, in bits.
2163 /// This can be different than the ABI alignment in cases where it is
2164 /// beneficial for performance to overalign a data type.
2165 unsigned getPreferredTypeAlign(const Type *T) const;
2167 /// Return the default alignment for __attribute__((aligned)) on
2168 /// this target, to be used if no alignment value is specified.
2169 unsigned getTargetDefaultAlignForAttributeAligned() const;
2171 /// Return the alignment in bits that should be given to a
2172 /// global variable with type \p T.
2173 unsigned getAlignOfGlobalVar(QualType T) const;
2175 /// Return the alignment in characters that should be given to a
2176 /// global variable with type \p T.
2177 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
2179 /// Return a conservative estimate of the alignment of the specified
2182 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
2185 /// If \p ForAlignof, references are treated like their underlying type
2186 /// and large arrays don't get any special treatment. If not \p ForAlignof
2187 /// it computes the value expected by CodeGen: references are treated like
2188 /// pointers and large arrays get extra alignment.
2189 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2191 /// Return the alignment (in bytes) of the thrown exception object. This is
2192 /// only meaningful for targets that allocate C++ exceptions in a system
2193 /// runtime, such as those using the Itanium C++ ABI.
2194 CharUnits getExnObjectAlignment() const {
2195 return toCharUnitsFromBits(Target->getExnObjectAlignment());
2198 /// Get or compute information about the layout of the specified
2199 /// record (struct/union/class) \p D, which indicates its size and field
2200 /// position information.
2201 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2203 /// Get or compute information about the layout of the specified
2204 /// Objective-C interface.
2205 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2208 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2209 bool Simple = false) const;
2211 /// Get or compute information about the layout of the specified
2212 /// Objective-C implementation.
2214 /// This may differ from the interface if synthesized ivars are present.
2215 const ASTRecordLayout &
2216 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2218 /// Get our current best idea for the key function of the
2219 /// given record decl, or nullptr if there isn't one.
2221 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2222 /// ...the first non-pure virtual function that is not inline at the
2223 /// point of class definition.
2225 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
2226 /// virtual functions that are defined 'inline', which means that
2227 /// the result of this computation can change.
2228 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2230 /// Observe that the given method cannot be a key function.
2231 /// Checks the key-function cache for the method's class and clears it
2232 /// if matches the given declaration.
2234 /// This is used in ABIs where out-of-line definitions marked
2235 /// inline are not considered to be key functions.
2237 /// \param method should be the declaration from the class definition
2238 void setNonKeyFunction(const CXXMethodDecl *method);
2240 /// Loading virtual member pointers using the virtual inheritance model
2241 /// always results in an adjustment using the vbtable even if the index is
2244 /// This is usually OK because the first slot in the vbtable points
2245 /// backwards to the top of the MDC. However, the MDC might be reusing a
2246 /// vbptr from an nv-base. In this case, the first slot in the vbtable
2247 /// points to the start of the nv-base which introduced the vbptr and *not*
2248 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
2249 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2251 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2252 uint64_t getFieldOffset(const ValueDecl *FD) const;
2254 /// Get the offset of an ObjCIvarDecl in bits.
2255 uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2256 const ObjCImplementationDecl *ID,
2257 const ObjCIvarDecl *Ivar) const;
2259 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2261 VTableContextBase *getVTableContext();
2263 /// If \p T is null pointer, assume the target in ASTContext.
2264 MangleContext *createMangleContext(const TargetInfo *T = nullptr);
2266 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2267 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2269 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2270 void CollectInheritedProtocols(const Decl *CDecl,
2271 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2273 /// Return true if the specified type has unique object representations
2274 /// according to (C++17 [meta.unary.prop]p9)
2275 bool hasUniqueObjectRepresentations(QualType Ty) const;
2277 //===--------------------------------------------------------------------===//
2279 //===--------------------------------------------------------------------===//
2281 /// Return the canonical (structural) type corresponding to the
2282 /// specified potentially non-canonical type \p T.
2284 /// The non-canonical version of a type may have many "decorated" versions of
2285 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
2286 /// returned type is guaranteed to be free of any of these, allowing two
2287 /// canonical types to be compared for exact equality with a simple pointer
2289 CanQualType getCanonicalType(QualType T) const {
2290 return CanQualType::CreateUnsafe(T.getCanonicalType());
2293 const Type *getCanonicalType(const Type *T) const {
2294 return T->getCanonicalTypeInternal().getTypePtr();
2297 /// Return the canonical parameter type corresponding to the specific
2298 /// potentially non-canonical one.
2300 /// Qualifiers are stripped off, functions are turned into function
2301 /// pointers, and arrays decay one level into pointers.
2302 CanQualType getCanonicalParamType(QualType T) const;
2304 /// Determine whether the given types \p T1 and \p T2 are equivalent.
2305 bool hasSameType(QualType T1, QualType T2) const {
2306 return getCanonicalType(T1) == getCanonicalType(T2);
2308 bool hasSameType(const Type *T1, const Type *T2) const {
2309 return getCanonicalType(T1) == getCanonicalType(T2);
2312 /// Return this type as a completely-unqualified array type,
2313 /// capturing the qualifiers in \p Quals.
2315 /// This will remove the minimal amount of sugaring from the types, similar
2316 /// to the behavior of QualType::getUnqualifiedType().
2318 /// \param T is the qualified type, which may be an ArrayType
2320 /// \param Quals will receive the full set of qualifiers that were
2321 /// applied to the array.
2323 /// \returns if this is an array type, the completely unqualified array type
2324 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2325 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2327 /// Determine whether the given types are equivalent after
2328 /// cvr-qualifiers have been removed.
2329 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2330 return getCanonicalType(T1).getTypePtr() ==
2331 getCanonicalType(T2).getTypePtr();
2334 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2335 bool IsParam) const {
2336 auto SubTnullability = SubT->getNullability(*this);
2337 auto SuperTnullability = SuperT->getNullability(*this);
2338 if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
2339 // Neither has nullability; return true
2340 if (!SubTnullability)
2342 // Both have nullability qualifier.
2343 if (*SubTnullability == *SuperTnullability ||
2344 *SubTnullability == NullabilityKind::Unspecified ||
2345 *SuperTnullability == NullabilityKind::Unspecified)
2349 // Ok for the superclass method parameter to be "nonnull" and the subclass
2350 // method parameter to be "nullable"
2351 return (*SuperTnullability == NullabilityKind::NonNull &&
2352 *SubTnullability == NullabilityKind::Nullable);
2355 // For the return type, it's okay for the superclass method to specify
2356 // "nullable" and the subclass method specify "nonnull"
2357 return (*SuperTnullability == NullabilityKind::Nullable &&
2358 *SubTnullability == NullabilityKind::NonNull);
2364 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2365 const ObjCMethodDecl *MethodImp);
2367 bool UnwrapSimilarTypes(QualType &T1, QualType &T2);
2368 bool UnwrapSimilarArrayTypes(QualType &T1, QualType &T2);
2370 /// Determine if two types are similar, according to the C++ rules. That is,
2371 /// determine if they are the same other than qualifiers on the initial
2372 /// sequence of pointer / pointer-to-member / array (and in Clang, object
2373 /// pointer) types and their element types.
2375 /// Clang offers a number of qualifiers in addition to the C++ qualifiers;
2376 /// those qualifiers are also ignored in the 'similarity' check.
2377 bool hasSimilarType(QualType T1, QualType T2);
2379 /// Determine if two types are similar, ignoring only CVR qualifiers.
2380 bool hasCvrSimilarType(QualType T1, QualType T2);
2382 /// Retrieves the "canonical" nested name specifier for a
2383 /// given nested name specifier.
2385 /// The canonical nested name specifier is a nested name specifier
2386 /// that uniquely identifies a type or namespace within the type
2387 /// system. For example, given:
2392 /// template<typename T> struct X { typename T* type; };
2396 /// template<typename T> struct Y {
2397 /// typename N::S::X<T>::type member;
2401 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2402 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2403 /// by declarations in the type system and the canonical type for
2404 /// the template type parameter 'T' is template-param-0-0.
2405 NestedNameSpecifier *
2406 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2408 /// Retrieves the default calling convention for the current target.
2409 CallingConv getDefaultCallingConvention(bool IsVariadic,
2411 bool IsBuiltin = false) const;
2413 /// Retrieves the "canonical" template name that refers to a
2416 /// The canonical template name is the simplest expression that can
2417 /// be used to refer to a given template. For most templates, this
2418 /// expression is just the template declaration itself. For example,
2419 /// the template std::vector can be referred to via a variety of
2420 /// names---std::vector, \::std::vector, vector (if vector is in
2421 /// scope), etc.---but all of these names map down to the same
2422 /// TemplateDecl, which is used to form the canonical template name.
2424 /// Dependent template names are more interesting. Here, the
2425 /// template name could be something like T::template apply or
2426 /// std::allocator<T>::template rebind, where the nested name
2427 /// specifier itself is dependent. In this case, the canonical
2428 /// template name uses the shortest form of the dependent
2429 /// nested-name-specifier, which itself contains all canonical
2430 /// types, values, and templates.
2431 TemplateName getCanonicalTemplateName(TemplateName Name) const;
2433 /// Determine whether the given template names refer to the same
2435 bool hasSameTemplateName(TemplateName X, TemplateName Y);
2437 /// Retrieve the "canonical" template argument.
2439 /// The canonical template argument is the simplest template argument
2440 /// (which may be a type, value, expression, or declaration) that
2441 /// expresses the value of the argument.
2442 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2445 /// Type Query functions. If the type is an instance of the specified class,
2446 /// return the Type pointer for the underlying maximally pretty type. This
2447 /// is a member of ASTContext because this may need to do some amount of
2448 /// canonicalization, e.g. to move type qualifiers into the element type.
2449 const ArrayType *getAsArrayType(QualType T) const;
2450 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2451 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2453 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2454 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2456 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2457 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2459 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2461 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2464 /// Return the innermost element type of an array type.
2466 /// For example, will return "int" for int[m][n]
2467 QualType getBaseElementType(const ArrayType *VAT) const;
2469 /// Return the innermost element type of a type (which needn't
2470 /// actually be an array type).
2471 QualType getBaseElementType(QualType QT) const;
2473 /// Return number of constant array elements.
2474 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2476 /// Perform adjustment on the parameter type of a function.
2478 /// This routine adjusts the given parameter type @p T to the actual
2479 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2480 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2481 QualType getAdjustedParameterType(QualType T) const;
2483 /// Retrieve the parameter type as adjusted for use in the signature
2484 /// of a function, decaying array and function types and removing top-level
2486 QualType getSignatureParameterType(QualType T) const;
2488 QualType getExceptionObjectType(QualType T) const;
2490 /// Return the properly qualified result of decaying the specified
2491 /// array type to a pointer.
2493 /// This operation is non-trivial when handling typedefs etc. The canonical
2494 /// type of \p T must be an array type, this returns a pointer to a properly
2495 /// qualified element of the array.
2497 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2498 QualType getArrayDecayedType(QualType T) const;
2500 /// Return the type that \p PromotableType will promote to: C99
2501 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2502 QualType getPromotedIntegerType(QualType PromotableType) const;
2504 /// Recurses in pointer/array types until it finds an Objective-C
2505 /// retainable type and returns its ownership.
2506 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2508 /// Whether this is a promotable bitfield reference according
2509 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2511 /// \returns the type this bit-field will promote to, or NULL if no
2512 /// promotion occurs.
2513 QualType isPromotableBitField(Expr *E) const;
2515 /// Return the highest ranked integer type, see C99 6.3.1.8p1.
2517 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2518 /// \p LHS < \p RHS, return -1.
2519 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2521 /// Compare the rank of the two specified floating point types,
2522 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2524 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2525 /// \p LHS < \p RHS, return -1.
2526 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2528 /// Compare the rank of two floating point types as above, but compare equal
2529 /// if both types have the same floating-point semantics on the target (i.e.
2530 /// long double and double on AArch64 will return 0).
2531 int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const;
2533 /// Return a real floating point or a complex type (based on
2534 /// \p typeDomain/\p typeSize).
2536 /// \param typeDomain a real floating point or complex type.
2537 /// \param typeSize a real floating point or complex type.
2538 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2539 QualType typeDomain) const;
2541 unsigned getTargetAddressSpace(QualType T) const {
2542 return getTargetAddressSpace(T.getQualifiers());
2545 unsigned getTargetAddressSpace(Qualifiers Q) const {
2546 return getTargetAddressSpace(Q.getAddressSpace());
2549 unsigned getTargetAddressSpace(LangAS AS) const;
2551 LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;
2553 /// Get target-dependent integer value for null pointer which is used for
2554 /// constant folding.
2555 uint64_t getTargetNullPointerValue(QualType QT) const;
2557 bool addressSpaceMapManglingFor(LangAS AS) const {
2558 return AddrSpaceMapMangling || isTargetAddressSpace(AS);
2562 // Helper for integer ordering
2563 unsigned getIntegerRank(const Type *T) const;
2566 //===--------------------------------------------------------------------===//
2567 // Type Compatibility Predicates
2568 //===--------------------------------------------------------------------===//
2570 /// Compatibility predicates used to check assignment expressions.
2571 bool typesAreCompatible(QualType T1, QualType T2,
2572 bool CompareUnqualified = false); // C99 6.2.7p1
2574 bool propertyTypesAreCompatible(QualType, QualType);
2575 bool typesAreBlockPointerCompatible(QualType, QualType);
2577 bool isObjCIdType(QualType T) const {
2578 return T == getObjCIdType();
2581 bool isObjCClassType(QualType T) const {
2582 return T == getObjCClassType();
2585 bool isObjCSelType(QualType T) const {
2586 return T == getObjCSelType();
2589 bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS,
2590 const ObjCObjectPointerType *RHS,
2593 bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS,
2594 const ObjCObjectPointerType *RHS);
2596 // Check the safety of assignment from LHS to RHS
2597 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2598 const ObjCObjectPointerType *RHSOPT);
2599 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2600 const ObjCObjectType *RHS);
2601 bool canAssignObjCInterfacesInBlockPointer(
2602 const ObjCObjectPointerType *LHSOPT,
2603 const ObjCObjectPointerType *RHSOPT,
2604 bool BlockReturnType);
2605 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2606 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2607 const ObjCObjectPointerType *RHSOPT);
2608 bool canBindObjCObjectType(QualType To, QualType From);
2610 // Functions for calculating composite types
2611 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2612 bool Unqualified = false, bool BlockReturnType = false);
2613 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2614 bool Unqualified = false);
2615 QualType mergeFunctionParameterTypes(QualType, QualType,
2616 bool OfBlockPointer = false,
2617 bool Unqualified = false);
2618 QualType mergeTransparentUnionType(QualType, QualType,
2619 bool OfBlockPointer=false,
2620 bool Unqualified = false);
2622 QualType mergeObjCGCQualifiers(QualType, QualType);
2624 /// This function merges the ExtParameterInfo lists of two functions. It
2625 /// returns true if the lists are compatible. The merged list is returned in
2628 /// \param FirstFnType The type of the first function.
2630 /// \param SecondFnType The type of the second function.
2632 /// \param CanUseFirst This flag is set to true if the first function's
2633 /// ExtParameterInfo list can be used as the composite list of
2634 /// ExtParameterInfo.
2636 /// \param CanUseSecond This flag is set to true if the second function's
2637 /// ExtParameterInfo list can be used as the composite list of
2638 /// ExtParameterInfo.
2640 /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
2641 /// empty if none of the flags are set.
2643 bool mergeExtParameterInfo(
2644 const FunctionProtoType *FirstFnType,
2645 const FunctionProtoType *SecondFnType,
2646 bool &CanUseFirst, bool &CanUseSecond,
2647 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
2649 void ResetObjCLayout(const ObjCContainerDecl *CD);
2651 //===--------------------------------------------------------------------===//
2652 // Integer Predicates
2653 //===--------------------------------------------------------------------===//
2655 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2656 // of bits in an integer type excluding any padding bits.
2657 unsigned getIntWidth(QualType T) const;
2659 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2660 // unsigned integer type. This method takes a signed type, and returns the
2661 // corresponding unsigned integer type.
2662 // With the introduction of fixed point types in ISO N1169, this method also
2663 // accepts fixed point types and returns the corresponding unsigned type for
2664 // a given fixed point type.
2665 QualType getCorrespondingUnsignedType(QualType T) const;
2667 // Per ISO N1169, this method accepts fixed point types and returns the
2668 // corresponding saturated type for a given fixed point type.
2669 QualType getCorrespondingSaturatedType(QualType Ty) const;
2671 // This method accepts fixed point types and returns the corresponding signed
2672 // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned
2673 // fixed point types because there are unsigned integer types like bool and
2674 // char8_t that don't have signed equivalents.
2675 QualType getCorrespondingSignedFixedPointType(QualType Ty) const;
2677 //===--------------------------------------------------------------------===//
2679 //===--------------------------------------------------------------------===//
2681 /// Make an APSInt of the appropriate width and signedness for the
2682 /// given \p Value and integer \p Type.
2683 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2684 // If Type is a signed integer type larger than 64 bits, we need to be sure
2685 // to sign extend Res appropriately.
2686 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2688 unsigned Width = getIntWidth(Type);
2689 if (Width != Res.getBitWidth())
2690 return Res.extOrTrunc(Width);
2694 bool isSentinelNullExpr(const Expr *E);
2696 /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
2698 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2700 /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
2702 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2704 /// Return true if there is at least one \@implementation in the TU.
2705 bool AnyObjCImplementation() {
2706 return !ObjCImpls.empty();
2709 /// Set the implementation of ObjCInterfaceDecl.
2710 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2711 ObjCImplementationDecl *ImplD);
2713 /// Set the implementation of ObjCCategoryDecl.
2714 void setObjCImplementation(ObjCCategoryDecl *CatD,
2715 ObjCCategoryImplDecl *ImplD);
2717 /// Get the duplicate declaration of a ObjCMethod in the same
2718 /// interface, or null if none exists.
2719 const ObjCMethodDecl *
2720 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2722 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2723 const ObjCMethodDecl *Redecl);
2725 /// Returns the Objective-C interface that \p ND belongs to if it is
2726 /// an Objective-C method/property/ivar etc. that is part of an interface,
2727 /// otherwise returns null.
2728 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2730 /// Set the copy initialization expression of a block var decl. \p CanThrow
2731 /// indicates whether the copy expression can throw or not.
2732 void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow);
2734 /// Get the copy initialization expression of the VarDecl \p VD, or
2735 /// nullptr if none exists.
2736 BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const;
2738 /// Allocate an uninitialized TypeSourceInfo.
2740 /// The caller should initialize the memory held by TypeSourceInfo using
2741 /// the TypeLoc wrappers.
2743 /// \param T the type that will be the basis for type source info. This type
2744 /// should refer to how the declarator was written in source code, not to
2745 /// what type semantic analysis resolved the declarator to.
2747 /// \param Size the size of the type info to create, or 0 if the size
2748 /// should be calculated based on the type.
2749 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2751 /// Allocate a TypeSourceInfo where all locations have been
2752 /// initialized to a given location, which defaults to the empty
2755 getTrivialTypeSourceInfo(QualType T,
2756 SourceLocation Loc = SourceLocation()) const;
2758 /// Add a deallocation callback that will be invoked when the
2759 /// ASTContext is destroyed.
2761 /// \param Callback A callback function that will be invoked on destruction.
2763 /// \param Data Pointer data that will be provided to the callback function
2764 /// when it is called.
2765 void AddDeallocation(void (*Callback)(void *), void *Data) const;
2767 /// If T isn't trivially destructible, calls AddDeallocation to register it
2768 /// for destruction.
2769 template <typename T> void addDestruction(T *Ptr) const {
2770 if (!std::is_trivially_destructible<T>::value) {
2771 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
2772 AddDeallocation(DestroyPtr, Ptr);
2776 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2777 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2779 /// Determines if the decl can be CodeGen'ed or deserialized from PCH
2780 /// lazily, only when used; this is only relevant for function or file scoped
2781 /// var definitions.
2783 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2785 bool DeclMustBeEmitted(const Decl *D);
2787 /// Visits all versions of a multiversioned function with the passed
2789 void forEachMultiversionedFunctionVersion(
2790 const FunctionDecl *FD,
2791 llvm::function_ref<void(FunctionDecl *)> Pred) const;
2793 const CXXConstructorDecl *
2794 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2796 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2797 CXXConstructorDecl *CD);
2799 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2801 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2803 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2805 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2807 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2808 unsigned getManglingNumber(const NamedDecl *ND) const;
2810 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2811 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2813 /// Retrieve the context for computing mangling numbers in the given
2815 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2816 enum NeedExtraManglingDecl_t { NeedExtraManglingDecl };
2817 MangleNumberingContext &getManglingNumberContext(NeedExtraManglingDecl_t,
2820 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
2822 /// Used by ParmVarDecl to store on the side the
2823 /// index of the parameter when it exceeds the size of the normal bitfield.
2824 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2826 /// Used by ParmVarDecl to retrieve on the side the
2827 /// index of the parameter when it exceeds the size of the normal bitfield.
2828 unsigned getParameterIndex(const ParmVarDecl *D) const;
2830 /// Get the storage for the constant value of a materialized temporary
2831 /// of static storage duration.
2832 APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
2835 /// Return a string representing the human readable name for the specified
2836 /// function declaration or file name. Used by SourceLocExpr and
2837 /// PredefinedExpr to cache evaluated results.
2838 StringLiteral *getPredefinedStringLiteralFromCache(StringRef Key) const;
2840 //===--------------------------------------------------------------------===//
2842 //===--------------------------------------------------------------------===//
2844 /// The number of implicitly-declared default constructors.
2845 unsigned NumImplicitDefaultConstructors = 0;
2847 /// The number of implicitly-declared default constructors for
2848 /// which declarations were built.
2849 unsigned NumImplicitDefaultConstructorsDeclared = 0;
2851 /// The number of implicitly-declared copy constructors.
2852 unsigned NumImplicitCopyConstructors = 0;
2854 /// The number of implicitly-declared copy constructors for
2855 /// which declarations were built.
2856 unsigned NumImplicitCopyConstructorsDeclared = 0;
2858 /// The number of implicitly-declared move constructors.
2859 unsigned NumImplicitMoveConstructors = 0;
2861 /// The number of implicitly-declared move constructors for
2862 /// which declarations were built.
2863 unsigned NumImplicitMoveConstructorsDeclared = 0;
2865 /// The number of implicitly-declared copy assignment operators.
2866 unsigned NumImplicitCopyAssignmentOperators = 0;
2868 /// The number of implicitly-declared copy assignment operators for
2869 /// which declarations were built.
2870 unsigned NumImplicitCopyAssignmentOperatorsDeclared = 0;
2872 /// The number of implicitly-declared move assignment operators.
2873 unsigned NumImplicitMoveAssignmentOperators = 0;
2875 /// The number of implicitly-declared move assignment operators for
2876 /// which declarations were built.
2877 unsigned NumImplicitMoveAssignmentOperatorsDeclared = 0;
2879 /// The number of implicitly-declared destructors.
2880 unsigned NumImplicitDestructors = 0;
2882 /// The number of implicitly-declared destructors for which
2883 /// declarations were built.
2884 unsigned NumImplicitDestructorsDeclared = 0;
2887 /// Initialize built-in types.
2889 /// This routine may only be invoked once for a given ASTContext object.
2890 /// It is normally invoked after ASTContext construction.
2892 /// \param Target The target
2893 void InitBuiltinTypes(const TargetInfo &Target,
2894 const TargetInfo *AuxTarget = nullptr);
2897 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2899 class ObjCEncOptions {
2902 ObjCEncOptions(unsigned Bits) : Bits(Bits) {}
2905 ObjCEncOptions() : Bits(0) {}
2906 ObjCEncOptions(const ObjCEncOptions &RHS) : Bits(RHS.Bits) {}
2908 #define OPT_LIST(V) \
2909 V(ExpandPointedToStructures, 0) \
2910 V(ExpandStructures, 1) \
2911 V(IsOutermostType, 2) \
2912 V(EncodingProperty, 3) \
2913 V(IsStructField, 4) \
2914 V(EncodeBlockParameters, 5) \
2915 V(EncodeClassNames, 6) \
2917 #define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; }
2921 #define V(N,I) bool N() const { return Bits & 1 << I; }
2927 LLVM_NODISCARD ObjCEncOptions keepingOnly(ObjCEncOptions Mask) const {
2928 return Bits & Mask.Bits;
2931 LLVM_NODISCARD ObjCEncOptions forComponentType() const {
2932 ObjCEncOptions Mask = ObjCEncOptions()
2933 .setIsOutermostType()
2934 .setIsStructField();
2935 return Bits & ~Mask.Bits;
2939 // Return the Objective-C type encoding for a given type.
2940 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2941 ObjCEncOptions Options,
2942 const FieldDecl *Field,
2943 QualType *NotEncodedT = nullptr) const;
2945 // Adds the encoding of the structure's members.
2946 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2947 const FieldDecl *Field,
2948 bool includeVBases = true,
2949 QualType *NotEncodedT=nullptr) const;
2952 // Adds the encoding of a method parameter or return type.
2953 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2954 QualType T, std::string& S,
2955 bool Extended) const;
2957 /// Returns true if this is an inline-initialized static data member
2958 /// which is treated as a definition for MSVC compatibility.
2959 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2961 enum class InlineVariableDefinitionKind {
2962 /// Not an inline variable.
2965 /// Weak definition of inline variable.
2968 /// Weak for now, might become strong later in this TU.
2971 /// Strong definition.
2975 /// Determine whether a definition of this inline variable should
2976 /// be treated as a weak or strong definition. For compatibility with
2977 /// C++14 and before, for a constexpr static data member, if there is an
2978 /// out-of-line declaration of the member, we may promote it from weak to
2980 InlineVariableDefinitionKind
2981 getInlineVariableDefinitionKind(const VarDecl *VD) const;
2984 friend class DeclarationNameTable;
2985 friend class DeclContext;
2987 const ASTRecordLayout &
2988 getObjCLayout(const ObjCInterfaceDecl *D,
2989 const ObjCImplementationDecl *Impl) const;
2991 /// A set of deallocations that should be performed when the
2992 /// ASTContext is destroyed.
2993 // FIXME: We really should have a better mechanism in the ASTContext to
2994 // manage running destructors for types which do variable sized allocation
2995 // within the AST. In some places we thread the AST bump pointer allocator
2996 // into the datastructures which avoids this mess during deallocation but is
2997 // wasteful of memory, and here we require a lot of error prone book keeping
2998 // in order to track and run destructors while we're tearing things down.
2999 using DeallocationFunctionsAndArguments =
3000 llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
3001 mutable DeallocationFunctionsAndArguments Deallocations;
3003 // FIXME: This currently contains the set of StoredDeclMaps used
3004 // by DeclContext objects. This probably should not be in ASTContext,
3005 // but we include it here so that ASTContext can quickly deallocate them.
3006 llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
3008 std::vector<Decl *> TraversalScope;
3010 std::unique_ptr<ParentMap> Parents;
3012 std::unique_ptr<VTableContextBase> VTContext;
3014 void ReleaseDeclContextMaps();
3017 enum PragmaSectionFlag : unsigned {
3023 PSF_Invalid = 0x80000000U,
3026 struct SectionInfo {
3027 DeclaratorDecl *Decl;
3028 SourceLocation PragmaSectionLocation;
3031 SectionInfo() = default;
3032 SectionInfo(DeclaratorDecl *Decl,
3033 SourceLocation PragmaSectionLocation,
3035 : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
3036 SectionFlags(SectionFlags) {}
3039 llvm::StringMap<SectionInfo> SectionInfos;
3042 /// Utility function for constructing a nullary selector.
3043 inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
3044 IdentifierInfo* II = &Ctx.Idents.get(name);
3045 return Ctx.Selectors.getSelector(0, &II);
3048 /// Utility function for constructing an unary selector.
3049 inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
3050 IdentifierInfo* II = &Ctx.Idents.get(name);
3051 return Ctx.Selectors.getSelector(1, &II);
3054 } // namespace clang
3056 // operator new and delete aren't allowed inside namespaces.
3058 /// Placement new for using the ASTContext's allocator.
3060 /// This placement form of operator new uses the ASTContext's allocator for
3061 /// obtaining memory.
3063 /// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h!
3064 /// Any changes here need to also be made there.
3066 /// We intentionally avoid using a nothrow specification here so that the calls
3067 /// to this operator will not perform a null check on the result -- the
3068 /// underlying allocator never returns null pointers.
3070 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3072 /// // Default alignment (8)
3073 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
3074 /// // Specific alignment
3075 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
3077 /// Memory allocated through this placement new operator does not need to be
3078 /// explicitly freed, as ASTContext will free all of this memory when it gets
3079 /// destroyed. Please note that you cannot use delete on the pointer.
3081 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3082 /// @param C The ASTContext that provides the allocator.
3083 /// @param Alignment The alignment of the allocated memory (if the underlying
3084 /// allocator supports it).
3085 /// @return The allocated memory. Could be nullptr.
3086 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
3087 size_t Alignment /* = 8 */) {
3088 return C.Allocate(Bytes, Alignment);
3091 /// Placement delete companion to the new above.
3093 /// This operator is just a companion to the new above. There is no way of
3094 /// invoking it directly; see the new operator for more details. This operator
3095 /// is called implicitly by the compiler if a placement new expression using
3096 /// the ASTContext throws in the object constructor.
3097 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
3101 /// This placement form of operator new[] uses the ASTContext's allocator for
3102 /// obtaining memory.
3104 /// We intentionally avoid using a nothrow specification here so that the calls
3105 /// to this operator will not perform a null check on the result -- the
3106 /// underlying allocator never returns null pointers.
3108 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3110 /// // Default alignment (8)
3111 /// char *data = new (Context) char[10];
3112 /// // Specific alignment
3113 /// char *data = new (Context, 4) char[10];
3115 /// Memory allocated through this placement new[] operator does not need to be
3116 /// explicitly freed, as ASTContext will free all of this memory when it gets
3117 /// destroyed. Please note that you cannot use delete on the pointer.
3119 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3120 /// @param C The ASTContext that provides the allocator.
3121 /// @param Alignment The alignment of the allocated memory (if the underlying
3122 /// allocator supports it).
3123 /// @return The allocated memory. Could be nullptr.
3124 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
3125 size_t Alignment /* = 8 */) {
3126 return C.Allocate(Bytes, Alignment);
3129 /// Placement delete[] companion to the new[] above.
3131 /// This operator is just a companion to the new[] above. There is no way of
3132 /// invoking it directly; see the new[] operator for more details. This operator
3133 /// is called implicitly by the compiler if a placement new[] expression using
3134 /// the ASTContext throws in the object constructor.
3135 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
3139 /// Create the representation of a LazyGenerationalUpdatePtr.
3140 template <typename Owner, typename T,
3141 void (clang::ExternalASTSource::*Update)(Owner)>
3142 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
3143 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
3144 const clang::ASTContext &Ctx, T Value) {
3145 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
3146 // include ASTContext.h. We explicitly instantiate it for all relevant types
3147 // in ASTContext.cpp.
3148 if (auto *Source = Ctx.getExternalSource())
3149 return new (Ctx) LazyData(Source, Value);
3153 #endif // LLVM_CLANG_AST_ASTCONTEXT_H