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