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