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

source code of clang/include/clang/AST/ASTContext.h