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