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