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