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