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