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