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