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