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 UnresolvedSetIterator; 134 class UsingShadowDecl; 135 class VarTemplateDecl; 136 class VTableContextBase; 137 struct BlockVarCopyInit; 138 139 namespace Builtin { 140 141 class Context; 142 143 } // namespace Builtin 144 145 enum BuiltinTemplateKind : int; 146 enum OpenCLTypeKind : uint8_t; 147 148 namespace comments { 149 150 class FullComment; 151 152 } // namespace comments 153 154 namespace interp { 155 156 class Context; 157 158 } // namespace interp 159 160 namespace serialization { 161 template <class> class AbstractTypeReader; 162 } // namespace serialization 163 164 enum class AlignRequirementKind { 165 /// The alignment was not explicit in code. 166 None, 167 168 /// The alignment comes from an alignment attribute on a typedef. 169 RequiredByTypedef, 170 171 /// The alignment comes from an alignment attribute on a record type. 172 RequiredByRecord, 173 174 /// The alignment comes from an alignment attribute on a enum type. 175 RequiredByEnum, 176 }; 177 178 struct TypeInfo { 179 uint64_t Width = 0; 180 unsigned Align = 0; 181 AlignRequirementKind AlignRequirement; 182 183 TypeInfo() : AlignRequirement(AlignRequirementKind::None) {} 184 TypeInfo(uint64_t Width, unsigned Align, 185 AlignRequirementKind AlignRequirement) 186 : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {} 187 bool isAlignRequired() { 188 return AlignRequirement != AlignRequirementKind::None; 189 } 190 }; 191 192 struct TypeInfoChars { 193 CharUnits Width; 194 CharUnits Align; 195 AlignRequirementKind AlignRequirement; 196 197 TypeInfoChars() : AlignRequirement(AlignRequirementKind::None) {} 198 TypeInfoChars(CharUnits Width, CharUnits Align, 199 AlignRequirementKind AlignRequirement) 200 : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {} 201 bool isAlignRequired() { 202 return AlignRequirement != AlignRequirementKind::None; 203 } 204 }; 205 206 /// Holds long-lived AST nodes (such as types and decls) that can be 207 /// referred to throughout the semantic analysis of a file. 208 class ASTContext : public RefCountedBase<ASTContext> { 209 friend class NestedNameSpecifier; 210 211 mutable SmallVector<Type *, 0> Types; 212 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes; 213 mutable llvm::FoldingSet<ComplexType> ComplexTypes; 214 mutable llvm::FoldingSet<PointerType> PointerTypes{GeneralTypesLog2InitSize}; 215 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes; 216 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes; 217 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes; 218 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes; 219 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes; 220 mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &> 221 ConstantArrayTypes; 222 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes; 223 mutable std::vector<VariableArrayType*> VariableArrayTypes; 224 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes; 225 mutable llvm::FoldingSet<DependentSizedExtVectorType> 226 DependentSizedExtVectorTypes; 227 mutable llvm::FoldingSet<DependentAddressSpaceType> 228 DependentAddressSpaceTypes; 229 mutable llvm::FoldingSet<VectorType> VectorTypes; 230 mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes; 231 mutable llvm::FoldingSet<ConstantMatrixType> MatrixTypes; 232 mutable llvm::FoldingSet<DependentSizedMatrixType> DependentSizedMatrixTypes; 233 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes; 234 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&> 235 FunctionProtoTypes; 236 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes; 237 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes; 238 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes; 239 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes; 240 mutable llvm::FoldingSet<SubstTemplateTypeParmType> 241 SubstTemplateTypeParmTypes; 242 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType> 243 SubstTemplateTypeParmPackTypes; 244 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&> 245 TemplateSpecializationTypes; 246 mutable llvm::FoldingSet<ParenType> ParenTypes{GeneralTypesLog2InitSize}; 247 mutable llvm::FoldingSet<UsingType> UsingTypes; 248 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes{ 249 GeneralTypesLog2InitSize}; 250 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes; 251 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType, 252 ASTContext&> 253 DependentTemplateSpecializationTypes; 254 llvm::FoldingSet<PackExpansionType> PackExpansionTypes; 255 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes; 256 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes; 257 mutable llvm::FoldingSet<DependentUnaryTransformType> 258 DependentUnaryTransformTypes; 259 mutable llvm::ContextualFoldingSet<AutoType, ASTContext&> AutoTypes; 260 mutable llvm::FoldingSet<DeducedTemplateSpecializationType> 261 DeducedTemplateSpecializationTypes; 262 mutable llvm::FoldingSet<AtomicType> AtomicTypes; 263 llvm::FoldingSet<AttributedType> AttributedTypes; 264 mutable llvm::FoldingSet<PipeType> PipeTypes; 265 mutable llvm::FoldingSet<BitIntType> BitIntTypes; 266 mutable llvm::FoldingSet<DependentBitIntType> DependentBitIntTypes; 267 llvm::FoldingSet<BTFTagAttributedType> BTFTagAttributedTypes; 268 269 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames; 270 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames; 271 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage> 272 SubstTemplateTemplateParms; 273 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage, 274 ASTContext&> 275 SubstTemplateTemplateParmPacks; 276 277 /// The set of nested name specifiers. 278 /// 279 /// This set is managed by the NestedNameSpecifier class. 280 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers; 281 mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr; 282 283 /// A cache mapping from RecordDecls to ASTRecordLayouts. 284 /// 285 /// This is lazily created. This is intentionally not serialized. 286 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*> 287 ASTRecordLayouts; 288 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*> 289 ObjCLayouts; 290 291 /// A cache from types to size and alignment information. 292 using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>; 293 mutable TypeInfoMap MemoizedTypeInfo; 294 295 /// A cache from types to unadjusted alignment information. Only ARM and 296 /// AArch64 targets need this information, keeping it separate prevents 297 /// imposing overhead on TypeInfo size. 298 using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>; 299 mutable UnadjustedAlignMap MemoizedUnadjustedAlign; 300 301 /// A cache mapping from CXXRecordDecls to key functions. 302 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions; 303 304 /// Mapping from ObjCContainers to their ObjCImplementations. 305 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls; 306 307 /// Mapping from ObjCMethod to its duplicate declaration in the same 308 /// interface. 309 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls; 310 311 /// Mapping from __block VarDecls to BlockVarCopyInit. 312 llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits; 313 314 /// Mapping from GUIDs to the corresponding MSGuidDecl. 315 mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls; 316 317 /// Mapping from APValues to the corresponding UnnamedGlobalConstantDecl. 318 mutable llvm::FoldingSet<UnnamedGlobalConstantDecl> 319 UnnamedGlobalConstantDecls; 320 321 /// Mapping from APValues to the corresponding TemplateParamObjects. 322 mutable llvm::FoldingSet<TemplateParamObjectDecl> TemplateParamObjectDecls; 323 324 /// A cache mapping a string value to a StringLiteral object with the same 325 /// value. 326 /// 327 /// This is lazily created. This is intentionally not serialized. 328 mutable llvm::StringMap<StringLiteral *> StringLiteralCache; 329 330 /// MD5 hash of CUID. It is calculated when first used and cached by this 331 /// data member. 332 mutable std::string CUIDHash; 333 334 /// Representation of a "canonical" template template parameter that 335 /// is used in canonical template names. 336 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode { 337 TemplateTemplateParmDecl *Parm; 338 339 public: 340 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm) 341 : Parm(Parm) {} 342 343 TemplateTemplateParmDecl *getParam() const { return Parm; } 344 345 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) { 346 Profile(ID, C, Parm); 347 } 348 349 static void Profile(llvm::FoldingSetNodeID &ID, 350 const ASTContext &C, 351 TemplateTemplateParmDecl *Parm); 352 }; 353 mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm, 354 const ASTContext&> 355 CanonTemplateTemplateParms; 356 357 TemplateTemplateParmDecl * 358 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const; 359 360 /// The typedef for the __int128_t type. 361 mutable TypedefDecl *Int128Decl = nullptr; 362 363 /// The typedef for the __uint128_t type. 364 mutable TypedefDecl *UInt128Decl = nullptr; 365 366 /// The typedef for the target specific predefined 367 /// __builtin_va_list type. 368 mutable TypedefDecl *BuiltinVaListDecl = nullptr; 369 370 /// The typedef for the predefined \c __builtin_ms_va_list type. 371 mutable TypedefDecl *BuiltinMSVaListDecl = nullptr; 372 373 /// The typedef for the predefined \c id type. 374 mutable TypedefDecl *ObjCIdDecl = nullptr; 375 376 /// The typedef for the predefined \c SEL type. 377 mutable TypedefDecl *ObjCSelDecl = nullptr; 378 379 /// The typedef for the predefined \c Class type. 380 mutable TypedefDecl *ObjCClassDecl = nullptr; 381 382 /// The typedef for the predefined \c Protocol class in Objective-C. 383 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr; 384 385 /// The typedef for the predefined 'BOOL' type. 386 mutable TypedefDecl *BOOLDecl = nullptr; 387 388 // Typedefs which may be provided defining the structure of Objective-C 389 // pseudo-builtins 390 QualType ObjCIdRedefinitionType; 391 QualType ObjCClassRedefinitionType; 392 QualType ObjCSelRedefinitionType; 393 394 /// The identifier 'bool'. 395 mutable IdentifierInfo *BoolName = nullptr; 396 397 /// The identifier 'NSObject'. 398 mutable IdentifierInfo *NSObjectName = nullptr; 399 400 /// The identifier 'NSCopying'. 401 IdentifierInfo *NSCopyingName = nullptr; 402 403 /// The identifier '__make_integer_seq'. 404 mutable IdentifierInfo *MakeIntegerSeqName = nullptr; 405 406 /// The identifier '__type_pack_element'. 407 mutable IdentifierInfo *TypePackElementName = nullptr; 408 409 QualType ObjCConstantStringType; 410 mutable RecordDecl *CFConstantStringTagDecl = nullptr; 411 mutable TypedefDecl *CFConstantStringTypeDecl = nullptr; 412 413 mutable QualType ObjCSuperType; 414 415 QualType ObjCNSStringType; 416 417 /// The typedef declaration for the Objective-C "instancetype" type. 418 TypedefDecl *ObjCInstanceTypeDecl = nullptr; 419 420 /// The type for the C FILE type. 421 TypeDecl *FILEDecl = nullptr; 422 423 /// The type for the C jmp_buf type. 424 TypeDecl *jmp_bufDecl = nullptr; 425 426 /// The type for the C sigjmp_buf type. 427 TypeDecl *sigjmp_bufDecl = nullptr; 428 429 /// The type for the C ucontext_t type. 430 TypeDecl *ucontext_tDecl = nullptr; 431 432 /// Type for the Block descriptor for Blocks CodeGen. 433 /// 434 /// Since this is only used for generation of debug info, it is not 435 /// serialized. 436 mutable RecordDecl *BlockDescriptorType = nullptr; 437 438 /// Type for the Block descriptor for Blocks CodeGen. 439 /// 440 /// Since this is only used for generation of debug info, it is not 441 /// serialized. 442 mutable RecordDecl *BlockDescriptorExtendedType = nullptr; 443 444 /// Declaration for the CUDA cudaConfigureCall function. 445 FunctionDecl *cudaConfigureCallDecl = nullptr; 446 447 /// Keeps track of all declaration attributes. 448 /// 449 /// Since so few decls have attrs, we keep them in a hash map instead of 450 /// wasting space in the Decl class. 451 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs; 452 453 /// A mapping from non-redeclarable declarations in modules that were 454 /// merged with other declarations to the canonical declaration that they were 455 /// merged into. 456 llvm::DenseMap<Decl*, Decl*> MergedDecls; 457 458 /// A mapping from a defining declaration to a list of modules (other 459 /// than the owning module of the declaration) that contain merged 460 /// definitions of that entity. 461 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules; 462 463 /// Initializers for a module, in order. Each Decl will be either 464 /// something that has a semantic effect on startup (such as a variable with 465 /// a non-constant initializer), or an ImportDecl (which recursively triggers 466 /// initialization of another module). 467 struct PerModuleInitializers { 468 llvm::SmallVector<Decl*, 4> Initializers; 469 llvm::SmallVector<uint32_t, 4> LazyInitializers; 470 471 void resolve(ASTContext &Ctx); 472 }; 473 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers; 474 475 static constexpr unsigned ConstantArrayTypesLog2InitSize = 8; 476 static constexpr unsigned GeneralTypesLog2InitSize = 9; 477 static constexpr unsigned FunctionProtoTypesLog2InitSize = 12; 478 479 ASTContext &this_() { return *this; } 480 481 public: 482 /// A type synonym for the TemplateOrInstantiation mapping. 483 using TemplateOrSpecializationInfo = 484 llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>; 485 486 private: 487 friend class ASTDeclReader; 488 friend class ASTReader; 489 friend class ASTWriter; 490 template <class> friend class serialization::AbstractTypeReader; 491 friend class CXXRecordDecl; 492 friend class IncrementalParser; 493 494 /// A mapping to contain the template or declaration that 495 /// a variable declaration describes or was instantiated from, 496 /// respectively. 497 /// 498 /// For non-templates, this value will be NULL. For variable 499 /// declarations that describe a variable template, this will be a 500 /// pointer to a VarTemplateDecl. For static data members 501 /// of class template specializations, this will be the 502 /// MemberSpecializationInfo referring to the member variable that was 503 /// instantiated or specialized. Thus, the mapping will keep track of 504 /// the static data member templates from which static data members of 505 /// class template specializations were instantiated. 506 /// 507 /// Given the following example: 508 /// 509 /// \code 510 /// template<typename T> 511 /// struct X { 512 /// static T value; 513 /// }; 514 /// 515 /// template<typename T> 516 /// T X<T>::value = T(17); 517 /// 518 /// int *x = &X<int>::value; 519 /// \endcode 520 /// 521 /// This mapping will contain an entry that maps from the VarDecl for 522 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the 523 /// class template X) and will be marked TSK_ImplicitInstantiation. 524 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo> 525 TemplateOrInstantiation; 526 527 /// Keeps track of the declaration from which a using declaration was 528 /// created during instantiation. 529 /// 530 /// The source and target declarations are always a UsingDecl, an 531 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl. 532 /// 533 /// For example: 534 /// \code 535 /// template<typename T> 536 /// struct A { 537 /// void f(); 538 /// }; 539 /// 540 /// template<typename T> 541 /// struct B : A<T> { 542 /// using A<T>::f; 543 /// }; 544 /// 545 /// template struct B<int>; 546 /// \endcode 547 /// 548 /// This mapping will contain an entry that maps from the UsingDecl in 549 /// B<int> to the UnresolvedUsingDecl in B<T>. 550 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl; 551 552 /// Like InstantiatedFromUsingDecl, but for using-enum-declarations. Maps 553 /// from the instantiated using-enum to the templated decl from whence it 554 /// came. 555 /// Note that using-enum-declarations cannot be dependent and 556 /// thus will never be instantiated from an "unresolved" 557 /// version thereof (as with using-declarations), so each mapping is from 558 /// a (resolved) UsingEnumDecl to a (resolved) UsingEnumDecl. 559 llvm::DenseMap<UsingEnumDecl *, UsingEnumDecl *> 560 InstantiatedFromUsingEnumDecl; 561 562 /// Simlarly maps instantiated UsingShadowDecls to their origin. 563 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*> 564 InstantiatedFromUsingShadowDecl; 565 566 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl; 567 568 /// Mapping that stores the methods overridden by a given C++ 569 /// member function. 570 /// 571 /// Since most C++ member functions aren't virtual and therefore 572 /// don't override anything, we store the overridden functions in 573 /// this map on the side rather than within the CXXMethodDecl structure. 574 using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>; 575 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods; 576 577 /// Mapping from each declaration context to its corresponding 578 /// mangling numbering context (used for constructs like lambdas which 579 /// need to be consistently numbered for the mangler). 580 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>> 581 MangleNumberingContexts; 582 llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>> 583 ExtraMangleNumberingContexts; 584 585 /// Side-table of mangling numbers for declarations which rarely 586 /// need them (like static local vars). 587 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers; 588 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers; 589 /// Mapping the associated device lambda mangling number if present. 590 mutable llvm::DenseMap<const CXXRecordDecl *, unsigned> 591 DeviceLambdaManglingNumbers; 592 593 /// Mapping that stores parameterIndex values for ParmVarDecls when 594 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex. 595 using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>; 596 ParameterIndexTable ParamIndices; 597 598 ImportDecl *FirstLocalImport = nullptr; 599 ImportDecl *LastLocalImport = nullptr; 600 601 TranslationUnitDecl *TUDecl = nullptr; 602 mutable ExternCContextDecl *ExternCContext = nullptr; 603 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr; 604 mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr; 605 606 /// The associated SourceManager object. 607 SourceManager &SourceMgr; 608 609 /// The language options used to create the AST associated with 610 /// this ASTContext object. 611 LangOptions &LangOpts; 612 613 /// NoSanitizeList object that is used by sanitizers to decide which 614 /// entities should not be instrumented. 615 std::unique_ptr<NoSanitizeList> NoSanitizeL; 616 617 /// Function filtering mechanism to determine whether a given function 618 /// should be imbued with the XRay "always" or "never" attributes. 619 std::unique_ptr<XRayFunctionFilter> XRayFilter; 620 621 /// ProfileList object that is used by the profile instrumentation 622 /// to decide which entities should be instrumented. 623 std::unique_ptr<ProfileList> ProfList; 624 625 /// The allocator used to create AST objects. 626 /// 627 /// AST objects are never destructed; rather, all memory associated with the 628 /// AST objects will be released when the ASTContext itself is destroyed. 629 mutable llvm::BumpPtrAllocator BumpAlloc; 630 631 /// Allocator for partial diagnostics. 632 PartialDiagnostic::DiagStorageAllocator DiagAllocator; 633 634 /// The current C++ ABI. 635 std::unique_ptr<CXXABI> ABI; 636 CXXABI *createCXXABI(const TargetInfo &T); 637 638 /// The logical -> physical address space map. 639 const LangASMap *AddrSpaceMap = nullptr; 640 641 /// Address space map mangling must be used with language specific 642 /// address spaces (e.g. OpenCL/CUDA) 643 bool AddrSpaceMapMangling; 644 645 const TargetInfo *Target = nullptr; 646 const TargetInfo *AuxTarget = nullptr; 647 clang::PrintingPolicy PrintingPolicy; 648 std::unique_ptr<interp::Context> InterpContext; 649 std::unique_ptr<ParentMapContext> ParentMapCtx; 650 651 /// Keeps track of the deallocated DeclListNodes for future reuse. 652 DeclListNode *ListNodeFreeList = nullptr; 653 654 public: 655 IdentifierTable &Idents; 656 SelectorTable &Selectors; 657 Builtin::Context &BuiltinInfo; 658 const TranslationUnitKind TUKind; 659 mutable DeclarationNameTable DeclarationNames; 660 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource; 661 ASTMutationListener *Listener = nullptr; 662 663 /// Returns the clang bytecode interpreter context. 664 interp::Context &getInterpContext(); 665 666 struct CUDAConstantEvalContext { 667 /// Do not allow wrong-sided variables in constant expressions. 668 bool NoWrongSidedVars = false; 669 } CUDAConstantEvalCtx; 670 struct CUDAConstantEvalContextRAII { 671 ASTContext &Ctx; 672 CUDAConstantEvalContext SavedCtx; 673 CUDAConstantEvalContextRAII(ASTContext &Ctx_, bool NoWrongSidedVars) 674 : Ctx(Ctx_), SavedCtx(Ctx_.CUDAConstantEvalCtx) { 675 Ctx_.CUDAConstantEvalCtx.NoWrongSidedVars = NoWrongSidedVars; 676 } 677 ~CUDAConstantEvalContextRAII() { Ctx.CUDAConstantEvalCtx = SavedCtx; } 678 }; 679 680 /// Returns the dynamic AST node parent map context. 681 ParentMapContext &getParentMapContext(); 682 683 // A traversal scope limits the parts of the AST visible to certain analyses. 684 // RecursiveASTVisitor only visits specified children of TranslationUnitDecl. 685 // getParents() will only observe reachable parent edges. 686 // 687 // The scope is defined by a set of "top-level" declarations which will be 688 // visible under the TranslationUnitDecl. 689 // Initially, it is the entire TU, represented by {getTranslationUnitDecl()}. 690 // 691 // After setTraversalScope({foo, bar}), the exposed AST looks like: 692 // TranslationUnitDecl 693 // - foo 694 // - ... 695 // - bar 696 // - ... 697 // All other siblings of foo and bar are pruned from the tree. 698 // (However they are still accessible via TranslationUnitDecl->decls()) 699 // 700 // Changing the scope clears the parent cache, which is expensive to rebuild. 701 std::vector<Decl *> getTraversalScope() const { return TraversalScope; } 702 void setTraversalScope(const std::vector<Decl *> &); 703 704 /// Forwards to get node parents from the ParentMapContext. New callers should 705 /// use ParentMapContext::getParents() directly. 706 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node); 707 708 const clang::PrintingPolicy &getPrintingPolicy() const { 709 return PrintingPolicy; 710 } 711 712 void setPrintingPolicy(const clang::PrintingPolicy &Policy) { 713 PrintingPolicy = Policy; 714 } 715 716 SourceManager& getSourceManager() { return SourceMgr; } 717 const SourceManager& getSourceManager() const { return SourceMgr; } 718 719 // Cleans up some of the data structures. This allows us to do cleanup 720 // normally done in the destructor earlier. Renders much of the ASTContext 721 // unusable, mostly the actual AST nodes, so should be called when we no 722 // longer need access to the AST. 723 void cleanup(); 724 725 llvm::BumpPtrAllocator &getAllocator() const { 726 return BumpAlloc; 727 } 728 729 void *Allocate(size_t Size, unsigned Align = 8) const { 730 return BumpAlloc.Allocate(Size, Align); 731 } 732 template <typename T> T *Allocate(size_t Num = 1) const { 733 return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T))); 734 } 735 void Deallocate(void *Ptr) const {} 736 737 /// Allocates a \c DeclListNode or returns one from the \c ListNodeFreeList 738 /// pool. 739 DeclListNode *AllocateDeclListNode(clang::NamedDecl *ND) { 740 if (DeclListNode *Alloc = ListNodeFreeList) { 741 ListNodeFreeList = Alloc->Rest.dyn_cast<DeclListNode*>(); 742 Alloc->D = ND; 743 Alloc->Rest = nullptr; 744 return Alloc; 745 } 746 return new (*this) DeclListNode(ND); 747 } 748 /// Deallcates a \c DeclListNode by returning it to the \c ListNodeFreeList 749 /// pool. 750 void DeallocateDeclListNode(DeclListNode *N) { 751 N->Rest = ListNodeFreeList; 752 ListNodeFreeList = N; 753 } 754 755 /// Return the total amount of physical memory allocated for representing 756 /// AST nodes and type information. 757 size_t getASTAllocatedMemory() const { 758 return BumpAlloc.getTotalMemory(); 759 } 760 761 /// Return the total memory used for various side tables. 762 size_t getSideTableAllocatedMemory() const; 763 764 PartialDiagnostic::DiagStorageAllocator &getDiagAllocator() { 765 return DiagAllocator; 766 } 767 768 const TargetInfo &getTargetInfo() const { return *Target; } 769 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; } 770 771 /// getIntTypeForBitwidth - 772 /// sets integer QualTy according to specified details: 773 /// bitwidth, signed/unsigned. 774 /// Returns empty type if there is no appropriate target types. 775 QualType getIntTypeForBitwidth(unsigned DestWidth, 776 unsigned Signed) const; 777 778 /// getRealTypeForBitwidth - 779 /// sets floating point QualTy according to specified bitwidth. 780 /// Returns empty type if there is no appropriate target types. 781 QualType getRealTypeForBitwidth(unsigned DestWidth, 782 FloatModeKind ExplicitType) const; 783 784 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const; 785 786 const LangOptions& getLangOpts() const { return LangOpts; } 787 788 // If this condition is false, typo correction must be performed eagerly 789 // rather than delayed in many places, as it makes use of dependent types. 790 // the condition is false for clang's C-only codepath, as it doesn't support 791 // dependent types yet. 792 bool isDependenceAllowed() const { 793 return LangOpts.CPlusPlus || LangOpts.RecoveryAST; 794 } 795 796 const NoSanitizeList &getNoSanitizeList() const { return *NoSanitizeL; } 797 798 const XRayFunctionFilter &getXRayFilter() const { 799 return *XRayFilter; 800 } 801 802 const ProfileList &getProfileList() const { return *ProfList; } 803 804 DiagnosticsEngine &getDiagnostics() const; 805 806 FullSourceLoc getFullLoc(SourceLocation Loc) const { 807 return FullSourceLoc(Loc,SourceMgr); 808 } 809 810 /// Return the C++ ABI kind that should be used. The C++ ABI can be overriden 811 /// at compile time with `-fc++-abi=`. If this is not provided, we instead use 812 /// the default ABI set by the target. 813 TargetCXXABI::Kind getCXXABIKind() const; 814 815 /// All comments in this translation unit. 816 RawCommentList Comments; 817 818 /// True if comments are already loaded from ExternalASTSource. 819 mutable bool CommentsLoaded = false; 820 821 /// Mapping from declaration to directly attached comment. 822 /// 823 /// Raw comments are owned by Comments list. This mapping is populated 824 /// lazily. 825 mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments; 826 827 /// Mapping from canonical declaration to the first redeclaration in chain 828 /// that has a comment attached. 829 /// 830 /// Raw comments are owned by Comments list. This mapping is populated 831 /// lazily. 832 mutable llvm::DenseMap<const Decl *, const Decl *> RedeclChainComments; 833 834 /// Keeps track of redeclaration chains that don't have any comment attached. 835 /// Mapping from canonical declaration to redeclaration chain that has no 836 /// comments attached to any redeclaration. Specifically it's mapping to 837 /// the last redeclaration we've checked. 838 /// 839 /// Shall not contain declarations that have comments attached to any 840 /// redeclaration in their chain. 841 mutable llvm::DenseMap<const Decl *, const Decl *> CommentlessRedeclChains; 842 843 /// Mapping from declarations to parsed comments attached to any 844 /// redeclaration. 845 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments; 846 847 /// Attaches \p Comment to \p OriginalD and to its redeclaration chain 848 /// and removes the redeclaration chain from the set of commentless chains. 849 /// 850 /// Don't do anything if a comment has already been attached to \p OriginalD 851 /// or its redeclaration chain. 852 void cacheRawCommentForDecl(const Decl &OriginalD, 853 const RawComment &Comment) const; 854 855 /// \returns searches \p CommentsInFile for doc comment for \p D. 856 /// 857 /// \p RepresentativeLocForDecl is used as a location for searching doc 858 /// comments. \p CommentsInFile is a mapping offset -> comment of files in the 859 /// same file where \p RepresentativeLocForDecl is. 860 RawComment *getRawCommentForDeclNoCacheImpl( 861 const Decl *D, const SourceLocation RepresentativeLocForDecl, 862 const std::map<unsigned, RawComment *> &CommentsInFile) const; 863 864 /// Return the documentation comment attached to a given declaration, 865 /// without looking into cache. 866 RawComment *getRawCommentForDeclNoCache(const Decl *D) const; 867 868 public: 869 void addComment(const RawComment &RC); 870 871 /// Return the documentation comment attached to a given declaration. 872 /// Returns nullptr if no comment is attached. 873 /// 874 /// \param OriginalDecl if not nullptr, is set to declaration AST node that 875 /// had the comment, if the comment we found comes from a redeclaration. 876 const RawComment * 877 getRawCommentForAnyRedecl(const Decl *D, 878 const Decl **OriginalDecl = nullptr) const; 879 880 /// Searches existing comments for doc comments that should be attached to \p 881 /// Decls. If any doc comment is found, it is parsed. 882 /// 883 /// Requirement: All \p Decls are in the same file. 884 /// 885 /// If the last comment in the file is already attached we assume 886 /// there are not comments left to be attached to \p Decls. 887 void attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, 888 const Preprocessor *PP); 889 890 /// Return parsed documentation comment attached to a given declaration. 891 /// Returns nullptr if no comment is attached. 892 /// 893 /// \param PP the Preprocessor used with this TU. Could be nullptr if 894 /// preprocessor is not available. 895 comments::FullComment *getCommentForDecl(const Decl *D, 896 const Preprocessor *PP) const; 897 898 /// Return parsed documentation comment attached to a given declaration. 899 /// Returns nullptr if no comment is attached. Does not look at any 900 /// redeclarations of the declaration. 901 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const; 902 903 comments::FullComment *cloneFullComment(comments::FullComment *FC, 904 const Decl *D) const; 905 906 private: 907 mutable comments::CommandTraits CommentCommandTraits; 908 909 /// Iterator that visits import declarations. 910 class import_iterator { 911 ImportDecl *Import = nullptr; 912 913 public: 914 using value_type = ImportDecl *; 915 using reference = ImportDecl *; 916 using pointer = ImportDecl *; 917 using difference_type = int; 918 using iterator_category = std::forward_iterator_tag; 919 920 import_iterator() = default; 921 explicit import_iterator(ImportDecl *Import) : Import(Import) {} 922 923 reference operator*() const { return Import; } 924 pointer operator->() const { return Import; } 925 926 import_iterator &operator++() { 927 Import = ASTContext::getNextLocalImport(Import); 928 return *this; 929 } 930 931 import_iterator operator++(int) { 932 import_iterator Other(*this); 933 ++(*this); 934 return Other; 935 } 936 937 friend bool operator==(import_iterator X, import_iterator Y) { 938 return X.Import == Y.Import; 939 } 940 941 friend bool operator!=(import_iterator X, import_iterator Y) { 942 return X.Import != Y.Import; 943 } 944 }; 945 946 public: 947 comments::CommandTraits &getCommentCommandTraits() const { 948 return CommentCommandTraits; 949 } 950 951 /// Retrieve the attributes for the given declaration. 952 AttrVec& getDeclAttrs(const Decl *D); 953 954 /// Erase the attributes corresponding to the given declaration. 955 void eraseDeclAttrs(const Decl *D); 956 957 /// If this variable is an instantiated static data member of a 958 /// class template specialization, returns the templated static data member 959 /// from which it was instantiated. 960 // FIXME: Remove ? 961 MemberSpecializationInfo *getInstantiatedFromStaticDataMember( 962 const VarDecl *Var); 963 964 /// Note that the static data member \p Inst is an instantiation of 965 /// the static data member template \p Tmpl of a class template. 966 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 967 TemplateSpecializationKind TSK, 968 SourceLocation PointOfInstantiation = SourceLocation()); 969 970 TemplateOrSpecializationInfo 971 getTemplateOrSpecializationInfo(const VarDecl *Var); 972 973 void setTemplateOrSpecializationInfo(VarDecl *Inst, 974 TemplateOrSpecializationInfo TSI); 975 976 /// If the given using decl \p Inst is an instantiation of 977 /// another (possibly unresolved) using decl, return it. 978 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst); 979 980 /// Remember that the using decl \p Inst is an instantiation 981 /// of the using decl \p Pattern of a class template. 982 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern); 983 984 /// If the given using-enum decl \p Inst is an instantiation of 985 /// another using-enum decl, return it. 986 UsingEnumDecl *getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst); 987 988 /// Remember that the using enum decl \p Inst is an instantiation 989 /// of the using enum decl \p Pattern of a class template. 990 void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, 991 UsingEnumDecl *Pattern); 992 993 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst); 994 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 995 UsingShadowDecl *Pattern); 996 997 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field); 998 999 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl); 1000 1001 // Access to the set of methods overridden by the given C++ method. 1002 using overridden_cxx_method_iterator = CXXMethodVector::const_iterator; 1003 overridden_cxx_method_iterator 1004 overridden_methods_begin(const CXXMethodDecl *Method) const; 1005 1006 overridden_cxx_method_iterator 1007 overridden_methods_end(const CXXMethodDecl *Method) const; 1008 1009 unsigned overridden_methods_size(const CXXMethodDecl *Method) const; 1010 1011 using overridden_method_range = 1012 llvm::iterator_range<overridden_cxx_method_iterator>; 1013 1014 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const; 1015 1016 /// Note that the given C++ \p Method overrides the given \p 1017 /// Overridden method. 1018 void addOverriddenMethod(const CXXMethodDecl *Method, 1019 const CXXMethodDecl *Overridden); 1020 1021 /// Return C++ or ObjC overridden methods for the given \p Method. 1022 /// 1023 /// An ObjC method is considered to override any method in the class's 1024 /// base classes, its protocols, or its categories' protocols, that has 1025 /// the same selector and is of the same kind (class or instance). 1026 /// A method in an implementation is not considered as overriding the same 1027 /// method in the interface or its categories. 1028 void getOverriddenMethods( 1029 const NamedDecl *Method, 1030 SmallVectorImpl<const NamedDecl *> &Overridden) const; 1031 1032 /// Notify the AST context that a new import declaration has been 1033 /// parsed or implicitly created within this translation unit. 1034 void addedLocalImportDecl(ImportDecl *Import); 1035 1036 static ImportDecl *getNextLocalImport(ImportDecl *Import) { 1037 return Import->getNextLocalImport(); 1038 } 1039 1040 using import_range = llvm::iterator_range<import_iterator>; 1041 1042 import_range local_imports() const { 1043 return import_range(import_iterator(FirstLocalImport), import_iterator()); 1044 } 1045 1046 Decl *getPrimaryMergedDecl(Decl *D) { 1047 Decl *Result = MergedDecls.lookup(D); 1048 return Result ? Result : D; 1049 } 1050 void setPrimaryMergedDecl(Decl *D, Decl *Primary) { 1051 MergedDecls[D] = Primary; 1052 } 1053 1054 /// Note that the definition \p ND has been merged into module \p M, 1055 /// and should be visible whenever \p M is visible. 1056 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, 1057 bool NotifyListeners = true); 1058 1059 /// Clean up the merged definition list. Call this if you might have 1060 /// added duplicates into the list. 1061 void deduplicateMergedDefinitonsFor(NamedDecl *ND); 1062 1063 /// Get the additional modules in which the definition \p Def has 1064 /// been merged. 1065 ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def); 1066 1067 /// Add a declaration to the list of declarations that are initialized 1068 /// for a module. This will typically be a global variable (with internal 1069 /// linkage) that runs module initializers, such as the iostream initializer, 1070 /// or an ImportDecl nominating another module that has initializers. 1071 void addModuleInitializer(Module *M, Decl *Init); 1072 1073 void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs); 1074 1075 /// Get the initializations to perform when importing a module, if any. 1076 ArrayRef<Decl*> getModuleInitializers(Module *M); 1077 1078 TranslationUnitDecl *getTranslationUnitDecl() const { 1079 return TUDecl->getMostRecentDecl(); 1080 } 1081 void addTranslationUnitDecl() { 1082 assert(!TUDecl || TUKind == TU_Incremental); 1083 TranslationUnitDecl *NewTUDecl = TranslationUnitDecl::Create(*this); 1084 if (TraversalScope.empty() || TraversalScope.back() == TUDecl) 1085 TraversalScope = {NewTUDecl}; 1086 if (TUDecl) 1087 NewTUDecl->setPreviousDecl(TUDecl); 1088 TUDecl = NewTUDecl; 1089 } 1090 1091 ExternCContextDecl *getExternCContextDecl() const; 1092 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const; 1093 BuiltinTemplateDecl *getTypePackElementDecl() const; 1094 1095 // Builtin Types. 1096 CanQualType VoidTy; 1097 CanQualType BoolTy; 1098 CanQualType CharTy; 1099 CanQualType WCharTy; // [C++ 3.9.1p5]. 1100 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99. 1101 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions. 1102 CanQualType Char8Ty; // [C++20 proposal] 1103 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99. 1104 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99. 1105 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty; 1106 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy; 1107 CanQualType UnsignedLongLongTy, UnsignedInt128Ty; 1108 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty, Ibm128Ty; 1109 CanQualType ShortAccumTy, AccumTy, 1110 LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension 1111 CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy; 1112 CanQualType ShortFractTy, FractTy, LongFractTy; 1113 CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy; 1114 CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy; 1115 CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy, 1116 SatUnsignedLongAccumTy; 1117 CanQualType SatShortFractTy, SatFractTy, SatLongFractTy; 1118 CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy, 1119 SatUnsignedLongFractTy; 1120 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON 1121 CanQualType BFloat16Ty; 1122 CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3 1123 CanQualType VoidPtrTy, NullPtrTy; 1124 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy; 1125 CanQualType BuiltinFnTy; 1126 CanQualType PseudoObjectTy, ARCUnbridgedCastTy; 1127 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy; 1128 CanQualType ObjCBuiltinBoolTy; 1129 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1130 CanQualType SingletonId; 1131 #include "clang/Basic/OpenCLImageTypes.def" 1132 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy; 1133 CanQualType OCLQueueTy, OCLReserveIDTy; 1134 CanQualType IncompleteMatrixIdxTy; 1135 CanQualType OMPArraySectionTy, OMPArrayShapingTy, OMPIteratorTy; 1136 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1137 CanQualType Id##Ty; 1138 #include "clang/Basic/OpenCLExtensionTypes.def" 1139 #define SVE_TYPE(Name, Id, SingletonId) \ 1140 CanQualType SingletonId; 1141 #include "clang/Basic/AArch64SVEACLETypes.def" 1142 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 1143 CanQualType Id##Ty; 1144 #include "clang/Basic/PPCTypes.def" 1145 #define RVV_TYPE(Name, Id, SingletonId) \ 1146 CanQualType SingletonId; 1147 #include "clang/Basic/RISCVVTypes.def" 1148 1149 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand. 1150 mutable QualType AutoDeductTy; // Deduction against 'auto'. 1151 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'. 1152 1153 // Decl used to help define __builtin_va_list for some targets. 1154 // The decl is built when constructing 'BuiltinVaListDecl'. 1155 mutable Decl *VaListTagDecl = nullptr; 1156 1157 // Implicitly-declared type 'struct _GUID'. 1158 mutable TagDecl *MSGuidTagDecl = nullptr; 1159 1160 /// Keep track of CUDA/HIP device-side variables ODR-used by host code. 1161 llvm::DenseSet<const VarDecl *> CUDADeviceVarODRUsedByHost; 1162 1163 /// Keep track of CUDA/HIP external kernels or device variables ODR-used by 1164 /// host code. 1165 llvm::DenseSet<const ValueDecl *> CUDAExternalDeviceDeclODRUsedByHost; 1166 1167 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, 1168 SelectorTable &sels, Builtin::Context &builtins, 1169 TranslationUnitKind TUKind); 1170 ASTContext(const ASTContext &) = delete; 1171 ASTContext &operator=(const ASTContext &) = delete; 1172 ~ASTContext(); 1173 1174 /// Attach an external AST source to the AST context. 1175 /// 1176 /// The external AST source provides the ability to load parts of 1177 /// the abstract syntax tree as needed from some external storage, 1178 /// e.g., a precompiled header. 1179 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source); 1180 1181 /// Retrieve a pointer to the external AST source associated 1182 /// with this AST context, if any. 1183 ExternalASTSource *getExternalSource() const { 1184 return ExternalSource.get(); 1185 } 1186 1187 /// Attach an AST mutation listener to the AST context. 1188 /// 1189 /// The AST mutation listener provides the ability to track modifications to 1190 /// the abstract syntax tree entities committed after they were initially 1191 /// created. 1192 void setASTMutationListener(ASTMutationListener *Listener) { 1193 this->Listener = Listener; 1194 } 1195 1196 /// Retrieve a pointer to the AST mutation listener associated 1197 /// with this AST context, if any. 1198 ASTMutationListener *getASTMutationListener() const { return Listener; } 1199 1200 void PrintStats() const; 1201 const SmallVectorImpl<Type *>& getTypes() const { return Types; } 1202 1203 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, 1204 const IdentifierInfo *II) const; 1205 1206 /// Create a new implicit TU-level CXXRecordDecl or RecordDecl 1207 /// declaration. 1208 RecordDecl *buildImplicitRecord(StringRef Name, 1209 RecordDecl::TagKind TK = TTK_Struct) const; 1210 1211 /// Create a new implicit TU-level typedef declaration. 1212 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const; 1213 1214 /// Retrieve the declaration for the 128-bit signed integer type. 1215 TypedefDecl *getInt128Decl() const; 1216 1217 /// Retrieve the declaration for the 128-bit unsigned integer type. 1218 TypedefDecl *getUInt128Decl() const; 1219 1220 //===--------------------------------------------------------------------===// 1221 // Type Constructors 1222 //===--------------------------------------------------------------------===// 1223 1224 private: 1225 /// Return a type with extended qualifiers. 1226 QualType getExtQualType(const Type *Base, Qualifiers Quals) const; 1227 1228 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const; 1229 1230 QualType getPipeType(QualType T, bool ReadOnly) const; 1231 1232 public: 1233 /// Return the uniqued reference to the type for an address space 1234 /// qualified type with the specified type and address space. 1235 /// 1236 /// The resulting type has a union of the qualifiers from T and the address 1237 /// space. If T already has an address space specifier, it is silently 1238 /// replaced. 1239 QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const; 1240 1241 /// Remove any existing address space on the type and returns the type 1242 /// with qualifiers intact (or that's the idea anyway) 1243 /// 1244 /// The return type should be T with all prior qualifiers minus the address 1245 /// space. 1246 QualType removeAddrSpaceQualType(QualType T) const; 1247 1248 /// Apply Objective-C protocol qualifiers to the given type. 1249 /// \param allowOnPointerType specifies if we can apply protocol 1250 /// qualifiers on ObjCObjectPointerType. It can be set to true when 1251 /// constructing the canonical type of a Objective-C type parameter. 1252 QualType applyObjCProtocolQualifiers(QualType type, 1253 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, 1254 bool allowOnPointerType = false) const; 1255 1256 /// Return the uniqued reference to the type for an Objective-C 1257 /// gc-qualified type. 1258 /// 1259 /// The resulting type has a union of the qualifiers from T and the gc 1260 /// attribute. 1261 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const; 1262 1263 /// Remove the existing address space on the type if it is a pointer size 1264 /// address space and return the type with qualifiers intact. 1265 QualType removePtrSizeAddrSpace(QualType T) const; 1266 1267 /// Return the uniqued reference to the type for a \c restrict 1268 /// qualified type. 1269 /// 1270 /// The resulting type has a union of the qualifiers from \p T and 1271 /// \c restrict. 1272 QualType getRestrictType(QualType T) const { 1273 return T.withFastQualifiers(Qualifiers::Restrict); 1274 } 1275 1276 /// Return the uniqued reference to the type for a \c volatile 1277 /// qualified type. 1278 /// 1279 /// The resulting type has a union of the qualifiers from \p T and 1280 /// \c volatile. 1281 QualType getVolatileType(QualType T) const { 1282 return T.withFastQualifiers(Qualifiers::Volatile); 1283 } 1284 1285 /// Return the uniqued reference to the type for a \c const 1286 /// qualified type. 1287 /// 1288 /// The resulting type has a union of the qualifiers from \p T and \c const. 1289 /// 1290 /// It can be reasonably expected that this will always be equivalent to 1291 /// calling T.withConst(). 1292 QualType getConstType(QualType T) const { return T.withConst(); } 1293 1294 /// Change the ExtInfo on a function type. 1295 const FunctionType *adjustFunctionType(const FunctionType *Fn, 1296 FunctionType::ExtInfo EInfo); 1297 1298 /// Adjust the given function result type. 1299 CanQualType getCanonicalFunctionResultType(QualType ResultType) const; 1300 1301 /// Change the result type of a function type once it is deduced. 1302 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType); 1303 1304 /// Get a function type and produce the equivalent function type with the 1305 /// specified exception specification. Type sugar that can be present on a 1306 /// declaration of a function with an exception specification is permitted 1307 /// and preserved. Other type sugar (for instance, typedefs) is not. 1308 QualType getFunctionTypeWithExceptionSpec( 1309 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI); 1310 1311 /// Determine whether two function types are the same, ignoring 1312 /// exception specifications in cases where they're part of the type. 1313 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U); 1314 1315 /// Change the exception specification on a function once it is 1316 /// delay-parsed, instantiated, or computed. 1317 void adjustExceptionSpec(FunctionDecl *FD, 1318 const FunctionProtoType::ExceptionSpecInfo &ESI, 1319 bool AsWritten = false); 1320 1321 /// Get a function type and produce the equivalent function type where 1322 /// pointer size address spaces in the return type and parameter tyeps are 1323 /// replaced with the default address space. 1324 QualType getFunctionTypeWithoutPtrSizes(QualType T); 1325 1326 /// Determine whether two function types are the same, ignoring pointer sizes 1327 /// in the return type and parameter types. 1328 bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U); 1329 1330 /// Return the uniqued reference to the type for a complex 1331 /// number with the specified element type. 1332 QualType getComplexType(QualType T) const; 1333 CanQualType getComplexType(CanQualType T) const { 1334 return CanQualType::CreateUnsafe(getComplexType((QualType) T)); 1335 } 1336 1337 /// Return the uniqued reference to the type for a pointer to 1338 /// the specified type. 1339 QualType getPointerType(QualType T) const; 1340 CanQualType getPointerType(CanQualType T) const { 1341 return CanQualType::CreateUnsafe(getPointerType((QualType) T)); 1342 } 1343 1344 /// Return the uniqued reference to a type adjusted from the original 1345 /// type to a new type. 1346 QualType getAdjustedType(QualType Orig, QualType New) const; 1347 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const { 1348 return CanQualType::CreateUnsafe( 1349 getAdjustedType((QualType)Orig, (QualType)New)); 1350 } 1351 1352 /// Return the uniqued reference to the decayed version of the given 1353 /// type. Can only be called on array and function types which decay to 1354 /// pointer types. 1355 QualType getDecayedType(QualType T) const; 1356 CanQualType getDecayedType(CanQualType T) const { 1357 return CanQualType::CreateUnsafe(getDecayedType((QualType) T)); 1358 } 1359 1360 /// Return the uniqued reference to the atomic type for the specified 1361 /// type. 1362 QualType getAtomicType(QualType T) const; 1363 1364 /// Return the uniqued reference to the type for a block of the 1365 /// specified type. 1366 QualType getBlockPointerType(QualType T) const; 1367 1368 /// Gets the struct used to keep track of the descriptor for pointer to 1369 /// blocks. 1370 QualType getBlockDescriptorType() const; 1371 1372 /// Return a read_only pipe type for the specified type. 1373 QualType getReadPipeType(QualType T) const; 1374 1375 /// Return a write_only pipe type for the specified type. 1376 QualType getWritePipeType(QualType T) const; 1377 1378 /// Return a bit-precise integer type with the specified signedness and bit 1379 /// count. 1380 QualType getBitIntType(bool Unsigned, unsigned NumBits) const; 1381 1382 /// Return a dependent bit-precise integer type with the specified signedness 1383 /// and bit count. 1384 QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const; 1385 1386 /// Gets the struct used to keep track of the extended descriptor for 1387 /// pointer to blocks. 1388 QualType getBlockDescriptorExtendedType() const; 1389 1390 /// Map an AST Type to an OpenCLTypeKind enum value. 1391 OpenCLTypeKind getOpenCLTypeKind(const Type *T) const; 1392 1393 /// Get address space for OpenCL type. 1394 LangAS getOpenCLTypeAddrSpace(const Type *T) const; 1395 1396 /// Returns default address space based on OpenCL version and enabled features 1397 inline LangAS getDefaultOpenCLPointeeAddrSpace() { 1398 return LangOpts.OpenCLGenericAddressSpace ? LangAS::opencl_generic 1399 : LangAS::opencl_private; 1400 } 1401 1402 void setcudaConfigureCallDecl(FunctionDecl *FD) { 1403 cudaConfigureCallDecl = FD; 1404 } 1405 1406 FunctionDecl *getcudaConfigureCallDecl() { 1407 return cudaConfigureCallDecl; 1408 } 1409 1410 /// Returns true iff we need copy/dispose helpers for the given type. 1411 bool BlockRequiresCopying(QualType Ty, const VarDecl *D); 1412 1413 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout 1414 /// is set to false in this case. If HasByrefExtendedLayout returns true, 1415 /// byref variable has extended lifetime. 1416 bool getByrefLifetime(QualType Ty, 1417 Qualifiers::ObjCLifetime &Lifetime, 1418 bool &HasByrefExtendedLayout) const; 1419 1420 /// Return the uniqued reference to the type for an lvalue reference 1421 /// to the specified type. 1422 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true) 1423 const; 1424 1425 /// Return the uniqued reference to the type for an rvalue reference 1426 /// to the specified type. 1427 QualType getRValueReferenceType(QualType T) const; 1428 1429 /// Return the uniqued reference to the type for a member pointer to 1430 /// the specified type in the specified class. 1431 /// 1432 /// The class \p Cls is a \c Type because it could be a dependent name. 1433 QualType getMemberPointerType(QualType T, const Type *Cls) const; 1434 1435 /// Return a non-unique reference to the type for a variable array of 1436 /// the specified element type. 1437 QualType getVariableArrayType(QualType EltTy, Expr *NumElts, 1438 ArrayType::ArraySizeModifier ASM, 1439 unsigned IndexTypeQuals, 1440 SourceRange Brackets) const; 1441 1442 /// Return a non-unique reference to the type for a dependently-sized 1443 /// array of the specified element type. 1444 /// 1445 /// FIXME: We will need these to be uniqued, or at least comparable, at some 1446 /// point. 1447 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, 1448 ArrayType::ArraySizeModifier ASM, 1449 unsigned IndexTypeQuals, 1450 SourceRange Brackets) const; 1451 1452 /// Return a unique reference to the type for an incomplete array of 1453 /// the specified element type. 1454 QualType getIncompleteArrayType(QualType EltTy, 1455 ArrayType::ArraySizeModifier ASM, 1456 unsigned IndexTypeQuals) const; 1457 1458 /// Return the unique reference to the type for a constant array of 1459 /// the specified element type. 1460 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, 1461 const Expr *SizeExpr, 1462 ArrayType::ArraySizeModifier ASM, 1463 unsigned IndexTypeQuals) const; 1464 1465 /// Return a type for a constant array for a string literal of the 1466 /// specified element type and length. 1467 QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const; 1468 1469 /// Returns a vla type where known sizes are replaced with [*]. 1470 QualType getVariableArrayDecayedType(QualType Ty) const; 1471 1472 // Convenience struct to return information about a builtin vector type. 1473 struct BuiltinVectorTypeInfo { 1474 QualType ElementType; 1475 llvm::ElementCount EC; 1476 unsigned NumVectors; 1477 BuiltinVectorTypeInfo(QualType ElementType, llvm::ElementCount EC, 1478 unsigned NumVectors) 1479 : ElementType(ElementType), EC(EC), NumVectors(NumVectors) {} 1480 }; 1481 1482 /// Returns the element type, element count and number of vectors 1483 /// (in case of tuple) for a builtin vector type. 1484 BuiltinVectorTypeInfo 1485 getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const; 1486 1487 /// Return the unique reference to a scalable vector type of the specified 1488 /// element type and scalable number of elements. 1489 /// 1490 /// \pre \p EltTy must be a built-in type. 1491 QualType getScalableVectorType(QualType EltTy, unsigned NumElts) const; 1492 1493 /// Return the unique reference to a vector type of the specified 1494 /// element type and size. 1495 /// 1496 /// \pre \p VectorType must be a built-in type. 1497 QualType getVectorType(QualType VectorType, unsigned NumElts, 1498 VectorType::VectorKind VecKind) const; 1499 /// Return the unique reference to the type for a dependently sized vector of 1500 /// the specified element type. 1501 QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, 1502 SourceLocation AttrLoc, 1503 VectorType::VectorKind VecKind) const; 1504 1505 /// Return the unique reference to an extended vector type 1506 /// of the specified element type and size. 1507 /// 1508 /// \pre \p VectorType must be a built-in type. 1509 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const; 1510 1511 /// \pre Return a non-unique reference to the type for a dependently-sized 1512 /// vector of the specified element type. 1513 /// 1514 /// FIXME: We will need these to be uniqued, or at least comparable, at some 1515 /// point. 1516 QualType getDependentSizedExtVectorType(QualType VectorType, 1517 Expr *SizeExpr, 1518 SourceLocation AttrLoc) const; 1519 1520 /// Return the unique reference to the matrix type of the specified element 1521 /// type and size 1522 /// 1523 /// \pre \p ElementType must be a valid matrix element type (see 1524 /// MatrixType::isValidElementType). 1525 QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, 1526 unsigned NumColumns) const; 1527 1528 /// Return the unique reference to the matrix type of the specified element 1529 /// type and size 1530 QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, 1531 Expr *ColumnExpr, 1532 SourceLocation AttrLoc) const; 1533 1534 QualType getDependentAddressSpaceType(QualType PointeeType, 1535 Expr *AddrSpaceExpr, 1536 SourceLocation AttrLoc) const; 1537 1538 /// Return a K&R style C function type like 'int()'. 1539 QualType getFunctionNoProtoType(QualType ResultTy, 1540 const FunctionType::ExtInfo &Info) const; 1541 1542 QualType getFunctionNoProtoType(QualType ResultTy) const { 1543 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo()); 1544 } 1545 1546 /// Return a normal function type with a typed argument list. 1547 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args, 1548 const FunctionProtoType::ExtProtoInfo &EPI) const { 1549 return getFunctionTypeInternal(ResultTy, Args, EPI, false); 1550 } 1551 1552 QualType adjustStringLiteralBaseType(QualType StrLTy) const; 1553 1554 private: 1555 /// Return a normal function type with a typed argument list. 1556 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args, 1557 const FunctionProtoType::ExtProtoInfo &EPI, 1558 bool OnlyWantCanonical) const; 1559 QualType 1560 getAutoTypeInternal(QualType DeducedType, AutoTypeKeyword Keyword, 1561 bool IsDependent, bool IsPack = false, 1562 ConceptDecl *TypeConstraintConcept = nullptr, 1563 ArrayRef<TemplateArgument> TypeConstraintArgs = {}, 1564 bool IsCanon = false) const; 1565 1566 public: 1567 /// Return the unique reference to the type for the specified type 1568 /// declaration. 1569 QualType getTypeDeclType(const TypeDecl *Decl, 1570 const TypeDecl *PrevDecl = nullptr) const { 1571 assert(Decl && "Passed null for Decl param"); 1572 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1573 1574 if (PrevDecl) { 1575 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 1576 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1577 return QualType(PrevDecl->TypeForDecl, 0); 1578 } 1579 1580 return getTypeDeclTypeSlow(Decl); 1581 } 1582 1583 QualType getUsingType(const UsingShadowDecl *Found, 1584 QualType Underlying) const; 1585 1586 /// Return the unique reference to the type for the specified 1587 /// typedef-name decl. 1588 QualType getTypedefType(const TypedefNameDecl *Decl, 1589 QualType Underlying = QualType()) const; 1590 1591 QualType getRecordType(const RecordDecl *Decl) const; 1592 1593 QualType getEnumType(const EnumDecl *Decl) const; 1594 1595 QualType 1596 getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) const; 1597 1598 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const; 1599 1600 QualType getAttributedType(attr::Kind attrKind, 1601 QualType modifiedType, 1602 QualType equivalentType); 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 /// 2658 /// FIXME: isSameEntity is not const due to its implementation calls 2659 /// hasSameFunctionTypeIgnoringExceptionSpec which may alter this. 2660 bool isSameEntity(const NamedDecl *X, const NamedDecl *Y); 2661 2662 /// Determine whether two template parameter lists are similar enough 2663 /// that they may be used in declarations of the same template. 2664 /// 2665 /// FIXME: isSameTemplateParameterList is not const since it calls 2666 /// isSameTemplateParameter. 2667 bool isSameTemplateParameterList(const TemplateParameterList *X, 2668 const TemplateParameterList *Y); 2669 2670 /// Determine whether two template parameters are similar enough 2671 /// that they may be used in declarations of the same template. 2672 /// 2673 /// FIXME: isSameTemplateParameterList is not const since it calls 2674 /// isSameEntity. 2675 bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y); 2676 2677 /// Retrieve the "canonical" template argument. 2678 /// 2679 /// The canonical template argument is the simplest template argument 2680 /// (which may be a type, value, expression, or declaration) that 2681 /// expresses the value of the argument. 2682 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) 2683 const; 2684 2685 /// Type Query functions. If the type is an instance of the specified class, 2686 /// return the Type pointer for the underlying maximally pretty type. This 2687 /// is a member of ASTContext because this may need to do some amount of 2688 /// canonicalization, e.g. to move type qualifiers into the element type. 2689 const ArrayType *getAsArrayType(QualType T) const; 2690 const ConstantArrayType *getAsConstantArrayType(QualType T) const { 2691 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T)); 2692 } 2693 const VariableArrayType *getAsVariableArrayType(QualType T) const { 2694 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T)); 2695 } 2696 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const { 2697 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T)); 2698 } 2699 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T) 2700 const { 2701 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T)); 2702 } 2703 2704 /// Return the innermost element type of an array type. 2705 /// 2706 /// For example, will return "int" for int[m][n] 2707 QualType getBaseElementType(const ArrayType *VAT) const; 2708 2709 /// Return the innermost element type of a type (which needn't 2710 /// actually be an array type). 2711 QualType getBaseElementType(QualType QT) const; 2712 2713 /// Return number of constant array elements. 2714 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const; 2715 2716 /// Perform adjustment on the parameter type of a function. 2717 /// 2718 /// This routine adjusts the given parameter type @p T to the actual 2719 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8], 2720 /// C++ [dcl.fct]p3). The adjusted parameter type is returned. 2721 QualType getAdjustedParameterType(QualType T) const; 2722 2723 /// Retrieve the parameter type as adjusted for use in the signature 2724 /// of a function, decaying array and function types and removing top-level 2725 /// cv-qualifiers. 2726 QualType getSignatureParameterType(QualType T) const; 2727 2728 QualType getExceptionObjectType(QualType T) const; 2729 2730 /// Return the properly qualified result of decaying the specified 2731 /// array type to a pointer. 2732 /// 2733 /// This operation is non-trivial when handling typedefs etc. The canonical 2734 /// type of \p T must be an array type, this returns a pointer to a properly 2735 /// qualified element of the array. 2736 /// 2737 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 2738 QualType getArrayDecayedType(QualType T) const; 2739 2740 /// Return the type that \p PromotableType will promote to: C99 2741 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type. 2742 QualType getPromotedIntegerType(QualType PromotableType) const; 2743 2744 /// Recurses in pointer/array types until it finds an Objective-C 2745 /// retainable type and returns its ownership. 2746 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const; 2747 2748 /// Whether this is a promotable bitfield reference according 2749 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 2750 /// 2751 /// \returns the type this bit-field will promote to, or NULL if no 2752 /// promotion occurs. 2753 QualType isPromotableBitField(Expr *E) const; 2754 2755 /// Return the highest ranked integer type, see C99 6.3.1.8p1. 2756 /// 2757 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If 2758 /// \p LHS < \p RHS, return -1. 2759 int getIntegerTypeOrder(QualType LHS, QualType RHS) const; 2760 2761 /// Compare the rank of the two specified floating point types, 2762 /// ignoring the domain of the type (i.e. 'double' == '_Complex double'). 2763 /// 2764 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If 2765 /// \p LHS < \p RHS, return -1. 2766 int getFloatingTypeOrder(QualType LHS, QualType RHS) const; 2767 2768 /// Compare the rank of two floating point types as above, but compare equal 2769 /// if both types have the same floating-point semantics on the target (i.e. 2770 /// long double and double on AArch64 will return 0). 2771 int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const; 2772 2773 unsigned getTargetAddressSpace(QualType T) const; 2774 2775 unsigned getTargetAddressSpace(Qualifiers Q) const; 2776 2777 unsigned getTargetAddressSpace(LangAS AS) const; 2778 2779 LangAS getLangASForBuiltinAddressSpace(unsigned AS) const; 2780 2781 /// Get target-dependent integer value for null pointer which is used for 2782 /// constant folding. 2783 uint64_t getTargetNullPointerValue(QualType QT) const; 2784 2785 bool addressSpaceMapManglingFor(LangAS AS) const { 2786 return AddrSpaceMapMangling || isTargetAddressSpace(AS); 2787 } 2788 2789 private: 2790 // Helper for integer ordering 2791 unsigned getIntegerRank(const Type *T) const; 2792 2793 public: 2794 //===--------------------------------------------------------------------===// 2795 // Type Compatibility Predicates 2796 //===--------------------------------------------------------------------===// 2797 2798 /// Compatibility predicates used to check assignment expressions. 2799 bool typesAreCompatible(QualType T1, QualType T2, 2800 bool CompareUnqualified = false); // C99 6.2.7p1 2801 2802 bool propertyTypesAreCompatible(QualType, QualType); 2803 bool typesAreBlockPointerCompatible(QualType, QualType); 2804 2805 bool isObjCIdType(QualType T) const { 2806 return T == getObjCIdType(); 2807 } 2808 2809 bool isObjCClassType(QualType T) const { 2810 return T == getObjCClassType(); 2811 } 2812 2813 bool isObjCSelType(QualType T) const { 2814 return T == getObjCSelType(); 2815 } 2816 2817 bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, 2818 const ObjCObjectPointerType *RHS, 2819 bool ForCompare); 2820 2821 bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, 2822 const ObjCObjectPointerType *RHS); 2823 2824 // Check the safety of assignment from LHS to RHS 2825 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 2826 const ObjCObjectPointerType *RHSOPT); 2827 bool canAssignObjCInterfaces(const ObjCObjectType *LHS, 2828 const ObjCObjectType *RHS); 2829 bool canAssignObjCInterfacesInBlockPointer( 2830 const ObjCObjectPointerType *LHSOPT, 2831 const ObjCObjectPointerType *RHSOPT, 2832 bool BlockReturnType); 2833 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS); 2834 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, 2835 const ObjCObjectPointerType *RHSOPT); 2836 bool canBindObjCObjectType(QualType To, QualType From); 2837 2838 // Functions for calculating composite types 2839 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, 2840 bool Unqualified = false, bool BlockReturnType = false); 2841 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, 2842 bool Unqualified = false, bool AllowCXX = false); 2843 QualType mergeFunctionParameterTypes(QualType, QualType, 2844 bool OfBlockPointer = false, 2845 bool Unqualified = false); 2846 QualType mergeTransparentUnionType(QualType, QualType, 2847 bool OfBlockPointer=false, 2848 bool Unqualified = false); 2849 2850 QualType mergeObjCGCQualifiers(QualType, QualType); 2851 2852 /// This function merges the ExtParameterInfo lists of two functions. It 2853 /// returns true if the lists are compatible. The merged list is returned in 2854 /// NewParamInfos. 2855 /// 2856 /// \param FirstFnType The type of the first function. 2857 /// 2858 /// \param SecondFnType The type of the second function. 2859 /// 2860 /// \param CanUseFirst This flag is set to true if the first function's 2861 /// ExtParameterInfo list can be used as the composite list of 2862 /// ExtParameterInfo. 2863 /// 2864 /// \param CanUseSecond This flag is set to true if the second function's 2865 /// ExtParameterInfo list can be used as the composite list of 2866 /// ExtParameterInfo. 2867 /// 2868 /// \param NewParamInfos The composite list of ExtParameterInfo. The list is 2869 /// empty if none of the flags are set. 2870 /// 2871 bool mergeExtParameterInfo( 2872 const FunctionProtoType *FirstFnType, 2873 const FunctionProtoType *SecondFnType, 2874 bool &CanUseFirst, bool &CanUseSecond, 2875 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos); 2876 2877 void ResetObjCLayout(const ObjCContainerDecl *CD); 2878 2879 //===--------------------------------------------------------------------===// 2880 // Integer Predicates 2881 //===--------------------------------------------------------------------===// 2882 2883 // The width of an integer, as defined in C99 6.2.6.2. This is the number 2884 // of bits in an integer type excluding any padding bits. 2885 unsigned getIntWidth(QualType T) const; 2886 2887 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding 2888 // unsigned integer type. This method takes a signed type, and returns the 2889 // corresponding unsigned integer type. 2890 // With the introduction of fixed point types in ISO N1169, this method also 2891 // accepts fixed point types and returns the corresponding unsigned type for 2892 // a given fixed point type. 2893 QualType getCorrespondingUnsignedType(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 an unsigned type, and returns the 2897 // corresponding signed 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 signed type for 2900 // a given fixed point type. 2901 QualType getCorrespondingSignedType(QualType T) const; 2902 2903 // Per ISO N1169, this method accepts fixed point types and returns the 2904 // corresponding saturated type for a given fixed point type. 2905 QualType getCorrespondingSaturatedType(QualType Ty) const; 2906 2907 // This method accepts fixed point types and returns the corresponding signed 2908 // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned 2909 // fixed point types because there are unsigned integer types like bool and 2910 // char8_t that don't have signed equivalents. 2911 QualType getCorrespondingSignedFixedPointType(QualType Ty) const; 2912 2913 //===--------------------------------------------------------------------===// 2914 // Integer Values 2915 //===--------------------------------------------------------------------===// 2916 2917 /// Make an APSInt of the appropriate width and signedness for the 2918 /// given \p Value and integer \p Type. 2919 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const { 2920 // If Type is a signed integer type larger than 64 bits, we need to be sure 2921 // to sign extend Res appropriately. 2922 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType()); 2923 Res = Value; 2924 unsigned Width = getIntWidth(Type); 2925 if (Width != Res.getBitWidth()) 2926 return Res.extOrTrunc(Width); 2927 return Res; 2928 } 2929 2930 bool isSentinelNullExpr(const Expr *E); 2931 2932 /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if 2933 /// none exists. 2934 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D); 2935 2936 /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if 2937 /// none exists. 2938 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D); 2939 2940 /// Return true if there is at least one \@implementation in the TU. 2941 bool AnyObjCImplementation() { 2942 return !ObjCImpls.empty(); 2943 } 2944 2945 /// Set the implementation of ObjCInterfaceDecl. 2946 void setObjCImplementation(ObjCInterfaceDecl *IFaceD, 2947 ObjCImplementationDecl *ImplD); 2948 2949 /// Set the implementation of ObjCCategoryDecl. 2950 void setObjCImplementation(ObjCCategoryDecl *CatD, 2951 ObjCCategoryImplDecl *ImplD); 2952 2953 /// Get the duplicate declaration of a ObjCMethod in the same 2954 /// interface, or null if none exists. 2955 const ObjCMethodDecl * 2956 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const; 2957 2958 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, 2959 const ObjCMethodDecl *Redecl); 2960 2961 /// Returns the Objective-C interface that \p ND belongs to if it is 2962 /// an Objective-C method/property/ivar etc. that is part of an interface, 2963 /// otherwise returns null. 2964 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const; 2965 2966 /// Set the copy initialization expression of a block var decl. \p CanThrow 2967 /// indicates whether the copy expression can throw or not. 2968 void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow); 2969 2970 /// Get the copy initialization expression of the VarDecl \p VD, or 2971 /// nullptr if none exists. 2972 BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const; 2973 2974 /// Allocate an uninitialized TypeSourceInfo. 2975 /// 2976 /// The caller should initialize the memory held by TypeSourceInfo using 2977 /// the TypeLoc wrappers. 2978 /// 2979 /// \param T the type that will be the basis for type source info. This type 2980 /// should refer to how the declarator was written in source code, not to 2981 /// what type semantic analysis resolved the declarator to. 2982 /// 2983 /// \param Size the size of the type info to create, or 0 if the size 2984 /// should be calculated based on the type. 2985 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const; 2986 2987 /// Allocate a TypeSourceInfo where all locations have been 2988 /// initialized to a given location, which defaults to the empty 2989 /// location. 2990 TypeSourceInfo * 2991 getTrivialTypeSourceInfo(QualType T, 2992 SourceLocation Loc = SourceLocation()) const; 2993 2994 /// Add a deallocation callback that will be invoked when the 2995 /// ASTContext is destroyed. 2996 /// 2997 /// \param Callback A callback function that will be invoked on destruction. 2998 /// 2999 /// \param Data Pointer data that will be provided to the callback function 3000 /// when it is called. 3001 void AddDeallocation(void (*Callback)(void *), void *Data) const; 3002 3003 /// If T isn't trivially destructible, calls AddDeallocation to register it 3004 /// for destruction. 3005 template <typename T> void addDestruction(T *Ptr) const { 3006 if (!std::is_trivially_destructible<T>::value) { 3007 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); }; 3008 AddDeallocation(DestroyPtr, Ptr); 3009 } 3010 } 3011 3012 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const; 3013 GVALinkage GetGVALinkageForVariable(const VarDecl *VD); 3014 3015 /// Determines if the decl can be CodeGen'ed or deserialized from PCH 3016 /// lazily, only when used; this is only relevant for function or file scoped 3017 /// var definitions. 3018 /// 3019 /// \returns true if the function/var must be CodeGen'ed/deserialized even if 3020 /// it is not used. 3021 bool DeclMustBeEmitted(const Decl *D); 3022 3023 /// Visits all versions of a multiversioned function with the passed 3024 /// predicate. 3025 void forEachMultiversionedFunctionVersion( 3026 const FunctionDecl *FD, 3027 llvm::function_ref<void(FunctionDecl *)> Pred) const; 3028 3029 const CXXConstructorDecl * 3030 getCopyConstructorForExceptionObject(CXXRecordDecl *RD); 3031 3032 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, 3033 CXXConstructorDecl *CD); 3034 3035 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND); 3036 3037 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD); 3038 3039 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD); 3040 3041 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD); 3042 3043 void setManglingNumber(const NamedDecl *ND, unsigned Number); 3044 unsigned getManglingNumber(const NamedDecl *ND, 3045 bool ForAuxTarget = false) const; 3046 3047 void setStaticLocalNumber(const VarDecl *VD, unsigned Number); 3048 unsigned getStaticLocalNumber(const VarDecl *VD) const; 3049 3050 /// Retrieve the context for computing mangling numbers in the given 3051 /// DeclContext. 3052 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC); 3053 enum NeedExtraManglingDecl_t { NeedExtraManglingDecl }; 3054 MangleNumberingContext &getManglingNumberContext(NeedExtraManglingDecl_t, 3055 const Decl *D); 3056 3057 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const; 3058 3059 /// Used by ParmVarDecl to store on the side the 3060 /// index of the parameter when it exceeds the size of the normal bitfield. 3061 void setParameterIndex(const ParmVarDecl *D, unsigned index); 3062 3063 /// Used by ParmVarDecl to retrieve on the side the 3064 /// index of the parameter when it exceeds the size of the normal bitfield. 3065 unsigned getParameterIndex(const ParmVarDecl *D) const; 3066 3067 /// Return a string representing the human readable name for the specified 3068 /// function declaration or file name. Used by SourceLocExpr and 3069 /// PredefinedExpr to cache evaluated results. 3070 StringLiteral *getPredefinedStringLiteralFromCache(StringRef Key) const; 3071 3072 /// Return a declaration for the global GUID object representing the given 3073 /// GUID value. 3074 MSGuidDecl *getMSGuidDecl(MSGuidDeclParts Parts) const; 3075 3076 /// Return a declaration for a uniquified anonymous global constant 3077 /// corresponding to a given APValue. 3078 UnnamedGlobalConstantDecl * 3079 getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const; 3080 3081 /// Return the template parameter object of the given type with the given 3082 /// value. 3083 TemplateParamObjectDecl *getTemplateParamObjectDecl(QualType T, 3084 const APValue &V) const; 3085 3086 /// Parses the target attributes passed in, and returns only the ones that are 3087 /// valid feature names. 3088 ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const; 3089 3090 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 3091 const FunctionDecl *) const; 3092 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 3093 GlobalDecl GD) const; 3094 3095 //===--------------------------------------------------------------------===// 3096 // Statistics 3097 //===--------------------------------------------------------------------===// 3098 3099 /// The number of implicitly-declared default constructors. 3100 unsigned NumImplicitDefaultConstructors = 0; 3101 3102 /// The number of implicitly-declared default constructors for 3103 /// which declarations were built. 3104 unsigned NumImplicitDefaultConstructorsDeclared = 0; 3105 3106 /// The number of implicitly-declared copy constructors. 3107 unsigned NumImplicitCopyConstructors = 0; 3108 3109 /// The number of implicitly-declared copy constructors for 3110 /// which declarations were built. 3111 unsigned NumImplicitCopyConstructorsDeclared = 0; 3112 3113 /// The number of implicitly-declared move constructors. 3114 unsigned NumImplicitMoveConstructors = 0; 3115 3116 /// The number of implicitly-declared move constructors for 3117 /// which declarations were built. 3118 unsigned NumImplicitMoveConstructorsDeclared = 0; 3119 3120 /// The number of implicitly-declared copy assignment operators. 3121 unsigned NumImplicitCopyAssignmentOperators = 0; 3122 3123 /// The number of implicitly-declared copy assignment operators for 3124 /// which declarations were built. 3125 unsigned NumImplicitCopyAssignmentOperatorsDeclared = 0; 3126 3127 /// The number of implicitly-declared move assignment operators. 3128 unsigned NumImplicitMoveAssignmentOperators = 0; 3129 3130 /// The number of implicitly-declared move assignment operators for 3131 /// which declarations were built. 3132 unsigned NumImplicitMoveAssignmentOperatorsDeclared = 0; 3133 3134 /// The number of implicitly-declared destructors. 3135 unsigned NumImplicitDestructors = 0; 3136 3137 /// The number of implicitly-declared destructors for which 3138 /// declarations were built. 3139 unsigned NumImplicitDestructorsDeclared = 0; 3140 3141 public: 3142 /// Initialize built-in types. 3143 /// 3144 /// This routine may only be invoked once for a given ASTContext object. 3145 /// It is normally invoked after ASTContext construction. 3146 /// 3147 /// \param Target The target 3148 void InitBuiltinTypes(const TargetInfo &Target, 3149 const TargetInfo *AuxTarget = nullptr); 3150 3151 private: 3152 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K); 3153 3154 class ObjCEncOptions { 3155 unsigned Bits; 3156 3157 ObjCEncOptions(unsigned Bits) : Bits(Bits) {} 3158 3159 public: 3160 ObjCEncOptions() : Bits(0) {} 3161 ObjCEncOptions(const ObjCEncOptions &RHS) : Bits(RHS.Bits) {} 3162 3163 #define OPT_LIST(V) \ 3164 V(ExpandPointedToStructures, 0) \ 3165 V(ExpandStructures, 1) \ 3166 V(IsOutermostType, 2) \ 3167 V(EncodingProperty, 3) \ 3168 V(IsStructField, 4) \ 3169 V(EncodeBlockParameters, 5) \ 3170 V(EncodeClassNames, 6) \ 3171 3172 #define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; } 3173 OPT_LIST(V) 3174 #undef V 3175 3176 #define V(N,I) bool N() const { return Bits & 1 << I; } 3177 OPT_LIST(V) 3178 #undef V 3179 3180 #undef OPT_LIST 3181 3182 LLVM_NODISCARD ObjCEncOptions keepingOnly(ObjCEncOptions Mask) const { 3183 return Bits & Mask.Bits; 3184 } 3185 3186 LLVM_NODISCARD ObjCEncOptions forComponentType() const { 3187 ObjCEncOptions Mask = ObjCEncOptions() 3188 .setIsOutermostType() 3189 .setIsStructField(); 3190 return Bits & ~Mask.Bits; 3191 } 3192 }; 3193 3194 // Return the Objective-C type encoding for a given type. 3195 void getObjCEncodingForTypeImpl(QualType t, std::string &S, 3196 ObjCEncOptions Options, 3197 const FieldDecl *Field, 3198 QualType *NotEncodedT = nullptr) const; 3199 3200 // Adds the encoding of the structure's members. 3201 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S, 3202 const FieldDecl *Field, 3203 bool includeVBases = true, 3204 QualType *NotEncodedT=nullptr) const; 3205 3206 public: 3207 // Adds the encoding of a method parameter or return type. 3208 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 3209 QualType T, std::string& S, 3210 bool Extended) const; 3211 3212 /// Returns true if this is an inline-initialized static data member 3213 /// which is treated as a definition for MSVC compatibility. 3214 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const; 3215 3216 enum class InlineVariableDefinitionKind { 3217 /// Not an inline variable. 3218 None, 3219 3220 /// Weak definition of inline variable. 3221 Weak, 3222 3223 /// Weak for now, might become strong later in this TU. 3224 WeakUnknown, 3225 3226 /// Strong definition. 3227 Strong 3228 }; 3229 3230 /// Determine whether a definition of this inline variable should 3231 /// be treated as a weak or strong definition. For compatibility with 3232 /// C++14 and before, for a constexpr static data member, if there is an 3233 /// out-of-line declaration of the member, we may promote it from weak to 3234 /// strong. 3235 InlineVariableDefinitionKind 3236 getInlineVariableDefinitionKind(const VarDecl *VD) const; 3237 3238 private: 3239 friend class DeclarationNameTable; 3240 friend class DeclContext; 3241 3242 const ASTRecordLayout & 3243 getObjCLayout(const ObjCInterfaceDecl *D, 3244 const ObjCImplementationDecl *Impl) const; 3245 3246 /// A set of deallocations that should be performed when the 3247 /// ASTContext is destroyed. 3248 // FIXME: We really should have a better mechanism in the ASTContext to 3249 // manage running destructors for types which do variable sized allocation 3250 // within the AST. In some places we thread the AST bump pointer allocator 3251 // into the datastructures which avoids this mess during deallocation but is 3252 // wasteful of memory, and here we require a lot of error prone book keeping 3253 // in order to track and run destructors while we're tearing things down. 3254 using DeallocationFunctionsAndArguments = 3255 llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>; 3256 mutable DeallocationFunctionsAndArguments Deallocations; 3257 3258 // FIXME: This currently contains the set of StoredDeclMaps used 3259 // by DeclContext objects. This probably should not be in ASTContext, 3260 // but we include it here so that ASTContext can quickly deallocate them. 3261 llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM; 3262 3263 std::vector<Decl *> TraversalScope; 3264 3265 std::unique_ptr<VTableContextBase> VTContext; 3266 3267 void ReleaseDeclContextMaps(); 3268 3269 public: 3270 enum PragmaSectionFlag : unsigned { 3271 PSF_None = 0, 3272 PSF_Read = 0x1, 3273 PSF_Write = 0x2, 3274 PSF_Execute = 0x4, 3275 PSF_Implicit = 0x8, 3276 PSF_ZeroInit = 0x10, 3277 PSF_Invalid = 0x80000000U, 3278 }; 3279 3280 struct SectionInfo { 3281 NamedDecl *Decl; 3282 SourceLocation PragmaSectionLocation; 3283 int SectionFlags; 3284 3285 SectionInfo() = default; 3286 SectionInfo(NamedDecl *Decl, SourceLocation PragmaSectionLocation, 3287 int SectionFlags) 3288 : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation), 3289 SectionFlags(SectionFlags) {} 3290 }; 3291 3292 llvm::StringMap<SectionInfo> SectionInfos; 3293 3294 /// Return a new OMPTraitInfo object owned by this context. 3295 OMPTraitInfo &getNewOMPTraitInfo(); 3296 3297 /// Whether a C++ static variable or CUDA/HIP kernel may be externalized. 3298 bool mayExternalize(const Decl *D) const; 3299 3300 /// Whether a C++ static variable or CUDA/HIP kernel should be externalized. 3301 bool shouldExternalize(const Decl *D) const; 3302 3303 StringRef getCUIDHash() const; 3304 3305 private: 3306 /// All OMPTraitInfo objects live in this collection, one per 3307 /// `pragma omp [begin] declare variant` directive. 3308 SmallVector<std::unique_ptr<OMPTraitInfo>, 4> OMPTraitInfoVector; 3309 }; 3310 3311 /// Insertion operator for diagnostics. 3312 const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB, 3313 const ASTContext::SectionInfo &Section); 3314 3315 /// Utility function for constructing a nullary selector. 3316 inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) { 3317 IdentifierInfo* II = &Ctx.Idents.get(name); 3318 return Ctx.Selectors.getSelector(0, &II); 3319 } 3320 3321 /// Utility function for constructing an unary selector. 3322 inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) { 3323 IdentifierInfo* II = &Ctx.Idents.get(name); 3324 return Ctx.Selectors.getSelector(1, &II); 3325 } 3326 3327 } // namespace clang 3328 3329 // operator new and delete aren't allowed inside namespaces. 3330 3331 /// Placement new for using the ASTContext's allocator. 3332 /// 3333 /// This placement form of operator new uses the ASTContext's allocator for 3334 /// obtaining memory. 3335 /// 3336 /// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h! 3337 /// Any changes here need to also be made there. 3338 /// 3339 /// We intentionally avoid using a nothrow specification here so that the calls 3340 /// to this operator will not perform a null check on the result -- the 3341 /// underlying allocator never returns null pointers. 3342 /// 3343 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope): 3344 /// @code 3345 /// // Default alignment (8) 3346 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments); 3347 /// // Specific alignment 3348 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments); 3349 /// @endcode 3350 /// Memory allocated through this placement new operator does not need to be 3351 /// explicitly freed, as ASTContext will free all of this memory when it gets 3352 /// destroyed. Please note that you cannot use delete on the pointer. 3353 /// 3354 /// @param Bytes The number of bytes to allocate. Calculated by the compiler. 3355 /// @param C The ASTContext that provides the allocator. 3356 /// @param Alignment The alignment of the allocated memory (if the underlying 3357 /// allocator supports it). 3358 /// @return The allocated memory. Could be nullptr. 3359 inline void *operator new(size_t Bytes, const clang::ASTContext &C, 3360 size_t Alignment /* = 8 */) { 3361 return C.Allocate(Bytes, Alignment); 3362 } 3363 3364 /// Placement delete companion to the new above. 3365 /// 3366 /// This operator is just a companion to the new above. There is no way of 3367 /// invoking it directly; see the new operator for more details. This operator 3368 /// is called implicitly by the compiler if a placement new expression using 3369 /// the ASTContext throws in the object constructor. 3370 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) { 3371 C.Deallocate(Ptr); 3372 } 3373 3374 /// This placement form of operator new[] uses the ASTContext's allocator for 3375 /// obtaining memory. 3376 /// 3377 /// We intentionally avoid using a nothrow specification here so that the calls 3378 /// to this operator will not perform a null check on the result -- the 3379 /// underlying allocator never returns null pointers. 3380 /// 3381 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope): 3382 /// @code 3383 /// // Default alignment (8) 3384 /// char *data = new (Context) char[10]; 3385 /// // Specific alignment 3386 /// char *data = new (Context, 4) char[10]; 3387 /// @endcode 3388 /// Memory allocated through this placement new[] operator does not need to be 3389 /// explicitly freed, as ASTContext will free all of this memory when it gets 3390 /// destroyed. Please note that you cannot use delete on the pointer. 3391 /// 3392 /// @param Bytes The number of bytes to allocate. Calculated by the compiler. 3393 /// @param C The ASTContext that provides the allocator. 3394 /// @param Alignment The alignment of the allocated memory (if the underlying 3395 /// allocator supports it). 3396 /// @return The allocated memory. Could be nullptr. 3397 inline void *operator new[](size_t Bytes, const clang::ASTContext& C, 3398 size_t Alignment /* = 8 */) { 3399 return C.Allocate(Bytes, Alignment); 3400 } 3401 3402 /// Placement delete[] companion to the new[] above. 3403 /// 3404 /// This operator is just a companion to the new[] above. There is no way of 3405 /// invoking it directly; see the new[] operator for more details. This operator 3406 /// is called implicitly by the compiler if a placement new[] expression using 3407 /// the ASTContext throws in the object constructor. 3408 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) { 3409 C.Deallocate(Ptr); 3410 } 3411 3412 /// Create the representation of a LazyGenerationalUpdatePtr. 3413 template <typename Owner, typename T, 3414 void (clang::ExternalASTSource::*Update)(Owner)> 3415 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType 3416 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue( 3417 const clang::ASTContext &Ctx, T Value) { 3418 // Note, this is implemented here so that ExternalASTSource.h doesn't need to 3419 // include ASTContext.h. We explicitly instantiate it for all relevant types 3420 // in ASTContext.cpp. 3421 if (auto *Source = Ctx.getExternalSource()) 3422 return new (Ctx) LazyData(Source, Value); 3423 return Value; 3424 } 3425 3426 #endif // LLVM_CLANG_AST_ASTCONTEXT_H 3427