1 //===- ASTContext.h - Context to hold long-lived AST nodes ------*- C++ -*-===// 2 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Defines the clang::ASTContext interface. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_CLANG_AST_ASTCONTEXT_H 15 #define LLVM_CLANG_AST_ASTCONTEXT_H 16 17 #include "clang/AST/ASTContextAllocate.h" 18 #include "clang/AST/ASTFwd.h" 19 #include "clang/AST/CanonicalType.h" 20 #include "clang/AST/CommentCommandTraits.h" 21 #include "clang/AST/ComparisonCategories.h" 22 #include "clang/AST/Decl.h" 23 #include "clang/AST/DeclBase.h" 24 #include "clang/AST/DeclarationName.h" 25 #include "clang/AST/ExternalASTSource.h" 26 #include "clang/AST/NestedNameSpecifier.h" 27 #include "clang/AST/PrettyPrinter.h" 28 #include "clang/AST/RawCommentList.h" 29 #include "clang/AST/TemplateName.h" 30 #include "clang/AST/Type.h" 31 #include "clang/Basic/AddressSpaces.h" 32 #include "clang/Basic/AttrKinds.h" 33 #include "clang/Basic/IdentifierTable.h" 34 #include "clang/Basic/LLVM.h" 35 #include "clang/Basic/LangOptions.h" 36 #include "clang/Basic/Linkage.h" 37 #include "clang/Basic/NoSanitizeList.h" 38 #include "clang/Basic/OperatorKinds.h" 39 #include "clang/Basic/PartialDiagnostic.h" 40 #include "clang/Basic/ProfileList.h" 41 #include "clang/Basic/SourceLocation.h" 42 #include "clang/Basic/Specifiers.h" 43 #include "clang/Basic/TargetCXXABI.h" 44 #include "clang/Basic/XRayLists.h" 45 #include "llvm/ADT/APSInt.h" 46 #include "llvm/ADT/ArrayRef.h" 47 #include "llvm/ADT/DenseMap.h" 48 #include "llvm/ADT/DenseSet.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" 66 #include "llvm/Support/TypeSize.h" 67 #include <cassert> 68 #include <cstddef> 69 #include <cstdint> 70 #include <iterator> 71 #include <memory> 72 #include <string> 73 #include <type_traits> 74 #include <utility> 75 #include <vector> 76 77 namespace llvm { 78 79 class APFixedPoint; 80 class FixedPointSemantics; 81 struct fltSemantics; 82 template <typename T, unsigned N> class SmallPtrSet; 83 84 } // namespace llvm 85 86 namespace clang { 87 88 class APValue; 89 class ASTMutationListener; 90 class ASTRecordLayout; 91 class AtomicExpr; 92 class BlockExpr; 93 class BuiltinTemplateDecl; 94 class CharUnits; 95 class ConceptDecl; 96 class CXXABI; 97 class CXXConstructorDecl; 98 class CXXMethodDecl; 99 class CXXRecordDecl; 100 class DiagnosticsEngine; 101 class ParentMapContext; 102 class DynTypedNodeList; 103 class Expr; 104 enum class FloatModeKind; 105 class GlobalDecl; 106 class MangleContext; 107 class MangleNumberingContext; 108 class MemberSpecializationInfo; 109 class Module; 110 struct MSGuidDeclParts; 111 class ObjCCategoryDecl; 112 class ObjCCategoryImplDecl; 113 class ObjCContainerDecl; 114 class ObjCImplDecl; 115 class ObjCImplementationDecl; 116 class ObjCInterfaceDecl; 117 class ObjCIvarDecl; 118 class ObjCMethodDecl; 119 class ObjCPropertyDecl; 120 class ObjCPropertyImplDecl; 121 class ObjCProtocolDecl; 122 class ObjCTypeParamDecl; 123 class OMPTraitInfo; 124 struct ParsedTargetAttr; 125 class Preprocessor; 126 class StoredDeclsMap; 127 class TargetAttr; 128 class TargetInfo; 129 class TemplateDecl; 130 class TemplateParameterList; 131 class TemplateTemplateParmDecl; 132 class TemplateTypeParmDecl; 133 class TypeConstraint; 134 class UnresolvedSetIterator; 135 class UsingShadowDecl; 136 class VarTemplateDecl; 137 class VTableContextBase; 138 struct BlockVarCopyInit; 139 140 namespace Builtin { 141 142 class Context; 143 144 } // namespace Builtin 145 146 enum BuiltinTemplateKind : int; 147 enum OpenCLTypeKind : uint8_t; 148 149 namespace comments { 150 151 class FullComment; 152 153 } // namespace comments 154 155 namespace interp { 156 157 class Context; 158 159 } // namespace interp 160 161 namespace serialization { 162 template <class> class AbstractTypeReader; 163 } // namespace serialization 164 165 enum class AlignRequirementKind { 166 /// The alignment was not explicit in code. 167 None, 168 169 /// The alignment comes from an alignment attribute on a typedef. 170 RequiredByTypedef, 171 172 /// The alignment comes from an alignment attribute on a record type. 173 RequiredByRecord, 174 175 /// The alignment comes from an alignment attribute on a enum type. 176 RequiredByEnum, 177 }; 178 179 struct TypeInfo { 180 uint64_t Width = 0; 181 unsigned Align = 0; 182 AlignRequirementKind AlignRequirement; 183 184 TypeInfo() : AlignRequirement(AlignRequirementKind::None) {} 185 TypeInfo(uint64_t Width, unsigned Align, 186 AlignRequirementKind AlignRequirement) 187 : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {} 188 bool isAlignRequired() { 189 return AlignRequirement != AlignRequirementKind::None; 190 } 191 }; 192 193 struct TypeInfoChars { 194 CharUnits Width; 195 CharUnits Align; 196 AlignRequirementKind AlignRequirement; 197 198 TypeInfoChars() : AlignRequirement(AlignRequirementKind::None) {} 199 TypeInfoChars(CharUnits Width, CharUnits Align, 200 AlignRequirementKind AlignRequirement) 201 : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {} 202 bool isAlignRequired() { 203 return AlignRequirement != AlignRequirementKind::None; 204 } 205 }; 206 207 /// Holds long-lived AST nodes (such as types and decls) that can be 208 /// referred to throughout the semantic analysis of a file. 209 class ASTContext : public RefCountedBase<ASTContext> { 210 friend class NestedNameSpecifier; 211 212 mutable SmallVector<Type *, 0> Types; 213 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes; 214 mutable llvm::FoldingSet<ComplexType> ComplexTypes; 215 mutable llvm::FoldingSet<PointerType> PointerTypes{GeneralTypesLog2InitSize}; 216 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes; 217 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes; 218 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes; 219 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes; 220 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes; 221 mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &> 222 ConstantArrayTypes; 223 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes; 224 mutable std::vector<VariableArrayType*> VariableArrayTypes; 225 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes; 226 mutable llvm::FoldingSet<DependentSizedExtVectorType> 227 DependentSizedExtVectorTypes; 228 mutable llvm::FoldingSet<DependentAddressSpaceType> 229 DependentAddressSpaceTypes; 230 mutable llvm::FoldingSet<VectorType> VectorTypes; 231 mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes; 232 mutable llvm::FoldingSet<ConstantMatrixType> MatrixTypes; 233 mutable llvm::FoldingSet<DependentSizedMatrixType> DependentSizedMatrixTypes; 234 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes; 235 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&> 236 FunctionProtoTypes; 237 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes; 238 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes; 239 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes; 240 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes; 241 mutable llvm::FoldingSet<SubstTemplateTypeParmType> 242 SubstTemplateTypeParmTypes; 243 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType> 244 SubstTemplateTypeParmPackTypes; 245 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&> 246 TemplateSpecializationTypes; 247 mutable llvm::FoldingSet<ParenType> ParenTypes{GeneralTypesLog2InitSize}; 248 mutable llvm::FoldingSet<UsingType> UsingTypes; 249 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes{ 250 GeneralTypesLog2InitSize}; 251 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes; 252 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType, 253 ASTContext&> 254 DependentTemplateSpecializationTypes; 255 llvm::FoldingSet<PackExpansionType> PackExpansionTypes; 256 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes; 257 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes; 258 mutable llvm::FoldingSet<DependentUnaryTransformType> 259 DependentUnaryTransformTypes; 260 mutable llvm::ContextualFoldingSet<AutoType, ASTContext&> AutoTypes; 261 mutable llvm::FoldingSet<DeducedTemplateSpecializationType> 262 DeducedTemplateSpecializationTypes; 263 mutable llvm::FoldingSet<AtomicType> AtomicTypes; 264 mutable llvm::FoldingSet<AttributedType> AttributedTypes; 265 mutable llvm::FoldingSet<PipeType> PipeTypes; 266 mutable llvm::FoldingSet<BitIntType> BitIntTypes; 267 mutable llvm::FoldingSet<DependentBitIntType> DependentBitIntTypes; 268 llvm::FoldingSet<BTFTagAttributedType> BTFTagAttributedTypes; 269 270 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames; 271 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames; 272 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage> 273 SubstTemplateTemplateParms; 274 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage, 275 ASTContext&> 276 SubstTemplateTemplateParmPacks; 277 278 /// The set of nested name specifiers. 279 /// 280 /// This set is managed by the NestedNameSpecifier class. 281 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers; 282 mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr; 283 284 /// A cache mapping from RecordDecls to ASTRecordLayouts. 285 /// 286 /// This is lazily created. This is intentionally not serialized. 287 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*> 288 ASTRecordLayouts; 289 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*> 290 ObjCLayouts; 291 292 /// A cache from types to size and alignment information. 293 using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>; 294 mutable TypeInfoMap MemoizedTypeInfo; 295 296 /// A cache from types to unadjusted alignment information. Only ARM and 297 /// AArch64 targets need this information, keeping it separate prevents 298 /// imposing overhead on TypeInfo size. 299 using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>; 300 mutable UnadjustedAlignMap MemoizedUnadjustedAlign; 301 302 /// A cache mapping from CXXRecordDecls to key functions. 303 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions; 304 305 /// Mapping from ObjCContainers to their ObjCImplementations. 306 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls; 307 308 /// Mapping from ObjCMethod to its duplicate declaration in the same 309 /// interface. 310 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls; 311 312 /// Mapping from __block VarDecls to BlockVarCopyInit. 313 llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits; 314 315 /// Mapping from GUIDs to the corresponding MSGuidDecl. 316 mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls; 317 318 /// Mapping from APValues to the corresponding UnnamedGlobalConstantDecl. 319 mutable llvm::FoldingSet<UnnamedGlobalConstantDecl> 320 UnnamedGlobalConstantDecls; 321 322 /// Mapping from APValues to the corresponding TemplateParamObjects. 323 mutable llvm::FoldingSet<TemplateParamObjectDecl> TemplateParamObjectDecls; 324 325 /// A cache mapping a string value to a StringLiteral object with the same 326 /// value. 327 /// 328 /// This is lazily created. This is intentionally not serialized. 329 mutable llvm::StringMap<StringLiteral *> StringLiteralCache; 330 331 /// MD5 hash of CUID. It is calculated when first used and cached by this 332 /// data member. 333 mutable std::string CUIDHash; 334 335 /// Representation of a "canonical" template template parameter that 336 /// is used in canonical template names. 337 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode { 338 TemplateTemplateParmDecl *Parm; 339 340 public: 341 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm) 342 : Parm(Parm) {} 343 344 TemplateTemplateParmDecl *getParam() const { return Parm; } 345 346 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) { 347 Profile(ID, C, Parm); 348 } 349 350 static void Profile(llvm::FoldingSetNodeID &ID, 351 const ASTContext &C, 352 TemplateTemplateParmDecl *Parm); 353 }; 354 mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm, 355 const ASTContext&> 356 CanonTemplateTemplateParms; 357 358 TemplateTemplateParmDecl * 359 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const; 360 361 /// The typedef for the __int128_t type. 362 mutable TypedefDecl *Int128Decl = nullptr; 363 364 /// The typedef for the __uint128_t type. 365 mutable TypedefDecl *UInt128Decl = nullptr; 366 367 /// The typedef for the target specific predefined 368 /// __builtin_va_list type. 369 mutable TypedefDecl *BuiltinVaListDecl = nullptr; 370 371 /// The typedef for the predefined \c __builtin_ms_va_list type. 372 mutable TypedefDecl *BuiltinMSVaListDecl = nullptr; 373 374 /// The typedef for the predefined \c id type. 375 mutable TypedefDecl *ObjCIdDecl = nullptr; 376 377 /// The typedef for the predefined \c SEL type. 378 mutable TypedefDecl *ObjCSelDecl = nullptr; 379 380 /// The typedef for the predefined \c Class type. 381 mutable TypedefDecl *ObjCClassDecl = nullptr; 382 383 /// The typedef for the predefined \c Protocol class in Objective-C. 384 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr; 385 386 /// The typedef for the predefined 'BOOL' type. 387 mutable TypedefDecl *BOOLDecl = nullptr; 388 389 // Typedefs which may be provided defining the structure of Objective-C 390 // pseudo-builtins 391 QualType ObjCIdRedefinitionType; 392 QualType ObjCClassRedefinitionType; 393 QualType ObjCSelRedefinitionType; 394 395 /// The identifier 'bool'. 396 mutable IdentifierInfo *BoolName = nullptr; 397 398 /// The identifier 'NSObject'. 399 mutable IdentifierInfo *NSObjectName = nullptr; 400 401 /// The identifier 'NSCopying'. 402 IdentifierInfo *NSCopyingName = nullptr; 403 404 /// The identifier '__make_integer_seq'. 405 mutable IdentifierInfo *MakeIntegerSeqName = nullptr; 406 407 /// The identifier '__type_pack_element'. 408 mutable IdentifierInfo *TypePackElementName = nullptr; 409 410 QualType ObjCConstantStringType; 411 mutable RecordDecl *CFConstantStringTagDecl = nullptr; 412 mutable TypedefDecl *CFConstantStringTypeDecl = nullptr; 413 414 mutable QualType ObjCSuperType; 415 416 QualType ObjCNSStringType; 417 418 /// The typedef declaration for the Objective-C "instancetype" type. 419 TypedefDecl *ObjCInstanceTypeDecl = nullptr; 420 421 /// The type for the C FILE type. 422 TypeDecl *FILEDecl = nullptr; 423 424 /// The type for the C jmp_buf type. 425 TypeDecl *jmp_bufDecl = nullptr; 426 427 /// The type for the C sigjmp_buf type. 428 TypeDecl *sigjmp_bufDecl = nullptr; 429 430 /// The type for the C ucontext_t type. 431 TypeDecl *ucontext_tDecl = nullptr; 432 433 /// Type for the Block descriptor for Blocks CodeGen. 434 /// 435 /// Since this is only used for generation of debug info, it is not 436 /// serialized. 437 mutable RecordDecl *BlockDescriptorType = nullptr; 438 439 /// Type for the Block descriptor for Blocks CodeGen. 440 /// 441 /// Since this is only used for generation of debug info, it is not 442 /// serialized. 443 mutable RecordDecl *BlockDescriptorExtendedType = nullptr; 444 445 /// Declaration for the CUDA cudaConfigureCall function. 446 FunctionDecl *cudaConfigureCallDecl = nullptr; 447 448 /// Keeps track of all declaration attributes. 449 /// 450 /// Since so few decls have attrs, we keep them in a hash map instead of 451 /// wasting space in the Decl class. 452 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs; 453 454 /// A mapping from non-redeclarable declarations in modules that were 455 /// merged with other declarations to the canonical declaration that they were 456 /// merged into. 457 llvm::DenseMap<Decl*, Decl*> MergedDecls; 458 459 /// A mapping from a defining declaration to a list of modules (other 460 /// than the owning module of the declaration) that contain merged 461 /// definitions of that entity. 462 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules; 463 464 /// Initializers for a module, in order. Each Decl will be either 465 /// something that has a semantic effect on startup (such as a variable with 466 /// a non-constant initializer), or an ImportDecl (which recursively triggers 467 /// initialization of another module). 468 struct PerModuleInitializers { 469 llvm::SmallVector<Decl*, 4> Initializers; 470 llvm::SmallVector<uint32_t, 4> LazyInitializers; 471 472 void resolve(ASTContext &Ctx); 473 }; 474 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers; 475 476 static constexpr unsigned ConstantArrayTypesLog2InitSize = 8; 477 static constexpr unsigned GeneralTypesLog2InitSize = 9; 478 static constexpr unsigned FunctionProtoTypesLog2InitSize = 12; 479 480 ASTContext &this_() { return *this; } 481 482 public: 483 /// A type synonym for the TemplateOrInstantiation mapping. 484 using TemplateOrSpecializationInfo = 485 llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>; 486 487 private: 488 friend class ASTDeclReader; 489 friend class ASTReader; 490 friend class ASTWriter; 491 template <class> friend class serialization::AbstractTypeReader; 492 friend class CXXRecordDecl; 493 friend class IncrementalParser; 494 495 /// A mapping to contain the template or declaration that 496 /// a variable declaration describes or was instantiated from, 497 /// respectively. 498 /// 499 /// For non-templates, this value will be NULL. For variable 500 /// declarations that describe a variable template, this will be a 501 /// pointer to a VarTemplateDecl. For static data members 502 /// of class template specializations, this will be the 503 /// MemberSpecializationInfo referring to the member variable that was 504 /// instantiated or specialized. Thus, the mapping will keep track of 505 /// the static data member templates from which static data members of 506 /// class template specializations were instantiated. 507 /// 508 /// Given the following example: 509 /// 510 /// \code 511 /// template<typename T> 512 /// struct X { 513 /// static T value; 514 /// }; 515 /// 516 /// template<typename T> 517 /// T X<T>::value = T(17); 518 /// 519 /// int *x = &X<int>::value; 520 /// \endcode 521 /// 522 /// This mapping will contain an entry that maps from the VarDecl for 523 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the 524 /// class template X) and will be marked TSK_ImplicitInstantiation. 525 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo> 526 TemplateOrInstantiation; 527 528 /// Keeps track of the declaration from which a using declaration was 529 /// created during instantiation. 530 /// 531 /// The source and target declarations are always a UsingDecl, an 532 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl. 533 /// 534 /// For example: 535 /// \code 536 /// template<typename T> 537 /// struct A { 538 /// void f(); 539 /// }; 540 /// 541 /// template<typename T> 542 /// struct B : A<T> { 543 /// using A<T>::f; 544 /// }; 545 /// 546 /// template struct B<int>; 547 /// \endcode 548 /// 549 /// This mapping will contain an entry that maps from the UsingDecl in 550 /// B<int> to the UnresolvedUsingDecl in B<T>. 551 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl; 552 553 /// Like InstantiatedFromUsingDecl, but for using-enum-declarations. Maps 554 /// from the instantiated using-enum to the templated decl from whence it 555 /// came. 556 /// Note that using-enum-declarations cannot be dependent and 557 /// thus will never be instantiated from an "unresolved" 558 /// version thereof (as with using-declarations), so each mapping is from 559 /// a (resolved) UsingEnumDecl to a (resolved) UsingEnumDecl. 560 llvm::DenseMap<UsingEnumDecl *, UsingEnumDecl *> 561 InstantiatedFromUsingEnumDecl; 562 563 /// Simlarly maps instantiated UsingShadowDecls to their origin. 564 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*> 565 InstantiatedFromUsingShadowDecl; 566 567 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl; 568 569 /// Mapping that stores the methods overridden by a given C++ 570 /// member function. 571 /// 572 /// Since most C++ member functions aren't virtual and therefore 573 /// don't override anything, we store the overridden functions in 574 /// this map on the side rather than within the CXXMethodDecl structure. 575 using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>; 576 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods; 577 578 /// Mapping from each declaration context to its corresponding 579 /// mangling numbering context (used for constructs like lambdas which 580 /// need to be consistently numbered for the mangler). 581 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>> 582 MangleNumberingContexts; 583 llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>> 584 ExtraMangleNumberingContexts; 585 586 /// Side-table of mangling numbers for declarations which rarely 587 /// need them (like static local vars). 588 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers; 589 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers; 590 /// Mapping the associated device lambda mangling number if present. 591 mutable llvm::DenseMap<const CXXRecordDecl *, unsigned> 592 DeviceLambdaManglingNumbers; 593 594 /// Mapping that stores parameterIndex values for ParmVarDecls when 595 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex. 596 using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>; 597 ParameterIndexTable ParamIndices; 598 599 ImportDecl *FirstLocalImport = nullptr; 600 ImportDecl *LastLocalImport = nullptr; 601 602 TranslationUnitDecl *TUDecl = nullptr; 603 mutable ExternCContextDecl *ExternCContext = nullptr; 604 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr; 605 mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr; 606 607 /// The associated SourceManager object. 608 SourceManager &SourceMgr; 609 610 /// The language options used to create the AST associated with 611 /// this ASTContext object. 612 LangOptions &LangOpts; 613 614 /// NoSanitizeList object that is used by sanitizers to decide which 615 /// entities should not be instrumented. 616 std::unique_ptr<NoSanitizeList> NoSanitizeL; 617 618 /// Function filtering mechanism to determine whether a given function 619 /// should be imbued with the XRay "always" or "never" attributes. 620 std::unique_ptr<XRayFunctionFilter> XRayFilter; 621 622 /// ProfileList object that is used by the profile instrumentation 623 /// to decide which entities should be instrumented. 624 std::unique_ptr<ProfileList> ProfList; 625 626 /// The allocator used to create AST objects. 627 /// 628 /// AST objects are never destructed; rather, all memory associated with the 629 /// AST objects will be released when the ASTContext itself is destroyed. 630 mutable llvm::BumpPtrAllocator BumpAlloc; 631 632 /// Allocator for partial diagnostics. 633 PartialDiagnostic::DiagStorageAllocator DiagAllocator; 634 635 /// The current C++ ABI. 636 std::unique_ptr<CXXABI> ABI; 637 CXXABI *createCXXABI(const TargetInfo &T); 638 639 /// The logical -> physical address space map. 640 const LangASMap *AddrSpaceMap = nullptr; 641 642 /// Address space map mangling must be used with language specific 643 /// address spaces (e.g. OpenCL/CUDA) 644 bool AddrSpaceMapMangling; 645 646 const TargetInfo *Target = nullptr; 647 const TargetInfo *AuxTarget = nullptr; 648 clang::PrintingPolicy PrintingPolicy; 649 std::unique_ptr<interp::Context> InterpContext; 650 std::unique_ptr<ParentMapContext> ParentMapCtx; 651 652 /// Keeps track of the deallocated DeclListNodes for future reuse. 653 DeclListNode *ListNodeFreeList = nullptr; 654 655 public: 656 IdentifierTable &Idents; 657 SelectorTable &Selectors; 658 Builtin::Context &BuiltinInfo; 659 const TranslationUnitKind TUKind; 660 mutable DeclarationNameTable DeclarationNames; 661 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource; 662 ASTMutationListener *Listener = nullptr; 663 664 /// Returns the clang bytecode interpreter context. 665 interp::Context &getInterpContext(); 666 667 struct CUDAConstantEvalContext { 668 /// Do not allow wrong-sided variables in constant expressions. 669 bool NoWrongSidedVars = false; 670 } CUDAConstantEvalCtx; 671 struct CUDAConstantEvalContextRAII { 672 ASTContext &Ctx; 673 CUDAConstantEvalContext SavedCtx; 674 CUDAConstantEvalContextRAII(ASTContext &Ctx_, bool NoWrongSidedVars) 675 : Ctx(Ctx_), SavedCtx(Ctx_.CUDAConstantEvalCtx) { 676 Ctx_.CUDAConstantEvalCtx.NoWrongSidedVars = NoWrongSidedVars; 677 } 678 ~CUDAConstantEvalContextRAII() { Ctx.CUDAConstantEvalCtx = SavedCtx; } 679 }; 680 681 /// Returns the dynamic AST node parent map context. 682 ParentMapContext &getParentMapContext(); 683 684 // A traversal scope limits the parts of the AST visible to certain analyses. 685 // RecursiveASTVisitor only visits specified children of TranslationUnitDecl. 686 // getParents() will only observe reachable parent edges. 687 // 688 // The scope is defined by a set of "top-level" declarations which will be 689 // visible under the TranslationUnitDecl. 690 // Initially, it is the entire TU, represented by {getTranslationUnitDecl()}. 691 // 692 // After setTraversalScope({foo, bar}), the exposed AST looks like: 693 // TranslationUnitDecl 694 // - foo 695 // - ... 696 // - bar 697 // - ... 698 // All other siblings of foo and bar are pruned from the tree. 699 // (However they are still accessible via TranslationUnitDecl->decls()) 700 // 701 // Changing the scope clears the parent cache, which is expensive to rebuild. 702 std::vector<Decl *> getTraversalScope() const { return TraversalScope; } 703 void setTraversalScope(const std::vector<Decl *> &); 704 705 /// Forwards to get node parents from the ParentMapContext. New callers should 706 /// use ParentMapContext::getParents() directly. 707 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node); 708 709 const clang::PrintingPolicy &getPrintingPolicy() const { 710 return PrintingPolicy; 711 } 712 713 void setPrintingPolicy(const clang::PrintingPolicy &Policy) { 714 PrintingPolicy = Policy; 715 } 716 717 SourceManager& getSourceManager() { return SourceMgr; } 718 const SourceManager& getSourceManager() const { return SourceMgr; } 719 720 // Cleans up some of the data structures. This allows us to do cleanup 721 // normally done in the destructor earlier. Renders much of the ASTContext 722 // unusable, mostly the actual AST nodes, so should be called when we no 723 // longer need access to the AST. 724 void cleanup(); 725 726 llvm::BumpPtrAllocator &getAllocator() const { 727 return BumpAlloc; 728 } 729 730 void *Allocate(size_t Size, unsigned Align = 8) const { 731 return BumpAlloc.Allocate(Size, Align); 732 } 733 template <typename T> T *Allocate(size_t Num = 1) const { 734 return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T))); 735 } 736 void Deallocate(void *Ptr) const {} 737 738 /// Allocates a \c DeclListNode or returns one from the \c ListNodeFreeList 739 /// pool. 740 DeclListNode *AllocateDeclListNode(clang::NamedDecl *ND) { 741 if (DeclListNode *Alloc = ListNodeFreeList) { 742 ListNodeFreeList = Alloc->Rest.dyn_cast<DeclListNode*>(); 743 Alloc->D = ND; 744 Alloc->Rest = nullptr; 745 return Alloc; 746 } 747 return new (*this) DeclListNode(ND); 748 } 749 /// Deallcates a \c DeclListNode by returning it to the \c ListNodeFreeList 750 /// pool. 751 void DeallocateDeclListNode(DeclListNode *N) { 752 N->Rest = ListNodeFreeList; 753 ListNodeFreeList = N; 754 } 755 756 /// Return the total amount of physical memory allocated for representing 757 /// AST nodes and type information. 758 size_t getASTAllocatedMemory() const { 759 return BumpAlloc.getTotalMemory(); 760 } 761 762 /// Return the total memory used for various side tables. 763 size_t getSideTableAllocatedMemory() const; 764 765 PartialDiagnostic::DiagStorageAllocator &getDiagAllocator() { 766 return DiagAllocator; 767 } 768 769 const TargetInfo &getTargetInfo() const { return *Target; } 770 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; } 771 772 /// getIntTypeForBitwidth - 773 /// sets integer QualTy according to specified details: 774 /// bitwidth, signed/unsigned. 775 /// Returns empty type if there is no appropriate target types. 776 QualType getIntTypeForBitwidth(unsigned DestWidth, 777 unsigned Signed) const; 778 779 /// getRealTypeForBitwidth - 780 /// sets floating point QualTy according to specified bitwidth. 781 /// Returns empty type if there is no appropriate target types. 782 QualType getRealTypeForBitwidth(unsigned DestWidth, 783 FloatModeKind ExplicitType) const; 784 785 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const; 786 787 const LangOptions& getLangOpts() const { return LangOpts; } 788 789 // If this condition is false, typo correction must be performed eagerly 790 // rather than delayed in many places, as it makes use of dependent types. 791 // the condition is false for clang's C-only codepath, as it doesn't support 792 // dependent types yet. 793 bool isDependenceAllowed() const { 794 return LangOpts.CPlusPlus || LangOpts.RecoveryAST; 795 } 796 797 const NoSanitizeList &getNoSanitizeList() const { return *NoSanitizeL; } 798 799 const XRayFunctionFilter &getXRayFilter() const { 800 return *XRayFilter; 801 } 802 803 const ProfileList &getProfileList() const { return *ProfList; } 804 805 DiagnosticsEngine &getDiagnostics() const; 806 807 FullSourceLoc getFullLoc(SourceLocation Loc) const { 808 return FullSourceLoc(Loc,SourceMgr); 809 } 810 811 /// Return the C++ ABI kind that should be used. The C++ ABI can be overriden 812 /// at compile time with `-fc++-abi=`. If this is not provided, we instead use 813 /// the default ABI set by the target. 814 TargetCXXABI::Kind getCXXABIKind() const; 815 816 /// All comments in this translation unit. 817 RawCommentList Comments; 818 819 /// True if comments are already loaded from ExternalASTSource. 820 mutable bool CommentsLoaded = false; 821 822 /// Mapping from declaration to directly attached comment. 823 /// 824 /// Raw comments are owned by Comments list. This mapping is populated 825 /// lazily. 826 mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments; 827 828 /// Mapping from canonical declaration to the first redeclaration in chain 829 /// that has a comment attached. 830 /// 831 /// Raw comments are owned by Comments list. This mapping is populated 832 /// lazily. 833 mutable llvm::DenseMap<const Decl *, const Decl *> RedeclChainComments; 834 835 /// Keeps track of redeclaration chains that don't have any comment attached. 836 /// Mapping from canonical declaration to redeclaration chain that has no 837 /// comments attached to any redeclaration. Specifically it's mapping to 838 /// the last redeclaration we've checked. 839 /// 840 /// Shall not contain declarations that have comments attached to any 841 /// redeclaration in their chain. 842 mutable llvm::DenseMap<const Decl *, const Decl *> CommentlessRedeclChains; 843 844 /// Mapping from declarations to parsed comments attached to any 845 /// redeclaration. 846 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments; 847 848 /// Attaches \p Comment to \p OriginalD and to its redeclaration chain 849 /// and removes the redeclaration chain from the set of commentless chains. 850 /// 851 /// Don't do anything if a comment has already been attached to \p OriginalD 852 /// or its redeclaration chain. 853 void cacheRawCommentForDecl(const Decl &OriginalD, 854 const RawComment &Comment) const; 855 856 /// \returns searches \p CommentsInFile for doc comment for \p D. 857 /// 858 /// \p RepresentativeLocForDecl is used as a location for searching doc 859 /// comments. \p CommentsInFile is a mapping offset -> comment of files in the 860 /// same file where \p RepresentativeLocForDecl is. 861 RawComment *getRawCommentForDeclNoCacheImpl( 862 const Decl *D, const SourceLocation RepresentativeLocForDecl, 863 const std::map<unsigned, RawComment *> &CommentsInFile) const; 864 865 /// Return the documentation comment attached to a given declaration, 866 /// without looking into cache. 867 RawComment *getRawCommentForDeclNoCache(const Decl *D) const; 868 869 public: 870 void addComment(const RawComment &RC); 871 872 /// Return the documentation comment attached to a given declaration. 873 /// Returns nullptr if no comment is attached. 874 /// 875 /// \param OriginalDecl if not nullptr, is set to declaration AST node that 876 /// had the comment, if the comment we found comes from a redeclaration. 877 const RawComment * 878 getRawCommentForAnyRedecl(const Decl *D, 879 const Decl **OriginalDecl = nullptr) const; 880 881 /// Searches existing comments for doc comments that should be attached to \p 882 /// Decls. If any doc comment is found, it is parsed. 883 /// 884 /// Requirement: All \p Decls are in the same file. 885 /// 886 /// If the last comment in the file is already attached we assume 887 /// there are not comments left to be attached to \p Decls. 888 void attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, 889 const Preprocessor *PP); 890 891 /// Return parsed documentation comment attached to a given declaration. 892 /// Returns nullptr if no comment is attached. 893 /// 894 /// \param PP the Preprocessor used with this TU. Could be nullptr if 895 /// preprocessor is not available. 896 comments::FullComment *getCommentForDecl(const Decl *D, 897 const Preprocessor *PP) const; 898 899 /// Return parsed documentation comment attached to a given declaration. 900 /// Returns nullptr if no comment is attached. Does not look at any 901 /// redeclarations of the declaration. 902 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const; 903 904 comments::FullComment *cloneFullComment(comments::FullComment *FC, 905 const Decl *D) const; 906 907 private: 908 mutable comments::CommandTraits CommentCommandTraits; 909 910 /// Iterator that visits import declarations. 911 class import_iterator { 912 ImportDecl *Import = nullptr; 913 914 public: 915 using value_type = ImportDecl *; 916 using reference = ImportDecl *; 917 using pointer = ImportDecl *; 918 using difference_type = int; 919 using iterator_category = std::forward_iterator_tag; 920 921 import_iterator() = default; 922 explicit import_iterator(ImportDecl *Import) : Import(Import) {} 923 924 reference operator*() const { return Import; } 925 pointer operator->() const { return Import; } 926 927 import_iterator &operator++() { 928 Import = ASTContext::getNextLocalImport(Import); 929 return *this; 930 } 931 932 import_iterator operator++(int) { 933 import_iterator Other(*this); 934 ++(*this); 935 return Other; 936 } 937 938 friend bool operator==(import_iterator X, import_iterator Y) { 939 return X.Import == Y.Import; 940 } 941 942 friend bool operator!=(import_iterator X, import_iterator Y) { 943 return X.Import != Y.Import; 944 } 945 }; 946 947 public: 948 comments::CommandTraits &getCommentCommandTraits() const { 949 return CommentCommandTraits; 950 } 951 952 /// Retrieve the attributes for the given declaration. 953 AttrVec& getDeclAttrs(const Decl *D); 954 955 /// Erase the attributes corresponding to the given declaration. 956 void eraseDeclAttrs(const Decl *D); 957 958 /// If this variable is an instantiated static data member of a 959 /// class template specialization, returns the templated static data member 960 /// from which it was instantiated. 961 // FIXME: Remove ? 962 MemberSpecializationInfo *getInstantiatedFromStaticDataMember( 963 const VarDecl *Var); 964 965 /// Note that the static data member \p Inst is an instantiation of 966 /// the static data member template \p Tmpl of a class template. 967 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 968 TemplateSpecializationKind TSK, 969 SourceLocation PointOfInstantiation = SourceLocation()); 970 971 TemplateOrSpecializationInfo 972 getTemplateOrSpecializationInfo(const VarDecl *Var); 973 974 void setTemplateOrSpecializationInfo(VarDecl *Inst, 975 TemplateOrSpecializationInfo TSI); 976 977 /// If the given using decl \p Inst is an instantiation of 978 /// another (possibly unresolved) using decl, return it. 979 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst); 980 981 /// Remember that the using decl \p Inst is an instantiation 982 /// of the using decl \p Pattern of a class template. 983 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern); 984 985 /// If the given using-enum decl \p Inst is an instantiation of 986 /// another using-enum decl, return it. 987 UsingEnumDecl *getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst); 988 989 /// Remember that the using enum decl \p Inst is an instantiation 990 /// of the using enum decl \p Pattern of a class template. 991 void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, 992 UsingEnumDecl *Pattern); 993 994 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst); 995 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 996 UsingShadowDecl *Pattern); 997 998 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field); 999 1000 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl); 1001 1002 // Access to the set of methods overridden by the given C++ method. 1003 using overridden_cxx_method_iterator = CXXMethodVector::const_iterator; 1004 overridden_cxx_method_iterator 1005 overridden_methods_begin(const CXXMethodDecl *Method) const; 1006 1007 overridden_cxx_method_iterator 1008 overridden_methods_end(const CXXMethodDecl *Method) const; 1009 1010 unsigned overridden_methods_size(const CXXMethodDecl *Method) const; 1011 1012 using overridden_method_range = 1013 llvm::iterator_range<overridden_cxx_method_iterator>; 1014 1015 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const; 1016 1017 /// Note that the given C++ \p Method overrides the given \p 1018 /// Overridden method. 1019 void addOverriddenMethod(const CXXMethodDecl *Method, 1020 const CXXMethodDecl *Overridden); 1021 1022 /// Return C++ or ObjC overridden methods for the given \p Method. 1023 /// 1024 /// An ObjC method is considered to override any method in the class's 1025 /// base classes, its protocols, or its categories' protocols, that has 1026 /// the same selector and is of the same kind (class or instance). 1027 /// A method in an implementation is not considered as overriding the same 1028 /// method in the interface or its categories. 1029 void getOverriddenMethods( 1030 const NamedDecl *Method, 1031 SmallVectorImpl<const NamedDecl *> &Overridden) const; 1032 1033 /// Notify the AST context that a new import declaration has been 1034 /// parsed or implicitly created within this translation unit. 1035 void addedLocalImportDecl(ImportDecl *Import); 1036 1037 static ImportDecl *getNextLocalImport(ImportDecl *Import) { 1038 return Import->getNextLocalImport(); 1039 } 1040 1041 using import_range = llvm::iterator_range<import_iterator>; 1042 1043 import_range local_imports() const { 1044 return import_range(import_iterator(FirstLocalImport), import_iterator()); 1045 } 1046 1047 Decl *getPrimaryMergedDecl(Decl *D) { 1048 Decl *Result = MergedDecls.lookup(D); 1049 return Result ? Result : D; 1050 } 1051 void setPrimaryMergedDecl(Decl *D, Decl *Primary) { 1052 MergedDecls[D] = Primary; 1053 } 1054 1055 /// Note that the definition \p ND has been merged into module \p M, 1056 /// and should be visible whenever \p M is visible. 1057 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1058 bool NotifyListeners = true); 1059 1060 /// Clean up the merged definition list. Call this if you might have 1061 /// added duplicates into the list. 1062 void deduplicateMergedDefinitonsFor(NamedDecl *ND); 1063 1064 /// Get the additional modules in which the definition \p Def has 1065 /// been merged. 1066 ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def); 1067 1068 /// Add a declaration to the list of declarations that are initialized 1069 /// for a module. This will typically be a global variable (with internal 1070 /// linkage) that runs module initializers, such as the iostream initializer, 1071 /// or an ImportDecl nominating another module that has initializers. 1072 void addModuleInitializer(Module *M, Decl *Init); 1073 1074 void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs); 1075 1076 /// Get the initializations to perform when importing a module, if any. 1077 ArrayRef<Decl*> getModuleInitializers(Module *M); 1078 1079 TranslationUnitDecl *getTranslationUnitDecl() const { 1080 return TUDecl->getMostRecentDecl(); 1081 } 1082 void addTranslationUnitDecl() { 1083 assert(!TUDecl || TUKind == TU_Incremental); 1084 TranslationUnitDecl *NewTUDecl = TranslationUnitDecl::Create(*this); 1085 if (TraversalScope.empty() || TraversalScope.back() == TUDecl) 1086 TraversalScope = {NewTUDecl}; 1087 if (TUDecl) 1088 NewTUDecl->setPreviousDecl(TUDecl); 1089 TUDecl = NewTUDecl; 1090 } 1091 1092 ExternCContextDecl *getExternCContextDecl() const; 1093 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const; 1094 BuiltinTemplateDecl *getTypePackElementDecl() const; 1095 1096 // Builtin Types. 1097 CanQualType VoidTy; 1098 CanQualType BoolTy; 1099 CanQualType CharTy; 1100 CanQualType WCharTy; // [C++ 3.9.1p5]. 1101 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99. 1102 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions. 1103 CanQualType Char8Ty; // [C++20 proposal] 1104 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99. 1105 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99. 1106 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty; 1107 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy; 1108 CanQualType UnsignedLongLongTy, UnsignedInt128Ty; 1109 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty, Ibm128Ty; 1110 CanQualType ShortAccumTy, AccumTy, 1111 LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1112 CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy; 1113 CanQualType ShortFractTy, FractTy, LongFractTy; 1114 CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy; 1115 CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy; 1116 CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy, 1117 SatUnsignedLongAccumTy; 1118 CanQualType SatShortFractTy, SatFractTy, SatLongFractTy; 1119 CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy, 1120 SatUnsignedLongFractTy; 1121 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON 1122 CanQualType BFloat16Ty; 1123 CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3 1124 CanQualType VoidPtrTy, NullPtrTy; 1125 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy; 1126 CanQualType BuiltinFnTy; 1127 CanQualType PseudoObjectTy, ARCUnbridgedCastTy; 1128 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy; 1129 CanQualType ObjCBuiltinBoolTy; 1130 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1131 CanQualType SingletonId; 1132 #include "clang/Basic/OpenCLImageTypes.def" 1133 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy; 1134 CanQualType OCLQueueTy, OCLReserveIDTy; 1135 CanQualType IncompleteMatrixIdxTy; 1136 CanQualType OMPArraySectionTy, OMPArrayShapingTy, OMPIteratorTy; 1137 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1138 CanQualType Id##Ty; 1139 #include "clang/Basic/OpenCLExtensionTypes.def" 1140 #define SVE_TYPE(Name, Id, SingletonId) \ 1141 CanQualType SingletonId; 1142 #include "clang/Basic/AArch64SVEACLETypes.def" 1143 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 1144 CanQualType Id##Ty; 1145 #include "clang/Basic/PPCTypes.def" 1146 #define RVV_TYPE(Name, Id, SingletonId) \ 1147 CanQualType SingletonId; 1148 #include "clang/Basic/RISCVVTypes.def" 1149 1150 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand. 1151 mutable QualType AutoDeductTy; // Deduction against 'auto'. 1152 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'. 1153 1154 // Decl used to help define __builtin_va_list for some targets. 1155 // The decl is built when constructing 'BuiltinVaListDecl'. 1156 mutable Decl *VaListTagDecl = nullptr; 1157 1158 // Implicitly-declared type 'struct _GUID'. 1159 mutable TagDecl *MSGuidTagDecl = nullptr; 1160 1161 /// Keep track of CUDA/HIP device-side variables ODR-used by host code. 1162 llvm::DenseSet<const VarDecl *> CUDADeviceVarODRUsedByHost; 1163 1164 /// Keep track of CUDA/HIP external kernels or device variables ODR-used by 1165 /// host code. 1166 llvm::DenseSet<const ValueDecl *> CUDAExternalDeviceDeclODRUsedByHost; 1167 1168 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, 1169 SelectorTable &sels, Builtin::Context &builtins, 1170 TranslationUnitKind TUKind); 1171 ASTContext(const ASTContext &) = delete; 1172 ASTContext &operator=(const ASTContext &) = delete; 1173 ~ASTContext(); 1174 1175 /// Attach an external AST source to the AST context. 1176 /// 1177 /// The external AST source provides the ability to load parts of 1178 /// the abstract syntax tree as needed from some external storage, 1179 /// e.g., a precompiled header. 1180 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source); 1181 1182 /// Retrieve a pointer to the external AST source associated 1183 /// with this AST context, if any. 1184 ExternalASTSource *getExternalSource() const { 1185 return ExternalSource.get(); 1186 } 1187 1188 /// Attach an AST mutation listener to the AST context. 1189 /// 1190 /// The AST mutation listener provides the ability to track modifications to 1191 /// the abstract syntax tree entities committed after they were initially 1192 /// created. 1193 void setASTMutationListener(ASTMutationListener *Listener) { 1194 this->Listener = Listener; 1195 } 1196 1197 /// Retrieve a pointer to the AST mutation listener associated 1198 /// with this AST context, if any. 1199 ASTMutationListener *getASTMutationListener() const { return Listener; } 1200 1201 void PrintStats() const; 1202 const SmallVectorImpl<Type *>& getTypes() const { return Types; } 1203 1204 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1205 const IdentifierInfo *II) const; 1206 1207 /// Create a new implicit TU-level CXXRecordDecl or RecordDecl 1208 /// declaration. 1209 RecordDecl *buildImplicitRecord(StringRef Name, 1210 RecordDecl::TagKind TK = TTK_Struct) const; 1211 1212 /// Create a new implicit TU-level typedef declaration. 1213 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const; 1214 1215 /// Retrieve the declaration for the 128-bit signed integer type. 1216 TypedefDecl *getInt128Decl() const; 1217 1218 /// Retrieve the declaration for the 128-bit unsigned integer type. 1219 TypedefDecl *getUInt128Decl() const; 1220 1221 //===--------------------------------------------------------------------===// 1222 // Type Constructors 1223 //===--------------------------------------------------------------------===// 1224 1225 private: 1226 /// Return a type with extended qualifiers. 1227 QualType getExtQualType(const Type *Base, Qualifiers Quals) const; 1228 1229 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const; 1230 1231 QualType getPipeType(QualType T, bool ReadOnly) const; 1232 1233 public: 1234 /// Return the uniqued reference to the type for an address space 1235 /// qualified type with the specified type and address space. 1236 /// 1237 /// The resulting type has a union of the qualifiers from T and the address 1238 /// space. If T already has an address space specifier, it is silently 1239 /// replaced. 1240 QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const; 1241 1242 /// Remove any existing address space on the type and returns the type 1243 /// with qualifiers intact (or that's the idea anyway) 1244 /// 1245 /// The return type should be T with all prior qualifiers minus the address 1246 /// space. 1247 QualType removeAddrSpaceQualType(QualType T) const; 1248 1249 /// Apply Objective-C protocol qualifiers to the given type. 1250 /// \param allowOnPointerType specifies if we can apply protocol 1251 /// qualifiers on ObjCObjectPointerType. It can be set to true when 1252 /// constructing the canonical type of a Objective-C type parameter. 1253 QualType applyObjCProtocolQualifiers(QualType type, 1254 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 1255 bool allowOnPointerType = false) const; 1256 1257 /// Return the uniqued reference to the type for an Objective-C 1258 /// gc-qualified type. 1259 /// 1260 /// The resulting type has a union of the qualifiers from T and the gc 1261 /// attribute. 1262 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const; 1263 1264 /// Remove the existing address space on the type if it is a pointer size 1265 /// address space and return the type with qualifiers intact. 1266 QualType removePtrSizeAddrSpace(QualType T) const; 1267 1268 /// Return the uniqued reference to the type for a \c restrict 1269 /// qualified type. 1270 /// 1271 /// The resulting type has a union of the qualifiers from \p T and 1272 /// \c restrict. 1273 QualType getRestrictType(QualType T) const { 1274 return T.withFastQualifiers(Qualifiers::Restrict); 1275 } 1276 1277 /// Return the uniqued reference to the type for a \c volatile 1278 /// qualified type. 1279 /// 1280 /// The resulting type has a union of the qualifiers from \p T and 1281 /// \c volatile. 1282 QualType getVolatileType(QualType T) const { 1283 return T.withFastQualifiers(Qualifiers::Volatile); 1284 } 1285 1286 /// Return the uniqued reference to the type for a \c const 1287 /// qualified type. 1288 /// 1289 /// The resulting type has a union of the qualifiers from \p T and \c const. 1290 /// 1291 /// It can be reasonably expected that this will always be equivalent to 1292 /// calling T.withConst(). 1293 QualType getConstType(QualType T) const { return T.withConst(); } 1294 1295 /// Change the ExtInfo on a function type. 1296 const FunctionType *adjustFunctionType(const FunctionType *Fn, 1297 FunctionType::ExtInfo EInfo); 1298 1299 /// Adjust the given function result type. 1300 CanQualType getCanonicalFunctionResultType(QualType ResultType) const; 1301 1302 /// Change the result type of a function type once it is deduced. 1303 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType); 1304 1305 /// Get a function type and produce the equivalent function type with the 1306 /// specified exception specification. Type sugar that can be present on a 1307 /// declaration of a function with an exception specification is permitted 1308 /// and preserved. Other type sugar (for instance, typedefs) is not. 1309 QualType getFunctionTypeWithExceptionSpec( 1310 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const; 1311 1312 /// Determine whether two function types are the same, ignoring 1313 /// exception specifications in cases where they're part of the type. 1314 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const; 1315 1316 /// Change the exception specification on a function once it is 1317 /// delay-parsed, instantiated, or computed. 1318 void adjustExceptionSpec(FunctionDecl *FD, 1319 const FunctionProtoType::ExceptionSpecInfo &ESI, 1320 bool AsWritten = false); 1321 1322 /// Get a function type and produce the equivalent function type where 1323 /// pointer size address spaces in the return type and parameter tyeps are 1324 /// replaced with the default address space. 1325 QualType getFunctionTypeWithoutPtrSizes(QualType T); 1326 1327 /// Determine whether two function types are the same, ignoring pointer sizes 1328 /// in the return type and parameter types. 1329 bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U); 1330 1331 /// Return the uniqued reference to the type for a complex 1332 /// number with the specified element type. 1333 QualType getComplexType(QualType T) const; 1334 CanQualType getComplexType(CanQualType T) const { 1335 return CanQualType::CreateUnsafe(getComplexType((QualType) T)); 1336 } 1337 1338 /// Return the uniqued reference to the type for a pointer to 1339 /// the specified type. 1340 QualType getPointerType(QualType T) const; 1341 CanQualType getPointerType(CanQualType T) const { 1342 return CanQualType::CreateUnsafe(getPointerType((QualType) T)); 1343 } 1344 1345 /// Return the uniqued reference to a type adjusted from the original 1346 /// type to a new type. 1347 QualType getAdjustedType(QualType Orig, QualType New) const; 1348 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const { 1349 return CanQualType::CreateUnsafe( 1350 getAdjustedType((QualType)Orig, (QualType)New)); 1351 } 1352 1353 /// Return the uniqued reference to the decayed version of the given 1354 /// type. Can only be called on array and function types which decay to 1355 /// pointer types. 1356 QualType getDecayedType(QualType T) const; 1357 CanQualType getDecayedType(CanQualType T) const { 1358 return CanQualType::CreateUnsafe(getDecayedType((QualType) T)); 1359 } 1360 1361 /// Return the uniqued reference to the atomic type for the specified 1362 /// type. 1363 QualType getAtomicType(QualType T) const; 1364 1365 /// Return the uniqued reference to the type for a block of the 1366 /// specified type. 1367 QualType getBlockPointerType(QualType T) const; 1368 1369 /// Gets the struct used to keep track of the descriptor for pointer to 1370 /// blocks. 1371 QualType getBlockDescriptorType() const; 1372 1373 /// Return a read_only pipe type for the specified type. 1374 QualType getReadPipeType(QualType T) const; 1375 1376 /// Return a write_only pipe type for the specified type. 1377 QualType getWritePipeType(QualType T) const; 1378 1379 /// Return a bit-precise integer type with the specified signedness and bit 1380 /// count. 1381 QualType getBitIntType(bool Unsigned, unsigned NumBits) const; 1382 1383 /// Return a dependent bit-precise integer type with the specified signedness 1384 /// and bit count. 1385 QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const; 1386 1387 /// Gets the struct used to keep track of the extended descriptor for 1388 /// pointer to blocks. 1389 QualType getBlockDescriptorExtendedType() const; 1390 1391 /// Map an AST Type to an OpenCLTypeKind enum value. 1392 OpenCLTypeKind getOpenCLTypeKind(const Type *T) const; 1393 1394 /// Get address space for OpenCL type. 1395 LangAS getOpenCLTypeAddrSpace(const Type *T) const; 1396 1397 /// Returns default address space based on OpenCL version and enabled features 1398 inline LangAS getDefaultOpenCLPointeeAddrSpace() { 1399 return LangOpts.OpenCLGenericAddressSpace ? LangAS::opencl_generic 1400 : LangAS::opencl_private; 1401 } 1402 1403 void setcudaConfigureCallDecl(FunctionDecl *FD) { 1404 cudaConfigureCallDecl = FD; 1405 } 1406 1407 FunctionDecl *getcudaConfigureCallDecl() { 1408 return cudaConfigureCallDecl; 1409 } 1410 1411 /// Returns true iff we need copy/dispose helpers for the given type. 1412 bool BlockRequiresCopying(QualType Ty, const VarDecl *D); 1413 1414 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout 1415 /// is set to false in this case. If HasByrefExtendedLayout returns true, 1416 /// byref variable has extended lifetime. 1417 bool getByrefLifetime(QualType Ty, 1418 Qualifiers::ObjCLifetime &Lifetime, 1419 bool &HasByrefExtendedLayout) const; 1420 1421 /// Return the uniqued reference to the type for an lvalue reference 1422 /// to the specified type. 1423 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true) 1424 const; 1425 1426 /// Return the uniqued reference to the type for an rvalue reference 1427 /// to the specified type. 1428 QualType getRValueReferenceType(QualType T) const; 1429 1430 /// Return the uniqued reference to the type for a member pointer to 1431 /// the specified type in the specified class. 1432 /// 1433 /// The class \p Cls is a \c Type because it could be a dependent name. 1434 QualType getMemberPointerType(QualType T, const Type *Cls) const; 1435 1436 /// Return a non-unique reference to the type for a variable array of 1437 /// the specified element type. 1438 QualType getVariableArrayType(QualType EltTy, Expr *NumElts, 1439 ArrayType::ArraySizeModifier ASM, 1440 unsigned IndexTypeQuals, 1441 SourceRange Brackets) const; 1442 1443 /// Return a non-unique reference to the type for a dependently-sized 1444 /// array of the specified element type. 1445 /// 1446 /// FIXME: We will need these to be uniqued, or at least comparable, at some 1447 /// point. 1448 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, 1449 ArrayType::ArraySizeModifier ASM, 1450 unsigned IndexTypeQuals, 1451 SourceRange Brackets) const; 1452 1453 /// Return a unique reference to the type for an incomplete array of 1454 /// the specified element type. 1455 QualType getIncompleteArrayType(QualType EltTy, 1456 ArrayType::ArraySizeModifier ASM, 1457 unsigned IndexTypeQuals) const; 1458 1459 /// Return the unique reference to the type for a constant array of 1460 /// the specified element type. 1461 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, 1462 const Expr *SizeExpr, 1463 ArrayType::ArraySizeModifier ASM, 1464 unsigned IndexTypeQuals) const; 1465 1466 /// Return a type for a constant array for a string literal of the 1467 /// specified element type and length. 1468 QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const; 1469 1470 /// Returns a vla type where known sizes are replaced with [*]. 1471 QualType getVariableArrayDecayedType(QualType Ty) const; 1472 1473 // Convenience struct to return information about a builtin vector type. 1474 struct BuiltinVectorTypeInfo { 1475 QualType ElementType; 1476 llvm::ElementCount EC; 1477 unsigned NumVectors; 1478 BuiltinVectorTypeInfo(QualType ElementType, llvm::ElementCount EC, 1479 unsigned NumVectors) 1480 : ElementType(ElementType), EC(EC), NumVectors(NumVectors) {} 1481 }; 1482 1483 /// Returns the element type, element count and number of vectors 1484 /// (in case of tuple) for a builtin vector type. 1485 BuiltinVectorTypeInfo 1486 getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const; 1487 1488 /// Return the unique reference to a scalable vector type of the specified 1489 /// element type and scalable number of elements. 1490 /// 1491 /// \pre \p EltTy must be a built-in type. 1492 QualType getScalableVectorType(QualType EltTy, unsigned NumElts) const; 1493 1494 /// Return the unique reference to a vector type of the specified 1495 /// element type and size. 1496 /// 1497 /// \pre \p VectorType must be a built-in type. 1498 QualType getVectorType(QualType VectorType, unsigned NumElts, 1499 VectorType::VectorKind VecKind) const; 1500 /// Return the unique reference to the type for a dependently sized vector of 1501 /// the specified element type. 1502 QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, 1503 SourceLocation AttrLoc, 1504 VectorType::VectorKind VecKind) const; 1505 1506 /// Return the unique reference to an extended vector type 1507 /// of the specified element type and size. 1508 /// 1509 /// \pre \p VectorType must be a built-in type. 1510 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const; 1511 1512 /// \pre Return a non-unique reference to the type for a dependently-sized 1513 /// vector of the specified element type. 1514 /// 1515 /// FIXME: We will need these to be uniqued, or at least comparable, at some 1516 /// point. 1517 QualType getDependentSizedExtVectorType(QualType VectorType, 1518 Expr *SizeExpr, 1519 SourceLocation AttrLoc) const; 1520 1521 /// Return the unique reference to the matrix type of the specified element 1522 /// type and size 1523 /// 1524 /// \pre \p ElementType must be a valid matrix element type (see 1525 /// MatrixType::isValidElementType). 1526 QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, 1527 unsigned NumColumns) const; 1528 1529 /// Return the unique reference to the matrix type of the specified element 1530 /// type and size 1531 QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, 1532 Expr *ColumnExpr, 1533 SourceLocation AttrLoc) const; 1534 1535 QualType getDependentAddressSpaceType(QualType PointeeType, 1536 Expr *AddrSpaceExpr, 1537 SourceLocation AttrLoc) const; 1538 1539 /// Return a K&R style C function type like 'int()'. 1540 QualType getFunctionNoProtoType(QualType ResultTy, 1541 const FunctionType::ExtInfo &Info) const; 1542 1543 QualType getFunctionNoProtoType(QualType ResultTy) const { 1544 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo()); 1545 } 1546 1547 /// Return a normal function type with a typed argument list. 1548 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args, 1549 const FunctionProtoType::ExtProtoInfo &EPI) const { 1550 return getFunctionTypeInternal(ResultTy, Args, EPI, false); 1551 } 1552 1553 QualType adjustStringLiteralBaseType(QualType StrLTy) const; 1554 1555 private: 1556 /// Return a normal function type with a typed argument list. 1557 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args, 1558 const FunctionProtoType::ExtProtoInfo &EPI, 1559 bool OnlyWantCanonical) const; 1560 QualType 1561 getAutoTypeInternal(QualType DeducedType, AutoTypeKeyword Keyword, 1562 bool IsDependent, bool IsPack = false, 1563 ConceptDecl *TypeConstraintConcept = nullptr, 1564 ArrayRef<TemplateArgument> TypeConstraintArgs = {}, 1565 bool IsCanon = false) const; 1566 1567 public: 1568 /// Return the unique reference to the type for the specified type 1569 /// declaration. 1570 QualType getTypeDeclType(const TypeDecl *Decl, 1571 const TypeDecl *PrevDecl = nullptr) const { 1572 assert(Decl && "Passed null for Decl param"); 1573 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1574 1575 if (PrevDecl) { 1576 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 1577 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1578 return QualType(PrevDecl->TypeForDecl, 0); 1579 } 1580 1581 return getTypeDeclTypeSlow(Decl); 1582 } 1583 1584 QualType getUsingType(const UsingShadowDecl *Found, 1585 QualType Underlying) const; 1586 1587 /// Return the unique reference to the type for the specified 1588 /// typedef-name decl. 1589 QualType getTypedefType(const TypedefNameDecl *Decl, 1590 QualType Underlying = QualType()) const; 1591 1592 QualType getRecordType(const RecordDecl *Decl) const; 1593 1594 QualType getEnumType(const EnumDecl *Decl) const; 1595 1596 QualType 1597 getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) const; 1598 1599 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const; 1600 1601 QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, 1602 QualType equivalentType) const; 1603 1604 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, 1605 QualType Wrapped); 1606 1607 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced, 1608 QualType Replacement) const; 1609 QualType getSubstTemplateTypeParmPackType( 1610 const TemplateTypeParmType *Replaced, 1611 const TemplateArgument &ArgPack); 1612 1613 QualType 1614 getTemplateTypeParmType(unsigned Depth, unsigned Index, 1615 bool ParameterPack, 1616 TemplateTypeParmDecl *ParmDecl = nullptr) const; 1617 1618 QualType getTemplateSpecializationType(TemplateName T, 1619 ArrayRef<TemplateArgument> Args, 1620 QualType Canon = QualType()) const; 1621 1622 QualType 1623 getCanonicalTemplateSpecializationType(TemplateName T, 1624 ArrayRef<TemplateArgument> Args) const; 1625 1626 QualType getTemplateSpecializationType(TemplateName T, 1627 const TemplateArgumentListInfo &Args, 1628 QualType Canon = QualType()) const; 1629 1630 TypeSourceInfo * 1631 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, 1632 const TemplateArgumentListInfo &Args, 1633 QualType Canon = QualType()) const; 1634 1635 QualType getParenType(QualType NamedType) const; 1636 1637 QualType getMacroQualifiedType(QualType UnderlyingTy, 1638 const IdentifierInfo *MacroII) const; 1639 1640 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 1641 NestedNameSpecifier *NNS, QualType NamedType, 1642 TagDecl *OwnedTagDecl = nullptr) const; 1643 QualType getDependentNameType(ElaboratedTypeKeyword Keyword, 1644 NestedNameSpecifier *NNS, 1645 const IdentifierInfo *Name, 1646 QualType Canon = QualType()) const; 1647 1648 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, 1649 NestedNameSpecifier *NNS, 1650 const IdentifierInfo *Name, 1651 const TemplateArgumentListInfo &Args) const; 1652 QualType getDependentTemplateSpecializationType( 1653 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, 1654 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const; 1655 1656 TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl); 1657 1658 /// Get a template argument list with one argument per template parameter 1659 /// in a template parameter list, such as for the injected class name of 1660 /// a class template. 1661 void getInjectedTemplateArgs(const TemplateParameterList *Params, 1662 SmallVectorImpl<TemplateArgument> &Args); 1663 1664 /// Form a pack expansion type with the given pattern. 1665 /// \param NumExpansions The number of expansions for the pack, if known. 1666 /// \param ExpectPackInType If \c false, we should not expect \p Pattern to 1667 /// contain an unexpanded pack. This only makes sense if the pack 1668 /// expansion is used in a context where the arity is inferred from 1669 /// elsewhere, such as if the pattern contains a placeholder type or 1670 /// if this is the canonical type of another pack expansion type. 1671 QualType getPackExpansionType(QualType Pattern, 1672 Optional<unsigned> NumExpansions, 1673 bool ExpectPackInType = true); 1674 1675 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 1676 ObjCInterfaceDecl *PrevDecl = nullptr) const; 1677 1678 /// Legacy interface: cannot provide type arguments or __kindof. 1679 QualType getObjCObjectType(QualType Base, 1680 ObjCProtocolDecl * const *Protocols, 1681 unsigned NumProtocols) const; 1682 1683 QualType getObjCObjectType(QualType Base, 1684 ArrayRef<QualType> typeArgs, 1685 ArrayRef<ObjCProtocolDecl *> protocols, 1686 bool isKindOf) const; 1687 1688 QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, 1689 ArrayRef<ObjCProtocolDecl *> protocols) const; 1690 void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, 1691 ObjCTypeParamDecl *New) const; 1692 1693 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl); 1694 1695 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 1696 /// QT's qualified-id protocol list adopt all protocols in IDecl's list 1697 /// of protocols. 1698 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 1699 ObjCInterfaceDecl *IDecl); 1700 1701 /// Return a ObjCObjectPointerType type for the given ObjCObjectType. 1702 QualType getObjCObjectPointerType(QualType OIT) const; 1703 1704 /// GCC extension. 1705 QualType getTypeOfExprType(Expr *e) const; 1706 QualType getTypeOfType(QualType t) const; 1707 1708 QualType getReferenceQualifiedType(const Expr *e) const; 1709 1710 /// C++11 decltype. 1711 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const; 1712 1713 /// Unary type transforms 1714 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, 1715 UnaryTransformType::UTTKind UKind) const; 1716 1717 /// C++11 deduced auto type. 1718 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, 1719 bool IsDependent, bool IsPack = false, 1720 ConceptDecl *TypeConstraintConcept = nullptr, 1721 ArrayRef<TemplateArgument> TypeConstraintArgs ={}) const; 1722 1723 /// C++11 deduction pattern for 'auto' type. 1724 QualType getAutoDeductType() const; 1725 1726 /// C++11 deduction pattern for 'auto &&' type. 1727 QualType getAutoRRefDeductType() const; 1728 1729 /// C++17 deduced class template specialization type. 1730 QualType getDeducedTemplateSpecializationType(TemplateName Template, 1731 QualType DeducedType, 1732 bool IsDependent) const; 1733 1734 /// Return the unique reference to the type for the specified TagDecl 1735 /// (struct/union/class/enum) decl. 1736 QualType getTagDeclType(const TagDecl *Decl) const; 1737 1738 /// Return the unique type for "size_t" (C99 7.17), defined in 1739 /// <stddef.h>. 1740 /// 1741 /// The sizeof operator requires this (C99 6.5.3.4p4). 1742 CanQualType getSizeType() const; 1743 1744 /// Return the unique signed counterpart of 1745 /// the integer type corresponding to size_t. 1746 CanQualType getSignedSizeType() const; 1747 1748 /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in 1749 /// <stdint.h>. 1750 CanQualType getIntMaxType() const; 1751 1752 /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in 1753 /// <stdint.h>. 1754 CanQualType getUIntMaxType() const; 1755 1756 /// Return the unique wchar_t type available in C++ (and available as 1757 /// __wchar_t as a Microsoft extension). 1758 QualType getWCharType() const { return WCharTy; } 1759 1760 /// Return the type of wide characters. In C++, this returns the 1761 /// unique wchar_t type. In C99, this returns a type compatible with the type 1762 /// defined in <stddef.h> as defined by the target. 1763 QualType getWideCharType() const { return WideCharTy; } 1764 1765 /// Return the type of "signed wchar_t". 1766 /// 1767 /// Used when in C++, as a GCC extension. 1768 QualType getSignedWCharType() const; 1769 1770 /// Return the type of "unsigned wchar_t". 1771 /// 1772 /// Used when in C++, as a GCC extension. 1773 QualType getUnsignedWCharType() const; 1774 1775 /// In C99, this returns a type compatible with the type 1776 /// defined in <stddef.h> as defined by the target. 1777 QualType getWIntType() const { return WIntTy; } 1778 1779 /// Return a type compatible with "intptr_t" (C99 7.18.1.4), 1780 /// as defined by the target. 1781 QualType getIntPtrType() const; 1782 1783 /// Return a type compatible with "uintptr_t" (C99 7.18.1.4), 1784 /// as defined by the target. 1785 QualType getUIntPtrType() const; 1786 1787 /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in 1788 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 1789 QualType getPointerDiffType() const; 1790 1791 /// Return the unique unsigned counterpart of "ptrdiff_t" 1792 /// integer type. The standard (C11 7.21.6.1p7) refers to this type 1793 /// in the definition of %tu format specifier. 1794 QualType getUnsignedPointerDiffType() const; 1795 1796 /// Return the unique type for "pid_t" defined in 1797 /// <sys/types.h>. We need this to compute the correct type for vfork(). 1798 QualType getProcessIDType() const; 1799 1800 /// Return the C structure type used to represent constant CFStrings. 1801 QualType getCFConstantStringType() const; 1802 1803 /// Returns the C struct type for objc_super 1804 QualType getObjCSuperType() const; 1805 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; } 1806 1807 /// Get the structure type used to representation CFStrings, or NULL 1808 /// if it hasn't yet been built. 1809 QualType getRawCFConstantStringType() const { 1810 if (CFConstantStringTypeDecl) 1811 return getTypedefType(CFConstantStringTypeDecl); 1812 return QualType(); 1813 } 1814 void setCFConstantStringType(QualType T); 1815 TypedefDecl *getCFConstantStringDecl() const; 1816 RecordDecl *getCFConstantStringTagDecl() const; 1817 1818 // This setter/getter represents the ObjC type for an NSConstantString. 1819 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl); 1820 QualType getObjCConstantStringInterface() const { 1821 return ObjCConstantStringType; 1822 } 1823 1824 QualType getObjCNSStringType() const { 1825 return ObjCNSStringType; 1826 } 1827 1828 void setObjCNSStringType(QualType T) { 1829 ObjCNSStringType = T; 1830 } 1831 1832 /// Retrieve the type that \c id has been defined to, which may be 1833 /// different from the built-in \c id if \c id has been typedef'd. 1834 QualType getObjCIdRedefinitionType() const { 1835 if (ObjCIdRedefinitionType.isNull()) 1836 return getObjCIdType(); 1837 return ObjCIdRedefinitionType; 1838 } 1839 1840 /// Set the user-written type that redefines \c id. 1841 void setObjCIdRedefinitionType(QualType RedefType) { 1842 ObjCIdRedefinitionType = RedefType; 1843 } 1844 1845 /// Retrieve the type that \c Class has been defined to, which may be 1846 /// different from the built-in \c Class if \c Class has been typedef'd. 1847 QualType getObjCClassRedefinitionType() const { 1848 if (ObjCClassRedefinitionType.isNull()) 1849 return getObjCClassType(); 1850 return ObjCClassRedefinitionType; 1851 } 1852 1853 /// Set the user-written type that redefines 'SEL'. 1854 void setObjCClassRedefinitionType(QualType RedefType) { 1855 ObjCClassRedefinitionType = RedefType; 1856 } 1857 1858 /// Retrieve the type that 'SEL' has been defined to, which may be 1859 /// different from the built-in 'SEL' if 'SEL' has been typedef'd. 1860 QualType getObjCSelRedefinitionType() const { 1861 if (ObjCSelRedefinitionType.isNull()) 1862 return getObjCSelType(); 1863 return ObjCSelRedefinitionType; 1864 } 1865 1866 /// Set the user-written type that redefines 'SEL'. 1867 void setObjCSelRedefinitionType(QualType RedefType) { 1868 ObjCSelRedefinitionType = RedefType; 1869 } 1870 1871 /// Retrieve the identifier 'NSObject'. 1872 IdentifierInfo *getNSObjectName() const { 1873 if (!NSObjectName) { 1874 NSObjectName = &Idents.get("NSObject"); 1875 } 1876 1877 return NSObjectName; 1878 } 1879 1880 /// Retrieve the identifier 'NSCopying'. 1881 IdentifierInfo *getNSCopyingName() { 1882 if (!NSCopyingName) { 1883 NSCopyingName = &Idents.get("NSCopying"); 1884 } 1885 1886 return NSCopyingName; 1887 } 1888 1889 CanQualType getNSUIntegerType() const; 1890 1891 CanQualType getNSIntegerType() const; 1892 1893 /// Retrieve the identifier 'bool'. 1894 IdentifierInfo *getBoolName() const { 1895 if (!BoolName) 1896 BoolName = &Idents.get("bool"); 1897 return BoolName; 1898 } 1899 1900 IdentifierInfo *getMakeIntegerSeqName() const { 1901 if (!MakeIntegerSeqName) 1902 MakeIntegerSeqName = &Idents.get("__make_integer_seq"); 1903 return MakeIntegerSeqName; 1904 } 1905 1906 IdentifierInfo *getTypePackElementName() const { 1907 if (!TypePackElementName) 1908 TypePackElementName = &Idents.get("__type_pack_element"); 1909 return TypePackElementName; 1910 } 1911 1912 /// Retrieve the Objective-C "instancetype" type, if already known; 1913 /// otherwise, returns a NULL type; 1914 QualType getObjCInstanceType() { 1915 return getTypeDeclType(getObjCInstanceTypeDecl()); 1916 } 1917 1918 /// Retrieve the typedef declaration corresponding to the Objective-C 1919 /// "instancetype" type. 1920 TypedefDecl *getObjCInstanceTypeDecl(); 1921 1922 /// Set the type for the C FILE type. 1923 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; } 1924 1925 /// Retrieve the C FILE type. 1926 QualType getFILEType() const { 1927 if (FILEDecl) 1928 return getTypeDeclType(FILEDecl); 1929 return QualType(); 1930 } 1931 1932 /// Set the type for the C jmp_buf type. 1933 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) { 1934 this->jmp_bufDecl = jmp_bufDecl; 1935 } 1936 1937 /// Retrieve the C jmp_buf type. 1938 QualType getjmp_bufType() const { 1939 if (jmp_bufDecl) 1940 return getTypeDeclType(jmp_bufDecl); 1941 return QualType(); 1942 } 1943 1944 /// Set the type for the C sigjmp_buf type. 1945 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) { 1946 this->sigjmp_bufDecl = sigjmp_bufDecl; 1947 } 1948 1949 /// Retrieve the C sigjmp_buf type. 1950 QualType getsigjmp_bufType() const { 1951 if (sigjmp_bufDecl) 1952 return getTypeDeclType(sigjmp_bufDecl); 1953 return QualType(); 1954 } 1955 1956 /// Set the type for the C ucontext_t type. 1957 void setucontext_tDecl(TypeDecl *ucontext_tDecl) { 1958 this->ucontext_tDecl = ucontext_tDecl; 1959 } 1960 1961 /// Retrieve the C ucontext_t type. 1962 QualType getucontext_tType() const { 1963 if (ucontext_tDecl) 1964 return getTypeDeclType(ucontext_tDecl); 1965 return QualType(); 1966 } 1967 1968 /// The result type of logical operations, '<', '>', '!=', etc. 1969 QualType getLogicalOperationType() const { 1970 return getLangOpts().CPlusPlus ? BoolTy : IntTy; 1971 } 1972 1973 /// Emit the Objective-CC type encoding for the given type \p T into 1974 /// \p S. 1975 /// 1976 /// If \p Field is specified then record field names are also encoded. 1977 void getObjCEncodingForType(QualType T, std::string &S, 1978 const FieldDecl *Field=nullptr, 1979 QualType *NotEncodedT=nullptr) const; 1980 1981 /// Emit the Objective-C property type encoding for the given 1982 /// type \p T into \p S. 1983 void getObjCEncodingForPropertyType(QualType T, std::string &S) const; 1984 1985 void getLegacyIntegralTypeEncoding(QualType &t) const; 1986 1987 /// Put the string version of the type qualifiers \p QT into \p S. 1988 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 1989 std::string &S) const; 1990 1991 /// Emit the encoded type for the function \p Decl into \p S. 1992 /// 1993 /// This is in the same format as Objective-C method encodings. 1994 /// 1995 /// \returns true if an error occurred (e.g., because one of the parameter 1996 /// types is incomplete), false otherwise. 1997 std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const; 1998 1999 /// Emit the encoded type for the method declaration \p Decl into 2000 /// \p S. 2001 std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 2002 bool Extended = false) const; 2003 2004 /// Return the encoded type for this block declaration. 2005 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const; 2006 2007 /// getObjCEncodingForPropertyDecl - Return the encoded type for 2008 /// this method declaration. If non-NULL, Container must be either 2009 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should 2010 /// only be NULL when getting encodings for protocol properties. 2011 std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 2012 const Decl *Container) const; 2013 2014 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 2015 ObjCProtocolDecl *rProto) const; 2016 2017 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl( 2018 const ObjCPropertyDecl *PD, 2019 const Decl *Container) const; 2020 2021 /// Return the size of type \p T for Objective-C encoding purpose, 2022 /// in characters. 2023 CharUnits getObjCEncodingTypeSize(QualType T) const; 2024 2025 /// Retrieve the typedef corresponding to the predefined \c id type 2026 /// in Objective-C. 2027 TypedefDecl *getObjCIdDecl() const; 2028 2029 /// Represents the Objective-CC \c id type. 2030 /// 2031 /// This is set up lazily, by Sema. \c id is always a (typedef for a) 2032 /// pointer type, a pointer to a struct. 2033 QualType getObjCIdType() const { 2034 return getTypeDeclType(getObjCIdDecl()); 2035 } 2036 2037 /// Retrieve the typedef corresponding to the predefined 'SEL' type 2038 /// in Objective-C. 2039 TypedefDecl *getObjCSelDecl() const; 2040 2041 /// Retrieve the type that corresponds to the predefined Objective-C 2042 /// 'SEL' type. 2043 QualType getObjCSelType() const { 2044 return getTypeDeclType(getObjCSelDecl()); 2045 } 2046 2047 /// Retrieve the typedef declaration corresponding to the predefined 2048 /// Objective-C 'Class' type. 2049 TypedefDecl *getObjCClassDecl() const; 2050 2051 /// Represents the Objective-C \c Class type. 2052 /// 2053 /// This is set up lazily, by Sema. \c Class is always a (typedef for a) 2054 /// pointer type, a pointer to a struct. 2055 QualType getObjCClassType() const { 2056 return getTypeDeclType(getObjCClassDecl()); 2057 } 2058 2059 /// Retrieve the Objective-C class declaration corresponding to 2060 /// the predefined \c Protocol class. 2061 ObjCInterfaceDecl *getObjCProtocolDecl() const; 2062 2063 /// Retrieve declaration of 'BOOL' typedef 2064 TypedefDecl *getBOOLDecl() const { 2065 return BOOLDecl; 2066 } 2067 2068 /// Save declaration of 'BOOL' typedef 2069 void setBOOLDecl(TypedefDecl *TD) { 2070 BOOLDecl = TD; 2071 } 2072 2073 /// type of 'BOOL' type. 2074 QualType getBOOLType() const { 2075 return getTypeDeclType(getBOOLDecl()); 2076 } 2077 2078 /// Retrieve the type of the Objective-C \c Protocol class. 2079 QualType getObjCProtoType() const { 2080 return getObjCInterfaceType(getObjCProtocolDecl()); 2081 } 2082 2083 /// Retrieve the C type declaration corresponding to the predefined 2084 /// \c __builtin_va_list type. 2085 TypedefDecl *getBuiltinVaListDecl() const; 2086 2087 /// Retrieve the type of the \c __builtin_va_list type. 2088 QualType getBuiltinVaListType() const { 2089 return getTypeDeclType(getBuiltinVaListDecl()); 2090 } 2091 2092 /// Retrieve the C type declaration corresponding to the predefined 2093 /// \c __va_list_tag type used to help define the \c __builtin_va_list type 2094 /// for some targets. 2095 Decl *getVaListTagDecl() const; 2096 2097 /// Retrieve the C type declaration corresponding to the predefined 2098 /// \c __builtin_ms_va_list type. 2099 TypedefDecl *getBuiltinMSVaListDecl() const; 2100 2101 /// Retrieve the type of the \c __builtin_ms_va_list type. 2102 QualType getBuiltinMSVaListType() const { 2103 return getTypeDeclType(getBuiltinMSVaListDecl()); 2104 } 2105 2106 /// Retrieve the implicitly-predeclared 'struct _GUID' declaration. 2107 TagDecl *getMSGuidTagDecl() const { return MSGuidTagDecl; } 2108 2109 /// Retrieve the implicitly-predeclared 'struct _GUID' type. 2110 QualType getMSGuidType() const { 2111 assert(MSGuidTagDecl && "asked for GUID type but MS extensions disabled"); 2112 return getTagDeclType(MSGuidTagDecl); 2113 } 2114 2115 /// Return whether a declaration to a builtin is allowed to be 2116 /// overloaded/redeclared. 2117 bool canBuiltinBeRedeclared(const FunctionDecl *) const; 2118 2119 /// Return a type with additional \c const, \c volatile, or 2120 /// \c restrict qualifiers. 2121 QualType getCVRQualifiedType(QualType T, unsigned CVR) const { 2122 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR)); 2123 } 2124 2125 /// Un-split a SplitQualType. 2126 QualType getQualifiedType(SplitQualType split) const { 2127 return getQualifiedType(split.Ty, split.Quals); 2128 } 2129 2130 /// Return a type with additional qualifiers. 2131 QualType getQualifiedType(QualType T, Qualifiers Qs) const { 2132 if (!Qs.hasNonFastQualifiers()) 2133 return T.withFastQualifiers(Qs.getFastQualifiers()); 2134 QualifierCollector Qc(Qs); 2135 const Type *Ptr = Qc.strip(T); 2136 return getExtQualType(Ptr, Qc); 2137 } 2138 2139 /// Return a type with additional qualifiers. 2140 QualType getQualifiedType(const Type *T, Qualifiers Qs) const { 2141 if (!Qs.hasNonFastQualifiers()) 2142 return QualType(T, Qs.getFastQualifiers()); 2143 return getExtQualType(T, Qs); 2144 } 2145 2146 /// Return a type with the given lifetime qualifier. 2147 /// 2148 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None. 2149 QualType getLifetimeQualifiedType(QualType type, 2150 Qualifiers::ObjCLifetime lifetime) { 2151 assert(type.getObjCLifetime() == Qualifiers::OCL_None); 2152 assert(lifetime != Qualifiers::OCL_None); 2153 2154 Qualifiers qs; 2155 qs.addObjCLifetime(lifetime); 2156 return getQualifiedType(type, qs); 2157 } 2158 2159 /// getUnqualifiedObjCPointerType - Returns version of 2160 /// Objective-C pointer type with lifetime qualifier removed. 2161 QualType getUnqualifiedObjCPointerType(QualType type) const { 2162 if (!type.getTypePtr()->isObjCObjectPointerType() || 2163 !type.getQualifiers().hasObjCLifetime()) 2164 return type; 2165 Qualifiers Qs = type.getQualifiers(); 2166 Qs.removeObjCLifetime(); 2167 return getQualifiedType(type.getUnqualifiedType(), Qs); 2168 } 2169 2170 unsigned char getFixedPointScale(QualType Ty) const; 2171 unsigned char getFixedPointIBits(QualType Ty) const; 2172 llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const; 2173 llvm::APFixedPoint getFixedPointMax(QualType Ty) const; 2174 llvm::APFixedPoint getFixedPointMin(QualType Ty) const; 2175 2176 DeclarationNameInfo getNameForTemplate(TemplateName Name, 2177 SourceLocation NameLoc) const; 2178 2179 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, 2180 UnresolvedSetIterator End) const; 2181 TemplateName getAssumedTemplateName(DeclarationName Name) const; 2182 2183 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, 2184 bool TemplateKeyword, 2185 TemplateName Template) const; 2186 2187 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, 2188 const IdentifierInfo *Name) const; 2189 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, 2190 OverloadedOperatorKind Operator) const; 2191 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 2192 TemplateName replacement) const; 2193 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 2194 const TemplateArgument &ArgPack) const; 2195 2196 enum GetBuiltinTypeError { 2197 /// No error 2198 GE_None, 2199 2200 /// Missing a type 2201 GE_Missing_type, 2202 2203 /// Missing a type from <stdio.h> 2204 GE_Missing_stdio, 2205 2206 /// Missing a type from <setjmp.h> 2207 GE_Missing_setjmp, 2208 2209 /// Missing a type from <ucontext.h> 2210 GE_Missing_ucontext 2211 }; 2212 2213 QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, 2214 ASTContext::GetBuiltinTypeError &Error, 2215 bool &RequireICE, bool AllowTypeModifiers) const; 2216 2217 /// Return the type for the specified builtin. 2218 /// 2219 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of 2220 /// arguments to the builtin that are required to be integer constant 2221 /// expressions. 2222 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, 2223 unsigned *IntegerConstantArgs = nullptr) const; 2224 2225 /// Types and expressions required to build C++2a three-way comparisons 2226 /// using operator<=>, including the values return by builtin <=> operators. 2227 ComparisonCategories CompCategories; 2228 2229 private: 2230 CanQualType getFromTargetType(unsigned Type) const; 2231 TypeInfo getTypeInfoImpl(const Type *T) const; 2232 2233 //===--------------------------------------------------------------------===// 2234 // Type Predicates. 2235 //===--------------------------------------------------------------------===// 2236 2237 public: 2238 /// Return one of the GCNone, Weak or Strong Objective-C garbage 2239 /// collection attributes. 2240 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const; 2241 2242 /// Return true if the given vector types are of the same unqualified 2243 /// type or if they are equivalent to the same GCC vector type. 2244 /// 2245 /// \note This ignores whether they are target-specific (AltiVec or Neon) 2246 /// types. 2247 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec); 2248 2249 /// Return true if the given types are an SVE builtin and a VectorType that 2250 /// is a fixed-length representation of the SVE builtin for a specific 2251 /// vector-length. 2252 bool areCompatibleSveTypes(QualType FirstType, QualType SecondType); 2253 2254 /// Return true if the given vector types are lax-compatible SVE vector types, 2255 /// false otherwise. 2256 bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType); 2257 2258 /// Return true if the type has been explicitly qualified with ObjC ownership. 2259 /// A type may be implicitly qualified with ownership under ObjC ARC, and in 2260 /// some cases the compiler treats these differently. 2261 bool hasDirectOwnershipQualifier(QualType Ty) const; 2262 2263 /// Return true if this is an \c NSObject object with its \c NSObject 2264 /// attribute set. 2265 static bool isObjCNSObjectType(QualType Ty) { 2266 return Ty->isObjCNSObjectType(); 2267 } 2268 2269 //===--------------------------------------------------------------------===// 2270 // Type Sizing and Analysis 2271 //===--------------------------------------------------------------------===// 2272 2273 /// Return the APFloat 'semantics' for the specified scalar floating 2274 /// point type. 2275 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const; 2276 2277 /// Get the size and alignment of the specified complete type in bits. 2278 TypeInfo getTypeInfo(const Type *T) const; 2279 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); } 2280 2281 /// Get default simd alignment of the specified complete type in bits. 2282 unsigned getOpenMPDefaultSimdAlign(QualType T) const; 2283 2284 /// Return the size of the specified (complete) type \p T, in bits. 2285 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; } 2286 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; } 2287 2288 /// Return the size of the character type, in bits. 2289 uint64_t getCharWidth() const { 2290 return getTypeSize(CharTy); 2291 } 2292 2293 /// Convert a size in bits to a size in characters. 2294 CharUnits toCharUnitsFromBits(int64_t BitSize) const; 2295 2296 /// Convert a size in characters to a size in bits. 2297 int64_t toBits(CharUnits CharSize) const; 2298 2299 /// Return the size of the specified (complete) type \p T, in 2300 /// characters. 2301 CharUnits getTypeSizeInChars(QualType T) const; 2302 CharUnits getTypeSizeInChars(const Type *T) const; 2303 2304 Optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const { 2305 if (Ty->isIncompleteType() || Ty->isDependentType()) 2306 return None; 2307 return getTypeSizeInChars(Ty); 2308 } 2309 2310 Optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const { 2311 return getTypeSizeInCharsIfKnown(QualType(Ty, 0)); 2312 } 2313 2314 /// Return the ABI-specified alignment of a (complete) type \p T, in 2315 /// bits. 2316 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; } 2317 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; } 2318 2319 /// Return the ABI-specified natural alignment of a (complete) type \p T, 2320 /// before alignment adjustments, in bits. 2321 /// 2322 /// This alignment is curently used only by ARM and AArch64 when passing 2323 /// arguments of a composite type. 2324 unsigned getTypeUnadjustedAlign(QualType T) const { 2325 return getTypeUnadjustedAlign(T.getTypePtr()); 2326 } 2327 unsigned getTypeUnadjustedAlign(const Type *T) const; 2328 2329 /// Return the alignment of a type, in bits, or 0 if 2330 /// the type is incomplete and we cannot determine the alignment (for 2331 /// example, from alignment attributes). The returned alignment is the 2332 /// Preferred alignment if NeedsPreferredAlignment is true, otherwise is the 2333 /// ABI alignment. 2334 unsigned getTypeAlignIfKnown(QualType T, 2335 bool NeedsPreferredAlignment = false) const; 2336 2337 /// Return the ABI-specified alignment of a (complete) type \p T, in 2338 /// characters. 2339 CharUnits getTypeAlignInChars(QualType T) const; 2340 CharUnits getTypeAlignInChars(const Type *T) const; 2341 2342 /// Return the PreferredAlignment of a (complete) type \p T, in 2343 /// characters. 2344 CharUnits getPreferredTypeAlignInChars(QualType T) const { 2345 return toCharUnitsFromBits(getPreferredTypeAlign(T)); 2346 } 2347 2348 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, 2349 /// in characters, before alignment adjustments. This method does not work on 2350 /// incomplete types. 2351 CharUnits getTypeUnadjustedAlignInChars(QualType T) const; 2352 CharUnits getTypeUnadjustedAlignInChars(const Type *T) const; 2353 2354 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the 2355 // type is a record, its data size is returned. 2356 TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const; 2357 2358 TypeInfoChars getTypeInfoInChars(const Type *T) const; 2359 TypeInfoChars getTypeInfoInChars(QualType T) const; 2360 2361 /// Determine if the alignment the type has was required using an 2362 /// alignment attribute. 2363 bool isAlignmentRequired(const Type *T) const; 2364 bool isAlignmentRequired(QualType T) const; 2365 2366 /// Return the "preferred" alignment of the specified type \p T for 2367 /// the current target, in bits. 2368 /// 2369 /// This can be different than the ABI alignment in cases where it is 2370 /// beneficial for performance or backwards compatibility preserving to 2371 /// overalign a data type. (Note: despite the name, the preferred alignment 2372 /// is ABI-impacting, and not an optimization.) 2373 unsigned getPreferredTypeAlign(QualType T) const { 2374 return getPreferredTypeAlign(T.getTypePtr()); 2375 } 2376 unsigned getPreferredTypeAlign(const Type *T) const; 2377 2378 /// Return the default alignment for __attribute__((aligned)) on 2379 /// this target, to be used if no alignment value is specified. 2380 unsigned getTargetDefaultAlignForAttributeAligned() const; 2381 2382 /// Return the alignment in bits that should be given to a 2383 /// global variable with type \p T. 2384 unsigned getAlignOfGlobalVar(QualType T) const; 2385 2386 /// Return the alignment in characters that should be given to a 2387 /// global variable with type \p T. 2388 CharUnits getAlignOfGlobalVarInChars(QualType T) const; 2389 2390 /// Return a conservative estimate of the alignment of the specified 2391 /// decl \p D. 2392 /// 2393 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid 2394 /// alignment. 2395 /// 2396 /// If \p ForAlignof, references are treated like their underlying type 2397 /// and large arrays don't get any special treatment. If not \p ForAlignof 2398 /// it computes the value expected by CodeGen: references are treated like 2399 /// pointers and large arrays get extra alignment. 2400 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const; 2401 2402 /// Return the alignment (in bytes) of the thrown exception object. This is 2403 /// only meaningful for targets that allocate C++ exceptions in a system 2404 /// runtime, such as those using the Itanium C++ ABI. 2405 CharUnits getExnObjectAlignment() const; 2406 2407 /// Get or compute information about the layout of the specified 2408 /// record (struct/union/class) \p D, which indicates its size and field 2409 /// position information. 2410 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const; 2411 2412 /// Get or compute information about the layout of the specified 2413 /// Objective-C interface. 2414 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) 2415 const; 2416 2417 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS, 2418 bool Simple = false) const; 2419 2420 /// Get or compute information about the layout of the specified 2421 /// Objective-C implementation. 2422 /// 2423 /// This may differ from the interface if synthesized ivars are present. 2424 const ASTRecordLayout & 2425 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const; 2426 2427 /// Get our current best idea for the key function of the 2428 /// given record decl, or nullptr if there isn't one. 2429 /// 2430 /// The key function is, according to the Itanium C++ ABI section 5.2.3: 2431 /// ...the first non-pure virtual function that is not inline at the 2432 /// point of class definition. 2433 /// 2434 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores 2435 /// virtual functions that are defined 'inline', which means that 2436 /// the result of this computation can change. 2437 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD); 2438 2439 /// Observe that the given method cannot be a key function. 2440 /// Checks the key-function cache for the method's class and clears it 2441 /// if matches the given declaration. 2442 /// 2443 /// This is used in ABIs where out-of-line definitions marked 2444 /// inline are not considered to be key functions. 2445 /// 2446 /// \param method should be the declaration from the class definition 2447 void setNonKeyFunction(const CXXMethodDecl *method); 2448 2449 /// Loading virtual member pointers using the virtual inheritance model 2450 /// always results in an adjustment using the vbtable even if the index is 2451 /// zero. 2452 /// 2453 /// This is usually OK because the first slot in the vbtable points 2454 /// backwards to the top of the MDC. However, the MDC might be reusing a 2455 /// vbptr from an nv-base. In this case, the first slot in the vbtable 2456 /// points to the start of the nv-base which introduced the vbptr and *not* 2457 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this. 2458 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const; 2459 2460 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits. 2461 uint64_t getFieldOffset(const ValueDecl *FD) const; 2462 2463 /// Get the offset of an ObjCIvarDecl in bits. 2464 uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, 2465 const ObjCImplementationDecl *ID, 2466 const ObjCIvarDecl *Ivar) const; 2467 2468 /// Find the 'this' offset for the member path in a pointer-to-member 2469 /// APValue. 2470 CharUnits getMemberPointerPathAdjustment(const APValue &MP) const; 2471 2472 bool isNearlyEmpty(const CXXRecordDecl *RD) const; 2473 2474 VTableContextBase *getVTableContext(); 2475 2476 /// If \p T is null pointer, assume the target in ASTContext. 2477 MangleContext *createMangleContext(const TargetInfo *T = nullptr); 2478 2479 /// Creates a device mangle context to correctly mangle lambdas in a mixed 2480 /// architecture compile by setting the lambda mangling number source to the 2481 /// DeviceLambdaManglingNumber. Currently this asserts that the TargetInfo 2482 /// (from the AuxTargetInfo) is a an itanium target. 2483 MangleContext *createDeviceMangleContext(const TargetInfo &T); 2484 2485 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, 2486 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const; 2487 2488 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const; 2489 void CollectInheritedProtocols(const Decl *CDecl, 2490 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols); 2491 2492 /// Return true if the specified type has unique object representations 2493 /// according to (C++17 [meta.unary.prop]p9) 2494 bool hasUniqueObjectRepresentations(QualType Ty) const; 2495 2496 //===--------------------------------------------------------------------===// 2497 // Type Operators 2498 //===--------------------------------------------------------------------===// 2499 2500 /// Return the canonical (structural) type corresponding to the 2501 /// specified potentially non-canonical type \p T. 2502 /// 2503 /// The non-canonical version of a type may have many "decorated" versions of 2504 /// types. Decorators can include typedefs, 'typeof' operators, etc. The 2505 /// returned type is guaranteed to be free of any of these, allowing two 2506 /// canonical types to be compared for exact equality with a simple pointer 2507 /// comparison. 2508 CanQualType getCanonicalType(QualType T) const { 2509 return CanQualType::CreateUnsafe(T.getCanonicalType()); 2510 } 2511 2512 const Type *getCanonicalType(const Type *T) const { 2513 return T->getCanonicalTypeInternal().getTypePtr(); 2514 } 2515 2516 /// Return the canonical parameter type corresponding to the specific 2517 /// potentially non-canonical one. 2518 /// 2519 /// Qualifiers are stripped off, functions are turned into function 2520 /// pointers, and arrays decay one level into pointers. 2521 CanQualType getCanonicalParamType(QualType T) const; 2522 2523 /// Determine whether the given types \p T1 and \p T2 are equivalent. 2524 bool hasSameType(QualType T1, QualType T2) const { 2525 return getCanonicalType(T1) == getCanonicalType(T2); 2526 } 2527 bool hasSameType(const Type *T1, const Type *T2) const { 2528 return getCanonicalType(T1) == getCanonicalType(T2); 2529 } 2530 2531 /// Return this type as a completely-unqualified array type, 2532 /// capturing the qualifiers in \p Quals. 2533 /// 2534 /// This will remove the minimal amount of sugaring from the types, similar 2535 /// to the behavior of QualType::getUnqualifiedType(). 2536 /// 2537 /// \param T is the qualified type, which may be an ArrayType 2538 /// 2539 /// \param Quals will receive the full set of qualifiers that were 2540 /// applied to the array. 2541 /// 2542 /// \returns if this is an array type, the completely unqualified array type 2543 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType(). 2544 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals); 2545 2546 /// Determine whether the given types are equivalent after 2547 /// cvr-qualifiers have been removed. 2548 bool hasSameUnqualifiedType(QualType T1, QualType T2) const { 2549 return getCanonicalType(T1).getTypePtr() == 2550 getCanonicalType(T2).getTypePtr(); 2551 } 2552 2553 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT, 2554 bool IsParam) const { 2555 auto SubTnullability = SubT->getNullability(*this); 2556 auto SuperTnullability = SuperT->getNullability(*this); 2557 if (SubTnullability.has_value() == SuperTnullability.has_value()) { 2558 // Neither has nullability; return true 2559 if (!SubTnullability) 2560 return true; 2561 // Both have nullability qualifier. 2562 if (*SubTnullability == *SuperTnullability || 2563 *SubTnullability == NullabilityKind::Unspecified || 2564 *SuperTnullability == NullabilityKind::Unspecified) 2565 return true; 2566 2567 if (IsParam) { 2568 // Ok for the superclass method parameter to be "nonnull" and the subclass 2569 // method parameter to be "nullable" 2570 return (*SuperTnullability == NullabilityKind::NonNull && 2571 *SubTnullability == NullabilityKind::Nullable); 2572 } 2573 // For the return type, it's okay for the superclass method to specify 2574 // "nullable" and the subclass method specify "nonnull" 2575 return (*SuperTnullability == NullabilityKind::Nullable && 2576 *SubTnullability == NullabilityKind::NonNull); 2577 } 2578 return true; 2579 } 2580 2581 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, 2582 const ObjCMethodDecl *MethodImp); 2583 2584 bool UnwrapSimilarTypes(QualType &T1, QualType &T2, 2585 bool AllowPiMismatch = true); 2586 void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, 2587 bool AllowPiMismatch = true); 2588 2589 /// Determine if two types are similar, according to the C++ rules. That is, 2590 /// determine if they are the same other than qualifiers on the initial 2591 /// sequence of pointer / pointer-to-member / array (and in Clang, object 2592 /// pointer) types and their element types. 2593 /// 2594 /// Clang offers a number of qualifiers in addition to the C++ qualifiers; 2595 /// those qualifiers are also ignored in the 'similarity' check. 2596 bool hasSimilarType(QualType T1, QualType T2); 2597 2598 /// Determine if two types are similar, ignoring only CVR qualifiers. 2599 bool hasCvrSimilarType(QualType T1, QualType T2); 2600 2601 /// Retrieves the "canonical" nested name specifier for a 2602 /// given nested name specifier. 2603 /// 2604 /// The canonical nested name specifier is a nested name specifier 2605 /// that uniquely identifies a type or namespace within the type 2606 /// system. For example, given: 2607 /// 2608 /// \code 2609 /// namespace N { 2610 /// struct S { 2611 /// template<typename T> struct X { typename T* type; }; 2612 /// }; 2613 /// } 2614 /// 2615 /// template<typename T> struct Y { 2616 /// typename N::S::X<T>::type member; 2617 /// }; 2618 /// \endcode 2619 /// 2620 /// Here, the nested-name-specifier for N::S::X<T>:: will be 2621 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined 2622 /// by declarations in the type system and the canonical type for 2623 /// the template type parameter 'T' is template-param-0-0. 2624 NestedNameSpecifier * 2625 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const; 2626 2627 /// Retrieves the default calling convention for the current target. 2628 CallingConv getDefaultCallingConvention(bool IsVariadic, 2629 bool IsCXXMethod, 2630 bool IsBuiltin = false) const; 2631 2632 /// Retrieves the "canonical" template name that refers to a 2633 /// given template. 2634 /// 2635 /// The canonical template name is the simplest expression that can 2636 /// be used to refer to a given template. For most templates, this 2637 /// expression is just the template declaration itself. For example, 2638 /// the template std::vector can be referred to via a variety of 2639 /// names---std::vector, \::std::vector, vector (if vector is in 2640 /// scope), etc.---but all of these names map down to the same 2641 /// TemplateDecl, which is used to form the canonical template name. 2642 /// 2643 /// Dependent template names are more interesting. Here, the 2644 /// template name could be something like T::template apply or 2645 /// std::allocator<T>::template rebind, where the nested name 2646 /// specifier itself is dependent. In this case, the canonical 2647 /// template name uses the shortest form of the dependent 2648 /// nested-name-specifier, which itself contains all canonical 2649 /// types, values, and templates. 2650 TemplateName getCanonicalTemplateName(const TemplateName &Name) const; 2651 2652 /// Determine whether the given template names refer to the same 2653 /// template. 2654 bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const; 2655 2656 /// Determine whether the two declarations refer to the same entity. 2657 bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const; 2658 2659 /// Determine whether two template parameter lists are similar enough 2660 /// that they may be used in declarations of the same template. 2661 bool isSameTemplateParameterList(const TemplateParameterList *X, 2662 const TemplateParameterList *Y) const; 2663 2664 /// Determine whether two template parameters are similar enough 2665 /// that they may be used in declarations of the same template. 2666 bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const; 2667 2668 /// Determine whether two 'requires' expressions are similar enough that they 2669 /// may be used in re-declarations. 2670 /// 2671 /// Use of 'requires' isn't mandatory, works with constraints expressed in 2672 /// other ways too. 2673 bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const; 2674 2675 /// Determine whether two type contraint are similar enough that they could 2676 /// used in declarations of the same template. 2677 bool isSameTypeConstraint(const TypeConstraint *XTC, 2678 const TypeConstraint *YTC) const; 2679 2680 /// Determine whether two default template arguments are similar enough 2681 /// that they may be used in declarations of the same template. 2682 bool isSameDefaultTemplateArgument(const NamedDecl *X, 2683 const NamedDecl *Y) const; 2684 2685 /// Retrieve the "canonical" template argument. 2686 /// 2687 /// The canonical template argument is the simplest template argument 2688 /// (which may be a type, value, expression, or declaration) that 2689 /// expresses the value of the argument. 2690 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) 2691 const; 2692 2693 /// Type Query functions. If the type is an instance of the specified class, 2694 /// return the Type pointer for the underlying maximally pretty type. This 2695 /// is a member of ASTContext because this may need to do some amount of 2696 /// canonicalization, e.g. to move type qualifiers into the element type. 2697 const ArrayType *getAsArrayType(QualType T) const; 2698 const ConstantArrayType *getAsConstantArrayType(QualType T) const { 2699 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T)); 2700 } 2701 const VariableArrayType *getAsVariableArrayType(QualType T) const { 2702 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T)); 2703 } 2704 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const { 2705 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T)); 2706 } 2707 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T) 2708 const { 2709 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T)); 2710 } 2711 2712 /// Return the innermost element type of an array type. 2713 /// 2714 /// For example, will return "int" for int[m][n] 2715 QualType getBaseElementType(const ArrayType *VAT) const; 2716 2717 /// Return the innermost element type of a type (which needn't 2718 /// actually be an array type). 2719 QualType getBaseElementType(QualType QT) const; 2720 2721 /// Return number of constant array elements. 2722 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const; 2723 2724 /// Perform adjustment on the parameter type of a function. 2725 /// 2726 /// This routine adjusts the given parameter type @p T to the actual 2727 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8], 2728 /// C++ [dcl.fct]p3). The adjusted parameter type is returned. 2729 QualType getAdjustedParameterType(QualType T) const; 2730 2731 /// Retrieve the parameter type as adjusted for use in the signature 2732 /// of a function, decaying array and function types and removing top-level 2733 /// cv-qualifiers. 2734 QualType getSignatureParameterType(QualType T) const; 2735 2736 QualType getExceptionObjectType(QualType T) const; 2737 2738 /// Return the properly qualified result of decaying the specified 2739 /// array type to a pointer. 2740 /// 2741 /// This operation is non-trivial when handling typedefs etc. The canonical 2742 /// type of \p T must be an array type, this returns a pointer to a properly 2743 /// qualified element of the array. 2744 /// 2745 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 2746 QualType getArrayDecayedType(QualType T) const; 2747 2748 /// Return the type that \p PromotableType will promote to: C99 2749 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type. 2750 QualType getPromotedIntegerType(QualType PromotableType) const; 2751 2752 /// Recurses in pointer/array types until it finds an Objective-C 2753 /// retainable type and returns its ownership. 2754 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const; 2755 2756 /// Whether this is a promotable bitfield reference according 2757 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 2758 /// 2759 /// \returns the type this bit-field will promote to, or NULL if no 2760 /// promotion occurs. 2761 QualType isPromotableBitField(Expr *E) const; 2762 2763 /// Return the highest ranked integer type, see C99 6.3.1.8p1. 2764 /// 2765 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If 2766 /// \p LHS < \p RHS, return -1. 2767 int getIntegerTypeOrder(QualType LHS, QualType RHS) const; 2768 2769 /// Compare the rank of the two specified floating point types, 2770 /// ignoring the domain of the type (i.e. 'double' == '_Complex double'). 2771 /// 2772 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If 2773 /// \p LHS < \p RHS, return -1. 2774 int getFloatingTypeOrder(QualType LHS, QualType RHS) const; 2775 2776 /// Compare the rank of two floating point types as above, but compare equal 2777 /// if both types have the same floating-point semantics on the target (i.e. 2778 /// long double and double on AArch64 will return 0). 2779 int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const; 2780 2781 unsigned getTargetAddressSpace(QualType T) const; 2782 2783 unsigned getTargetAddressSpace(Qualifiers Q) const; 2784 2785 unsigned getTargetAddressSpace(LangAS AS) const; 2786 2787 LangAS getLangASForBuiltinAddressSpace(unsigned AS) const; 2788 2789 /// Get target-dependent integer value for null pointer which is used for 2790 /// constant folding. 2791 uint64_t getTargetNullPointerValue(QualType QT) const; 2792 2793 bool addressSpaceMapManglingFor(LangAS AS) const { 2794 return AddrSpaceMapMangling || isTargetAddressSpace(AS); 2795 } 2796 2797 private: 2798 // Helper for integer ordering 2799 unsigned getIntegerRank(const Type *T) const; 2800 2801 public: 2802 //===--------------------------------------------------------------------===// 2803 // Type Compatibility Predicates 2804 //===--------------------------------------------------------------------===// 2805 2806 /// Compatibility predicates used to check assignment expressions. 2807 bool typesAreCompatible(QualType T1, QualType T2, 2808 bool CompareUnqualified = false); // C99 6.2.7p1 2809 2810 bool propertyTypesAreCompatible(QualType, QualType); 2811 bool typesAreBlockPointerCompatible(QualType, QualType); 2812 2813 bool isObjCIdType(QualType T) const { 2814 return T == getObjCIdType(); 2815 } 2816 2817 bool isObjCClassType(QualType T) const { 2818 return T == getObjCClassType(); 2819 } 2820 2821 bool isObjCSelType(QualType T) const { 2822 return T == getObjCSelType(); 2823 } 2824 2825 bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, 2826 const ObjCObjectPointerType *RHS, 2827 bool ForCompare); 2828 2829 bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, 2830 const ObjCObjectPointerType *RHS); 2831 2832 // Check the safety of assignment from LHS to RHS 2833 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 2834 const ObjCObjectPointerType *RHSOPT); 2835 bool canAssignObjCInterfaces(const ObjCObjectType *LHS, 2836 const ObjCObjectType *RHS); 2837 bool canAssignObjCInterfacesInBlockPointer( 2838 const ObjCObjectPointerType *LHSOPT, 2839 const ObjCObjectPointerType *RHSOPT, 2840 bool BlockReturnType); 2841 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS); 2842 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, 2843 const ObjCObjectPointerType *RHSOPT); 2844 bool canBindObjCObjectType(QualType To, QualType From); 2845 2846 // Functions for calculating composite types 2847 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, 2848 bool Unqualified = false, bool BlockReturnType = false); 2849 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, 2850 bool Unqualified = false, bool AllowCXX = false); 2851 QualType mergeFunctionParameterTypes(QualType, QualType, 2852 bool OfBlockPointer = false, 2853 bool Unqualified = false); 2854 QualType mergeTransparentUnionType(QualType, QualType, 2855 bool OfBlockPointer=false, 2856 bool Unqualified = false); 2857 2858 QualType mergeObjCGCQualifiers(QualType, QualType); 2859 2860 /// This function merges the ExtParameterInfo lists of two functions. It 2861 /// returns true if the lists are compatible. The merged list is returned in 2862 /// NewParamInfos. 2863 /// 2864 /// \param FirstFnType The type of the first function. 2865 /// 2866 /// \param SecondFnType The type of the second function. 2867 /// 2868 /// \param CanUseFirst This flag is set to true if the first function's 2869 /// ExtParameterInfo list can be used as the composite list of 2870 /// ExtParameterInfo. 2871 /// 2872 /// \param CanUseSecond This flag is set to true if the second function's 2873 /// ExtParameterInfo list can be used as the composite list of 2874 /// ExtParameterInfo. 2875 /// 2876 /// \param NewParamInfos The composite list of ExtParameterInfo. The list is 2877 /// empty if none of the flags are set. 2878 /// 2879 bool mergeExtParameterInfo( 2880 const FunctionProtoType *FirstFnType, 2881 const FunctionProtoType *SecondFnType, 2882 bool &CanUseFirst, bool &CanUseSecond, 2883 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos); 2884 2885 void ResetObjCLayout(const ObjCContainerDecl *CD); 2886 2887 //===--------------------------------------------------------------------===// 2888 // Integer Predicates 2889 //===--------------------------------------------------------------------===// 2890 2891 // The width of an integer, as defined in C99 6.2.6.2. This is the number 2892 // of bits in an integer type excluding any padding bits. 2893 unsigned getIntWidth(QualType T) const; 2894 2895 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding 2896 // unsigned integer type. This method takes a signed type, and returns the 2897 // corresponding unsigned integer type. 2898 // With the introduction of fixed point types in ISO N1169, this method also 2899 // accepts fixed point types and returns the corresponding unsigned type for 2900 // a given fixed point type. 2901 QualType getCorrespondingUnsignedType(QualType T) const; 2902 2903 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding 2904 // unsigned integer type. This method takes an unsigned type, and returns the 2905 // corresponding signed integer type. 2906 // With the introduction of fixed point types in ISO N1169, this method also 2907 // accepts fixed point types and returns the corresponding signed type for 2908 // a given fixed point type. 2909 QualType getCorrespondingSignedType(QualType T) const; 2910 2911 // Per ISO N1169, this method accepts fixed point types and returns the 2912 // corresponding saturated type for a given fixed point type. 2913 QualType getCorrespondingSaturatedType(QualType Ty) const; 2914 2915 // This method accepts fixed point types and returns the corresponding signed 2916 // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned 2917 // fixed point types because there are unsigned integer types like bool and 2918 // char8_t that don't have signed equivalents. 2919 QualType getCorrespondingSignedFixedPointType(QualType Ty) const; 2920 2921 //===--------------------------------------------------------------------===// 2922 // Integer Values 2923 //===--------------------------------------------------------------------===// 2924 2925 /// Make an APSInt of the appropriate width and signedness for the 2926 /// given \p Value and integer \p Type. 2927 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const { 2928 // If Type is a signed integer type larger than 64 bits, we need to be sure 2929 // to sign extend Res appropriately. 2930 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType()); 2931 Res = Value; 2932 unsigned Width = getIntWidth(Type); 2933 if (Width != Res.getBitWidth()) 2934 return Res.extOrTrunc(Width); 2935 return Res; 2936 } 2937 2938 bool isSentinelNullExpr(const Expr *E); 2939 2940 /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if 2941 /// none exists. 2942 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D); 2943 2944 /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if 2945 /// none exists. 2946 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D); 2947 2948 /// Return true if there is at least one \@implementation in the TU. 2949 bool AnyObjCImplementation() { 2950 return !ObjCImpls.empty(); 2951 } 2952 2953 /// Set the implementation of ObjCInterfaceDecl. 2954 void setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2955 ObjCImplementationDecl *ImplD); 2956 2957 /// Set the implementation of ObjCCategoryDecl. 2958 void setObjCImplementation(ObjCCategoryDecl *CatD, 2959 ObjCCategoryImplDecl *ImplD); 2960 2961 /// Get the duplicate declaration of a ObjCMethod in the same 2962 /// interface, or null if none exists. 2963 const ObjCMethodDecl * 2964 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const; 2965 2966 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2967 const ObjCMethodDecl *Redecl); 2968 2969 /// Returns the Objective-C interface that \p ND belongs to if it is 2970 /// an Objective-C method/property/ivar etc. that is part of an interface, 2971 /// otherwise returns null. 2972 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const; 2973 2974 /// Set the copy initialization expression of a block var decl. \p CanThrow 2975 /// indicates whether the copy expression can throw or not. 2976 void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow); 2977 2978 /// Get the copy initialization expression of the VarDecl \p VD, or 2979 /// nullptr if none exists. 2980 BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const; 2981 2982 /// Allocate an uninitialized TypeSourceInfo. 2983 /// 2984 /// The caller should initialize the memory held by TypeSourceInfo using 2985 /// the TypeLoc wrappers. 2986 /// 2987 /// \param T the type that will be the basis for type source info. This type 2988 /// should refer to how the declarator was written in source code, not to 2989 /// what type semantic analysis resolved the declarator to. 2990 /// 2991 /// \param Size the size of the type info to create, or 0 if the size 2992 /// should be calculated based on the type. 2993 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const; 2994 2995 /// Allocate a TypeSourceInfo where all locations have been 2996 /// initialized to a given location, which defaults to the empty 2997 /// location. 2998 TypeSourceInfo * 2999 getTrivialTypeSourceInfo(QualType T, 3000 SourceLocation Loc = SourceLocation()) const; 3001 3002 /// Add a deallocation callback that will be invoked when the 3003 /// ASTContext is destroyed. 3004 /// 3005 /// \param Callback A callback function that will be invoked on destruction. 3006 /// 3007 /// \param Data Pointer data that will be provided to the callback function 3008 /// when it is called. 3009 void AddDeallocation(void (*Callback)(void *), void *Data) const; 3010 3011 /// If T isn't trivially destructible, calls AddDeallocation to register it 3012 /// for destruction. 3013 template <typename T> void addDestruction(T *Ptr) const { 3014 if (!std::is_trivially_destructible<T>::value) { 3015 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); }; 3016 AddDeallocation(DestroyPtr, Ptr); 3017 } 3018 } 3019 3020 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const; 3021 GVALinkage GetGVALinkageForVariable(const VarDecl *VD); 3022 3023 /// Determines if the decl can be CodeGen'ed or deserialized from PCH 3024 /// lazily, only when used; this is only relevant for function or file scoped 3025 /// var definitions. 3026 /// 3027 /// \returns true if the function/var must be CodeGen'ed/deserialized even if 3028 /// it is not used. 3029 bool DeclMustBeEmitted(const Decl *D); 3030 3031 /// Visits all versions of a multiversioned function with the passed 3032 /// predicate. 3033 void forEachMultiversionedFunctionVersion( 3034 const FunctionDecl *FD, 3035 llvm::function_ref<void(FunctionDecl *)> Pred) const; 3036 3037 const CXXConstructorDecl * 3038 getCopyConstructorForExceptionObject(CXXRecordDecl *RD); 3039 3040 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 3041 CXXConstructorDecl *CD); 3042 3043 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND); 3044 3045 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD); 3046 3047 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD); 3048 3049 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD); 3050 3051 void setManglingNumber(const NamedDecl *ND, unsigned Number); 3052 unsigned getManglingNumber(const NamedDecl *ND, 3053 bool ForAuxTarget = false) const; 3054 3055 void setStaticLocalNumber(const VarDecl *VD, unsigned Number); 3056 unsigned getStaticLocalNumber(const VarDecl *VD) const; 3057 3058 /// Retrieve the context for computing mangling numbers in the given 3059 /// DeclContext. 3060 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC); 3061 enum NeedExtraManglingDecl_t { NeedExtraManglingDecl }; 3062 MangleNumberingContext &getManglingNumberContext(NeedExtraManglingDecl_t, 3063 const Decl *D); 3064 3065 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const; 3066 3067 /// Used by ParmVarDecl to store on the side the 3068 /// index of the parameter when it exceeds the size of the normal bitfield. 3069 void setParameterIndex(const ParmVarDecl *D, unsigned index); 3070 3071 /// Used by ParmVarDecl to retrieve on the side the 3072 /// index of the parameter when it exceeds the size of the normal bitfield. 3073 unsigned getParameterIndex(const ParmVarDecl *D) const; 3074 3075 /// Return a string representing the human readable name for the specified 3076 /// function declaration or file name. Used by SourceLocExpr and 3077 /// PredefinedExpr to cache evaluated results. 3078 StringLiteral *getPredefinedStringLiteralFromCache(StringRef Key) const; 3079 3080 /// Return a declaration for the global GUID object representing the given 3081 /// GUID value. 3082 MSGuidDecl *getMSGuidDecl(MSGuidDeclParts Parts) const; 3083 3084 /// Return a declaration for a uniquified anonymous global constant 3085 /// corresponding to a given APValue. 3086 UnnamedGlobalConstantDecl * 3087 getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const; 3088 3089 /// Return the template parameter object of the given type with the given 3090 /// value. 3091 TemplateParamObjectDecl *getTemplateParamObjectDecl(QualType T, 3092 const APValue &V) const; 3093 3094 /// Parses the target attributes passed in, and returns only the ones that are 3095 /// valid feature names. 3096 ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const; 3097 3098 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 3099 const FunctionDecl *) const; 3100 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 3101 GlobalDecl GD) const; 3102 3103 //===--------------------------------------------------------------------===// 3104 // Statistics 3105 //===--------------------------------------------------------------------===// 3106 3107 /// The number of implicitly-declared default constructors. 3108 unsigned NumImplicitDefaultConstructors = 0; 3109 3110 /// The number of implicitly-declared default constructors for 3111 /// which declarations were built. 3112 unsigned NumImplicitDefaultConstructorsDeclared = 0; 3113 3114 /// The number of implicitly-declared copy constructors. 3115 unsigned NumImplicitCopyConstructors = 0; 3116 3117 /// The number of implicitly-declared copy constructors for 3118 /// which declarations were built. 3119 unsigned NumImplicitCopyConstructorsDeclared = 0; 3120 3121 /// The number of implicitly-declared move constructors. 3122 unsigned NumImplicitMoveConstructors = 0; 3123 3124 /// The number of implicitly-declared move constructors for 3125 /// which declarations were built. 3126 unsigned NumImplicitMoveConstructorsDeclared = 0; 3127 3128 /// The number of implicitly-declared copy assignment operators. 3129 unsigned NumImplicitCopyAssignmentOperators = 0; 3130 3131 /// The number of implicitly-declared copy assignment operators for 3132 /// which declarations were built. 3133 unsigned NumImplicitCopyAssignmentOperatorsDeclared = 0; 3134 3135 /// The number of implicitly-declared move assignment operators. 3136 unsigned NumImplicitMoveAssignmentOperators = 0; 3137 3138 /// The number of implicitly-declared move assignment operators for 3139 /// which declarations were built. 3140 unsigned NumImplicitMoveAssignmentOperatorsDeclared = 0; 3141 3142 /// The number of implicitly-declared destructors. 3143 unsigned NumImplicitDestructors = 0; 3144 3145 /// The number of implicitly-declared destructors for which 3146 /// declarations were built. 3147 unsigned NumImplicitDestructorsDeclared = 0; 3148 3149 public: 3150 /// Initialize built-in types. 3151 /// 3152 /// This routine may only be invoked once for a given ASTContext object. 3153 /// It is normally invoked after ASTContext construction. 3154 /// 3155 /// \param Target The target 3156 void InitBuiltinTypes(const TargetInfo &Target, 3157 const TargetInfo *AuxTarget = nullptr); 3158 3159 private: 3160 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K); 3161 3162 class ObjCEncOptions { 3163 unsigned Bits; 3164 3165 ObjCEncOptions(unsigned Bits) : Bits(Bits) {} 3166 3167 public: 3168 ObjCEncOptions() : Bits(0) {} 3169 ObjCEncOptions(const ObjCEncOptions &RHS) : Bits(RHS.Bits) {} 3170 3171 #define OPT_LIST(V) \ 3172 V(ExpandPointedToStructures, 0) \ 3173 V(ExpandStructures, 1) \ 3174 V(IsOutermostType, 2) \ 3175 V(EncodingProperty, 3) \ 3176 V(IsStructField, 4) \ 3177 V(EncodeBlockParameters, 5) \ 3178 V(EncodeClassNames, 6) \ 3179 3180 #define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; } 3181 OPT_LIST(V) 3182 #undef V 3183 3184 #define V(N,I) bool N() const { return Bits & 1 << I; } 3185 OPT_LIST(V) 3186 #undef V 3187 3188 #undef OPT_LIST 3189 3190 LLVM_NODISCARD ObjCEncOptions keepingOnly(ObjCEncOptions Mask) const { 3191 return Bits & Mask.Bits; 3192 } 3193 3194 LLVM_NODISCARD ObjCEncOptions forComponentType() const { 3195 ObjCEncOptions Mask = ObjCEncOptions() 3196 .setIsOutermostType() 3197 .setIsStructField(); 3198 return Bits & ~Mask.Bits; 3199 } 3200 }; 3201 3202 // Return the Objective-C type encoding for a given type. 3203 void getObjCEncodingForTypeImpl(QualType t, std::string &S, 3204 ObjCEncOptions Options, 3205 const FieldDecl *Field, 3206 QualType *NotEncodedT = nullptr) const; 3207 3208 // Adds the encoding of the structure's members. 3209 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S, 3210 const FieldDecl *Field, 3211 bool includeVBases = true, 3212 QualType *NotEncodedT=nullptr) const; 3213 3214 public: 3215 // Adds the encoding of a method parameter or return type. 3216 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 3217 QualType T, std::string& S, 3218 bool Extended) const; 3219 3220 /// Returns true if this is an inline-initialized static data member 3221 /// which is treated as a definition for MSVC compatibility. 3222 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const; 3223 3224 enum class InlineVariableDefinitionKind { 3225 /// Not an inline variable. 3226 None, 3227 3228 /// Weak definition of inline variable. 3229 Weak, 3230 3231 /// Weak for now, might become strong later in this TU. 3232 WeakUnknown, 3233 3234 /// Strong definition. 3235 Strong 3236 }; 3237 3238 /// Determine whether a definition of this inline variable should 3239 /// be treated as a weak or strong definition. For compatibility with 3240 /// C++14 and before, for a constexpr static data member, if there is an 3241 /// out-of-line declaration of the member, we may promote it from weak to 3242 /// strong. 3243 InlineVariableDefinitionKind 3244 getInlineVariableDefinitionKind(const VarDecl *VD) const; 3245 3246 private: 3247 friend class DeclarationNameTable; 3248 friend class DeclContext; 3249 3250 const ASTRecordLayout & 3251 getObjCLayout(const ObjCInterfaceDecl *D, 3252 const ObjCImplementationDecl *Impl) const; 3253 3254 /// A set of deallocations that should be performed when the 3255 /// ASTContext is destroyed. 3256 // FIXME: We really should have a better mechanism in the ASTContext to 3257 // manage running destructors for types which do variable sized allocation 3258 // within the AST. In some places we thread the AST bump pointer allocator 3259 // into the datastructures which avoids this mess during deallocation but is 3260 // wasteful of memory, and here we require a lot of error prone book keeping 3261 // in order to track and run destructors while we're tearing things down. 3262 using DeallocationFunctionsAndArguments = 3263 llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>; 3264 mutable DeallocationFunctionsAndArguments Deallocations; 3265 3266 // FIXME: This currently contains the set of StoredDeclMaps used 3267 // by DeclContext objects. This probably should not be in ASTContext, 3268 // but we include it here so that ASTContext can quickly deallocate them. 3269 llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM; 3270 3271 std::vector<Decl *> TraversalScope; 3272 3273 std::unique_ptr<VTableContextBase> VTContext; 3274 3275 void ReleaseDeclContextMaps(); 3276 3277 public: 3278 enum PragmaSectionFlag : unsigned { 3279 PSF_None = 0, 3280 PSF_Read = 0x1, 3281 PSF_Write = 0x2, 3282 PSF_Execute = 0x4, 3283 PSF_Implicit = 0x8, 3284 PSF_ZeroInit = 0x10, 3285 PSF_Invalid = 0x80000000U, 3286 }; 3287 3288 struct SectionInfo { 3289 NamedDecl *Decl; 3290 SourceLocation PragmaSectionLocation; 3291 int SectionFlags; 3292 3293 SectionInfo() = default; 3294 SectionInfo(NamedDecl *Decl, SourceLocation PragmaSectionLocation, 3295 int SectionFlags) 3296 : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation), 3297 SectionFlags(SectionFlags) {} 3298 }; 3299 3300 llvm::StringMap<SectionInfo> SectionInfos; 3301 3302 /// Return a new OMPTraitInfo object owned by this context. 3303 OMPTraitInfo &getNewOMPTraitInfo(); 3304 3305 /// Whether a C++ static variable or CUDA/HIP kernel may be externalized. 3306 bool mayExternalize(const Decl *D) const; 3307 3308 /// Whether a C++ static variable or CUDA/HIP kernel should be externalized. 3309 bool shouldExternalize(const Decl *D) const; 3310 3311 StringRef getCUIDHash() const; 3312 3313 private: 3314 /// All OMPTraitInfo objects live in this collection, one per 3315 /// `pragma omp [begin] declare variant` directive. 3316 SmallVector<std::unique_ptr<OMPTraitInfo>, 4> OMPTraitInfoVector; 3317 }; 3318 3319 /// Insertion operator for diagnostics. 3320 const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB, 3321 const ASTContext::SectionInfo &Section); 3322 3323 /// Utility function for constructing a nullary selector. 3324 inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) { 3325 IdentifierInfo* II = &Ctx.Idents.get(name); 3326 return Ctx.Selectors.getSelector(0, &II); 3327 } 3328 3329 /// Utility function for constructing an unary selector. 3330 inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) { 3331 IdentifierInfo* II = &Ctx.Idents.get(name); 3332 return Ctx.Selectors.getSelector(1, &II); 3333 } 3334 3335 } // namespace clang 3336 3337 // operator new and delete aren't allowed inside namespaces. 3338 3339 /// Placement new for using the ASTContext's allocator. 3340 /// 3341 /// This placement form of operator new uses the ASTContext's allocator for 3342 /// obtaining memory. 3343 /// 3344 /// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h! 3345 /// Any changes here need to also be made there. 3346 /// 3347 /// We intentionally avoid using a nothrow specification here so that the calls 3348 /// to this operator will not perform a null check on the result -- the 3349 /// underlying allocator never returns null pointers. 3350 /// 3351 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope): 3352 /// @code 3353 /// // Default alignment (8) 3354 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments); 3355 /// // Specific alignment 3356 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments); 3357 /// @endcode 3358 /// Memory allocated through this placement new operator does not need to be 3359 /// explicitly freed, as ASTContext will free all of this memory when it gets 3360 /// destroyed. Please note that you cannot use delete on the pointer. 3361 /// 3362 /// @param Bytes The number of bytes to allocate. Calculated by the compiler. 3363 /// @param C The ASTContext that provides the allocator. 3364 /// @param Alignment The alignment of the allocated memory (if the underlying 3365 /// allocator supports it). 3366 /// @return The allocated memory. Could be nullptr. 3367 inline void *operator new(size_t Bytes, const clang::ASTContext &C, 3368 size_t Alignment /* = 8 */) { 3369 return C.Allocate(Bytes, Alignment); 3370 } 3371 3372 /// Placement delete companion to the new above. 3373 /// 3374 /// This operator is just a companion to the new above. There is no way of 3375 /// invoking it directly; see the new operator for more details. This operator 3376 /// is called implicitly by the compiler if a placement new expression using 3377 /// the ASTContext throws in the object constructor. 3378 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) { 3379 C.Deallocate(Ptr); 3380 } 3381 3382 /// This placement form of operator new[] uses the ASTContext's allocator for 3383 /// obtaining memory. 3384 /// 3385 /// We intentionally avoid using a nothrow specification here so that the calls 3386 /// to this operator will not perform a null check on the result -- the 3387 /// underlying allocator never returns null pointers. 3388 /// 3389 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope): 3390 /// @code 3391 /// // Default alignment (8) 3392 /// char *data = new (Context) char[10]; 3393 /// // Specific alignment 3394 /// char *data = new (Context, 4) char[10]; 3395 /// @endcode 3396 /// Memory allocated through this placement new[] operator does not need to be 3397 /// explicitly freed, as ASTContext will free all of this memory when it gets 3398 /// destroyed. Please note that you cannot use delete on the pointer. 3399 /// 3400 /// @param Bytes The number of bytes to allocate. Calculated by the compiler. 3401 /// @param C The ASTContext that provides the allocator. 3402 /// @param Alignment The alignment of the allocated memory (if the underlying 3403 /// allocator supports it). 3404 /// @return The allocated memory. Could be nullptr. 3405 inline void *operator new[](size_t Bytes, const clang::ASTContext& C, 3406 size_t Alignment /* = 8 */) { 3407 return C.Allocate(Bytes, Alignment); 3408 } 3409 3410 /// Placement delete[] companion to the new[] above. 3411 /// 3412 /// This operator is just a companion to the new[] above. There is no way of 3413 /// invoking it directly; see the new[] operator for more details. This operator 3414 /// is called implicitly by the compiler if a placement new[] expression using 3415 /// the ASTContext throws in the object constructor. 3416 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) { 3417 C.Deallocate(Ptr); 3418 } 3419 3420 /// Create the representation of a LazyGenerationalUpdatePtr. 3421 template <typename Owner, typename T, 3422 void (clang::ExternalASTSource::*Update)(Owner)> 3423 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType 3424 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue( 3425 const clang::ASTContext &Ctx, T Value) { 3426 // Note, this is implemented here so that ExternalASTSource.h doesn't need to 3427 // include ASTContext.h. We explicitly instantiate it for all relevant types 3428 // in ASTContext.cpp. 3429 if (auto *Source = Ctx.getExternalSource()) 3430 return new (Ctx) LazyData(Source, Value); 3431 return Value; 3432 } 3433 3434 #endif // LLVM_CLANG_AST_ASTCONTEXT_H 3435