ASTContext.h revision a6ea10e22b600d92e084f6b11b9b9a92d0eb2412
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//  This file defines the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
15#define LLVM_CLANG_AST_ASTCONTEXT_H
16
17#include "clang/Basic/AddressSpaces.h"
18#include "clang/Basic/IdentifierTable.h"
19#include "clang/Basic/LangOptions.h"
20#include "clang/Basic/OperatorKinds.h"
21#include "clang/Basic/PartialDiagnostic.h"
22#include "clang/Basic/VersionTuple.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/NestedNameSpecifier.h"
25#include "clang/AST/PrettyPrinter.h"
26#include "clang/AST/TemplateName.h"
27#include "clang/AST/Type.h"
28#include "clang/AST/CanonicalType.h"
29#include "clang/AST/UsuallyTinyPtrVector.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/FoldingSet.h"
32#include "llvm/ADT/IntrusiveRefCntPtr.h"
33#include "llvm/ADT/OwningPtr.h"
34#include "llvm/ADT/SmallPtrSet.h"
35#include "llvm/Support/Allocator.h"
36#include <vector>
37
38namespace llvm {
39  struct fltSemantics;
40}
41
42namespace clang {
43  class FileManager;
44  class ASTRecordLayout;
45  class BlockExpr;
46  class CharUnits;
47  class DiagnosticsEngine;
48  class Expr;
49  class ExternalASTSource;
50  class ASTMutationListener;
51  class IdentifierTable;
52  class SelectorTable;
53  class SourceManager;
54  class TargetInfo;
55  class CXXABI;
56  // Decls
57  class DeclContext;
58  class CXXMethodDecl;
59  class CXXRecordDecl;
60  class Decl;
61  class FieldDecl;
62  class MangleContext;
63  class ObjCIvarDecl;
64  class ObjCIvarRefExpr;
65  class ObjCPropertyDecl;
66  class ParmVarDecl;
67  class RecordDecl;
68  class StoredDeclsMap;
69  class TagDecl;
70  class TemplateTemplateParmDecl;
71  class TemplateTypeParmDecl;
72  class TranslationUnitDecl;
73  class TypeDecl;
74  class TypedefNameDecl;
75  class UsingDecl;
76  class UsingShadowDecl;
77  class UnresolvedSetIterator;
78
79  namespace Builtin { class Context; }
80
81/// ASTContext - This class holds long-lived AST nodes (such as types and
82/// decls) that can be referred to throughout the semantic analysis of a file.
83class ASTContext : public llvm::RefCountedBase<ASTContext> {
84  ASTContext &this_() { return *this; }
85
86  mutable std::vector<Type*> Types;
87  mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
88  mutable llvm::FoldingSet<ComplexType> ComplexTypes;
89  mutable llvm::FoldingSet<PointerType> PointerTypes;
90  mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
91  mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
92  mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
93  mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
94  mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
95  mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
96  mutable std::vector<VariableArrayType*> VariableArrayTypes;
97  mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
98  mutable llvm::FoldingSet<DependentSizedExtVectorType>
99    DependentSizedExtVectorTypes;
100  mutable llvm::FoldingSet<VectorType> VectorTypes;
101  mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
102  mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
103    FunctionProtoTypes;
104  mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
105  mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
106  mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
107  mutable llvm::FoldingSet<SubstTemplateTypeParmType>
108    SubstTemplateTypeParmTypes;
109  mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
110    SubstTemplateTypeParmPackTypes;
111  mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
112    TemplateSpecializationTypes;
113  mutable llvm::FoldingSet<ParenType> ParenTypes;
114  mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
115  mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
116  mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
117                                     ASTContext&>
118    DependentTemplateSpecializationTypes;
119  llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
120  mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
121  mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
122  mutable llvm::FoldingSet<AutoType> AutoTypes;
123  mutable llvm::FoldingSet<AtomicType> AtomicTypes;
124  llvm::FoldingSet<AttributedType> AttributedTypes;
125
126  mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
127  mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
128  mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
129    SubstTemplateTemplateParms;
130  mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
131                                     ASTContext&>
132    SubstTemplateTemplateParmPacks;
133
134  /// \brief The set of nested name specifiers.
135  ///
136  /// This set is managed by the NestedNameSpecifier class.
137  mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
138  mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
139  friend class NestedNameSpecifier;
140
141  /// ASTRecordLayouts - A cache mapping from RecordDecls to ASTRecordLayouts.
142  ///  This is lazily created.  This is intentionally not serialized.
143  mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
144    ASTRecordLayouts;
145  mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
146    ObjCLayouts;
147
148  /// KeyFunctions - A cache mapping from CXXRecordDecls to key functions.
149  llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*> KeyFunctions;
150
151  /// \brief Mapping from ObjCContainers to their ObjCImplementations.
152  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
153
154  /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
155  /// interface.
156  llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
157
158  /// \brief Mapping from __block VarDecls to their copy initialization expr.
159  llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
160
161  /// \brief Mapping from class scope functions specialization to their
162  ///  template patterns.
163  llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
164    ClassScopeSpecializationPattern;
165
166  /// \brief Representation of a "canonical" template template parameter that
167  /// is used in canonical template names.
168  class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
169    TemplateTemplateParmDecl *Parm;
170
171  public:
172    CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
173      : Parm(Parm) { }
174
175    TemplateTemplateParmDecl *getParam() const { return Parm; }
176
177    void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
178
179    static void Profile(llvm::FoldingSetNodeID &ID,
180                        TemplateTemplateParmDecl *Parm);
181  };
182  mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
183    CanonTemplateTemplateParms;
184
185  TemplateTemplateParmDecl *
186    getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
187
188  /// \brief The typedef for the __int128_t type.
189  mutable TypedefDecl *Int128Decl;
190
191  /// \brief The typedef for the __uint128_t type.
192  mutable TypedefDecl *UInt128Decl;
193
194  /// BuiltinVaListType - built-in va list type.
195  /// This is initially null and set by Sema::LazilyCreateBuiltin when
196  /// a builtin that takes a valist is encountered.
197  QualType BuiltinVaListType;
198
199  /// \brief The typedef for the predefined 'id' type.
200  mutable TypedefDecl *ObjCIdDecl;
201
202  /// \brief The typedef for the predefined 'SEL' type.
203  mutable TypedefDecl *ObjCSelDecl;
204
205  /// \brief The typedef for the predefined 'Class' type.
206  mutable TypedefDecl *ObjCClassDecl;
207
208  /// \brief The typedef for the predefined 'Protocol' class in Objective-C.
209  mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
210
211  // Typedefs which may be provided defining the structure of Objective-C
212  // pseudo-builtins
213  QualType ObjCIdRedefinitionType;
214  QualType ObjCClassRedefinitionType;
215  QualType ObjCSelRedefinitionType;
216
217  QualType ObjCConstantStringType;
218  mutable RecordDecl *CFConstantStringTypeDecl;
219
220  /// \brief The typedef declaration for the Objective-C "instancetype" type.
221  TypedefDecl *ObjCInstanceTypeDecl;
222
223  /// \brief The type for the C FILE type.
224  TypeDecl *FILEDecl;
225
226  /// \brief The type for the C jmp_buf type.
227  TypeDecl *jmp_bufDecl;
228
229  /// \brief The type for the C sigjmp_buf type.
230  TypeDecl *sigjmp_bufDecl;
231
232  /// \brief The type for the C ucontext_t type.
233  TypeDecl *ucontext_tDecl;
234
235  /// \brief Type for the Block descriptor for Blocks CodeGen.
236  ///
237  /// Since this is only used for generation of debug info, it is not
238  /// serialized.
239  mutable RecordDecl *BlockDescriptorType;
240
241  /// \brief Type for the Block descriptor for Blocks CodeGen.
242  ///
243  /// Since this is only used for generation of debug info, it is not
244  /// serialized.
245  mutable RecordDecl *BlockDescriptorExtendedType;
246
247  /// \brief Declaration for the CUDA cudaConfigureCall function.
248  FunctionDecl *cudaConfigureCallDecl;
249
250  TypeSourceInfo NullTypeSourceInfo;
251
252  /// \brief Keeps track of all declaration attributes.
253  ///
254  /// Since so few decls have attrs, we keep them in a hash map instead of
255  /// wasting space in the Decl class.
256  llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
257
258  /// \brief Keeps track of the static data member templates from which
259  /// static data members of class template specializations were instantiated.
260  ///
261  /// This data structure stores the mapping from instantiations of static
262  /// data members to the static data member representations within the
263  /// class template from which they were instantiated along with the kind
264  /// of instantiation or specialization (a TemplateSpecializationKind - 1).
265  ///
266  /// Given the following example:
267  ///
268  /// \code
269  /// template<typename T>
270  /// struct X {
271  ///   static T value;
272  /// };
273  ///
274  /// template<typename T>
275  ///   T X<T>::value = T(17);
276  ///
277  /// int *x = &X<int>::value;
278  /// \endcode
279  ///
280  /// This mapping will contain an entry that maps from the VarDecl for
281  /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
282  /// class template X) and will be marked TSK_ImplicitInstantiation.
283  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>
284    InstantiatedFromStaticDataMember;
285
286  /// \brief Keeps track of the declaration from which a UsingDecl was
287  /// created during instantiation.  The source declaration is always
288  /// a UsingDecl, an UnresolvedUsingValueDecl, or an
289  /// UnresolvedUsingTypenameDecl.
290  ///
291  /// For example:
292  /// \code
293  /// template<typename T>
294  /// struct A {
295  ///   void f();
296  /// };
297  ///
298  /// template<typename T>
299  /// struct B : A<T> {
300  ///   using A<T>::f;
301  /// };
302  ///
303  /// template struct B<int>;
304  /// \endcode
305  ///
306  /// This mapping will contain an entry that maps from the UsingDecl in
307  /// B<int> to the UnresolvedUsingDecl in B<T>.
308  llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
309
310  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
311    InstantiatedFromUsingShadowDecl;
312
313  llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
314
315  /// \brief Mapping that stores the methods overridden by a given C++
316  /// member function.
317  ///
318  /// Since most C++ member functions aren't virtual and therefore
319  /// don't override anything, we store the overridden functions in
320  /// this map on the side rather than within the CXXMethodDecl structure.
321  typedef UsuallyTinyPtrVector<const CXXMethodDecl> CXXMethodVector;
322  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
323
324  /// \brief Mapping that stores parameterIndex values for ParmVarDecls
325  /// when that value exceeds the bitfield size of
326  /// ParmVarDeclBits.ParameterIndex.
327  typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
328  ParameterIndexTable ParamIndices;
329
330  ImportDecl *FirstLocalImport;
331  ImportDecl *LastLocalImport;
332
333  TranslationUnitDecl *TUDecl;
334
335  /// SourceMgr - The associated SourceManager object.
336  SourceManager &SourceMgr;
337
338  /// LangOpts - The language options used to create the AST associated with
339  ///  this ASTContext object.
340  LangOptions &LangOpts;
341
342  /// \brief The allocator used to create AST objects.
343  ///
344  /// AST objects are never destructed; rather, all memory associated with the
345  /// AST objects will be released when the ASTContext itself is destroyed.
346  mutable llvm::BumpPtrAllocator BumpAlloc;
347
348  /// \brief Allocator for partial diagnostics.
349  PartialDiagnostic::StorageAllocator DiagAllocator;
350
351  /// \brief The current C++ ABI.
352  llvm::OwningPtr<CXXABI> ABI;
353  CXXABI *createCXXABI(const TargetInfo &T);
354
355  /// \brief The logical -> physical address space map.
356  const LangAS::Map *AddrSpaceMap;
357
358  friend class ASTDeclReader;
359  friend class ASTReader;
360  friend class ASTWriter;
361
362  const TargetInfo *Target;
363  clang::PrintingPolicy PrintingPolicy;
364
365public:
366  IdentifierTable &Idents;
367  SelectorTable &Selectors;
368  Builtin::Context &BuiltinInfo;
369  mutable DeclarationNameTable DeclarationNames;
370  llvm::OwningPtr<ExternalASTSource> ExternalSource;
371  ASTMutationListener *Listener;
372
373  clang::PrintingPolicy getPrintingPolicy() const { return PrintingPolicy; }
374
375  void setPrintingPolicy(clang::PrintingPolicy Policy) {
376    PrintingPolicy = Policy;
377  }
378
379  SourceManager& getSourceManager() { return SourceMgr; }
380  const SourceManager& getSourceManager() const { return SourceMgr; }
381  void *Allocate(unsigned Size, unsigned Align = 8) const {
382    return BumpAlloc.Allocate(Size, Align);
383  }
384  void Deallocate(void *Ptr) const { }
385
386  /// Return the total amount of physical memory allocated for representing
387  /// AST nodes and type information.
388  size_t getASTAllocatedMemory() const {
389    return BumpAlloc.getTotalMemory();
390  }
391  /// Return the total memory used for various side tables.
392  size_t getSideTableAllocatedMemory() const;
393
394  PartialDiagnostic::StorageAllocator &getDiagAllocator() {
395    return DiagAllocator;
396  }
397
398  const TargetInfo &getTargetInfo() const { return *Target; }
399
400  const LangOptions& getLangOptions() const { return LangOpts; }
401
402  DiagnosticsEngine &getDiagnostics() const;
403
404  FullSourceLoc getFullLoc(SourceLocation Loc) const {
405    return FullSourceLoc(Loc,SourceMgr);
406  }
407
408  /// \brief Retrieve the attributes for the given declaration.
409  AttrVec& getDeclAttrs(const Decl *D);
410
411  /// \brief Erase the attributes corresponding to the given declaration.
412  void eraseDeclAttrs(const Decl *D);
413
414  /// \brief If this variable is an instantiated static data member of a
415  /// class template specialization, returns the templated static data member
416  /// from which it was instantiated.
417  MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
418                                                           const VarDecl *Var);
419
420  FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
421
422  void setClassScopeSpecializationPattern(FunctionDecl *FD,
423                                          FunctionDecl *Pattern);
424
425  /// \brief Note that the static data member \p Inst is an instantiation of
426  /// the static data member template \p Tmpl of a class template.
427  void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
428                                           TemplateSpecializationKind TSK,
429                        SourceLocation PointOfInstantiation = SourceLocation());
430
431  /// \brief If the given using decl is an instantiation of a
432  /// (possibly unresolved) using decl from a template instantiation,
433  /// return it.
434  NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
435
436  /// \brief Remember that the using decl \p Inst is an instantiation
437  /// of the using decl \p Pattern of a class template.
438  void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
439
440  void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
441                                          UsingShadowDecl *Pattern);
442  UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
443
444  FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
445
446  void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
447
448  /// ZeroBitfieldFollowsNonBitfield - return 'true" if 'FD' is a zero-length
449  /// bitfield which follows the non-bitfield 'LastFD'.
450  bool ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
451                                      const FieldDecl *LastFD) const;
452
453  /// ZeroBitfieldFollowsBitfield - return 'true" if 'FD' is a zero-length
454  /// bitfield which follows the bitfield 'LastFD'.
455  bool ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
456                                   const FieldDecl *LastFD) const;
457
458  /// BitfieldFollowsBitfield - return 'true" if 'FD' is a
459  /// bitfield which follows the bitfield 'LastFD'.
460  bool BitfieldFollowsBitfield(const FieldDecl *FD,
461                               const FieldDecl *LastFD) const;
462
463  /// NonBitfieldFollowsBitfield - return 'true" if 'FD' is not a
464  /// bitfield which follows the bitfield 'LastFD'.
465  bool NonBitfieldFollowsBitfield(const FieldDecl *FD,
466                                  const FieldDecl *LastFD) const;
467
468  /// BitfieldFollowsNonBitfield - return 'true" if 'FD' is a
469  /// bitfield which follows the none bitfield 'LastFD'.
470  bool BitfieldFollowsNonBitfield(const FieldDecl *FD,
471                                  const FieldDecl *LastFD) const;
472
473  // Access to the set of methods overridden by the given C++ method.
474  typedef CXXMethodVector::iterator overridden_cxx_method_iterator;
475  overridden_cxx_method_iterator
476  overridden_methods_begin(const CXXMethodDecl *Method) const;
477
478  overridden_cxx_method_iterator
479  overridden_methods_end(const CXXMethodDecl *Method) const;
480
481  unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
482
483  /// \brief Note that the given C++ \p Method overrides the given \p
484  /// Overridden method.
485  void addOverriddenMethod(const CXXMethodDecl *Method,
486                           const CXXMethodDecl *Overridden);
487
488  /// \brief Notify the AST context that a new import declaration has been
489  /// parsed or implicitly created within this translation unit.
490  void addedLocalImportDecl(ImportDecl *Import);
491
492  static ImportDecl *getNextLocalImport(ImportDecl *Import) {
493    return Import->NextLocalImport;
494  }
495
496  /// \brief Iterator that visits import declarations.
497  class import_iterator {
498    ImportDecl *Import;
499
500  public:
501    typedef ImportDecl               *value_type;
502    typedef ImportDecl               *reference;
503    typedef ImportDecl               *pointer;
504    typedef int                       difference_type;
505    typedef std::forward_iterator_tag iterator_category;
506
507    import_iterator() : Import() { }
508    explicit import_iterator(ImportDecl *Import) : Import(Import) { }
509
510    reference operator*() const { return Import; }
511    pointer operator->() const { return Import; }
512
513    import_iterator &operator++() {
514      Import = ASTContext::getNextLocalImport(Import);
515      return *this;
516    }
517
518    import_iterator operator++(int) {
519      import_iterator Other(*this);
520      ++(*this);
521      return Other;
522    }
523
524    friend bool operator==(import_iterator X, import_iterator Y) {
525      return X.Import == Y.Import;
526    }
527
528    friend bool operator!=(import_iterator X, import_iterator Y) {
529      return X.Import != Y.Import;
530    }
531  };
532
533  import_iterator local_import_begin() const {
534    return import_iterator(FirstLocalImport);
535  }
536  import_iterator local_import_end() const { return import_iterator(); }
537
538  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
539
540
541  // Builtin Types.
542  CanQualType VoidTy;
543  CanQualType BoolTy;
544  CanQualType CharTy;
545  CanQualType WCharTy;  // [C++ 3.9.1p5], integer type in C99.
546  CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
547  CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
548  CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
549  CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
550  CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
551  CanQualType FloatTy, DoubleTy, LongDoubleTy;
552  CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
553  CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
554  CanQualType VoidPtrTy, NullPtrTy;
555  CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
556  CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
557  CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
558
559  // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
560  mutable QualType AutoDeductTy;     // Deduction against 'auto'.
561  mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
562
563  ASTContext(LangOptions& LOpts, SourceManager &SM, const TargetInfo *t,
564             IdentifierTable &idents, SelectorTable &sels,
565             Builtin::Context &builtins,
566             unsigned size_reserve,
567             bool DelayInitialization = false);
568
569  ~ASTContext();
570
571  /// \brief Attach an external AST source to the AST context.
572  ///
573  /// The external AST source provides the ability to load parts of
574  /// the abstract syntax tree as needed from some external storage,
575  /// e.g., a precompiled header.
576  void setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source);
577
578  /// \brief Retrieve a pointer to the external AST source associated
579  /// with this AST context, if any.
580  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
581
582  /// \brief Attach an AST mutation listener to the AST context.
583  ///
584  /// The AST mutation listener provides the ability to track modifications to
585  /// the abstract syntax tree entities committed after they were initially
586  /// created.
587  void setASTMutationListener(ASTMutationListener *Listener) {
588    this->Listener = Listener;
589  }
590
591  /// \brief Retrieve a pointer to the AST mutation listener associated
592  /// with this AST context, if any.
593  ASTMutationListener *getASTMutationListener() const { return Listener; }
594
595  void PrintStats() const;
596  const std::vector<Type*>& getTypes() const { return Types; }
597
598  /// \brief Retrieve the declaration for the 128-bit signed integer type.
599  TypedefDecl *getInt128Decl() const;
600
601  /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
602  TypedefDecl *getUInt128Decl() const;
603
604  //===--------------------------------------------------------------------===//
605  //                           Type Constructors
606  //===--------------------------------------------------------------------===//
607
608private:
609  /// getExtQualType - Return a type with extended qualifiers.
610  QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
611
612  QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
613
614public:
615  /// getAddSpaceQualType - Return the uniqued reference to the type for an
616  /// address space qualified type with the specified type and address space.
617  /// The resulting type has a union of the qualifiers from T and the address
618  /// space. If T already has an address space specifier, it is silently
619  /// replaced.
620  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
621
622  /// getObjCGCQualType - Returns the uniqued reference to the type for an
623  /// objc gc qualified type. The retulting type has a union of the qualifiers
624  /// from T and the gc attribute.
625  QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
626
627  /// getRestrictType - Returns the uniqued reference to the type for a
628  /// 'restrict' qualified type.  The resulting type has a union of the
629  /// qualifiers from T and 'restrict'.
630  QualType getRestrictType(QualType T) const {
631    return T.withFastQualifiers(Qualifiers::Restrict);
632  }
633
634  /// getVolatileType - Returns the uniqued reference to the type for a
635  /// 'volatile' qualified type.  The resulting type has a union of the
636  /// qualifiers from T and 'volatile'.
637  QualType getVolatileType(QualType T) const {
638    return T.withFastQualifiers(Qualifiers::Volatile);
639  }
640
641  /// getConstType - Returns the uniqued reference to the type for a
642  /// 'const' qualified type.  The resulting type has a union of the
643  /// qualifiers from T and 'const'.
644  ///
645  /// It can be reasonably expected that this will always be
646  /// equivalent to calling T.withConst().
647  QualType getConstType(QualType T) const { return T.withConst(); }
648
649  /// adjustFunctionType - Change the ExtInfo on a function type.
650  const FunctionType *adjustFunctionType(const FunctionType *Fn,
651                                         FunctionType::ExtInfo EInfo);
652
653  /// getComplexType - Return the uniqued reference to the type for a complex
654  /// number with the specified element type.
655  QualType getComplexType(QualType T) const;
656  CanQualType getComplexType(CanQualType T) const {
657    return CanQualType::CreateUnsafe(getComplexType((QualType) T));
658  }
659
660  /// getPointerType - Return the uniqued reference to the type for a pointer to
661  /// the specified type.
662  QualType getPointerType(QualType T) const;
663  CanQualType getPointerType(CanQualType T) const {
664    return CanQualType::CreateUnsafe(getPointerType((QualType) T));
665  }
666
667  /// getAtomicType - Return the uniqued reference to the atomic type for
668  /// the specified type.
669  QualType getAtomicType(QualType T) const;
670
671  /// getBlockPointerType - Return the uniqued reference to the type for a block
672  /// of the specified type.
673  QualType getBlockPointerType(QualType T) const;
674
675  /// This gets the struct used to keep track of the descriptor for pointer to
676  /// blocks.
677  QualType getBlockDescriptorType() const;
678
679  /// This gets the struct used to keep track of the extended descriptor for
680  /// pointer to blocks.
681  QualType getBlockDescriptorExtendedType() const;
682
683  void setcudaConfigureCallDecl(FunctionDecl *FD) {
684    cudaConfigureCallDecl = FD;
685  }
686  FunctionDecl *getcudaConfigureCallDecl() {
687    return cudaConfigureCallDecl;
688  }
689
690  /// This builds the struct used for __block variables.
691  QualType BuildByRefType(StringRef DeclName, QualType Ty) const;
692
693  /// Returns true iff we need copy/dispose helpers for the given type.
694  bool BlockRequiresCopying(QualType Ty) const;
695
696  /// getLValueReferenceType - Return the uniqued reference to the type for an
697  /// lvalue reference to the specified type.
698  QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
699    const;
700
701  /// getRValueReferenceType - Return the uniqued reference to the type for an
702  /// rvalue reference to the specified type.
703  QualType getRValueReferenceType(QualType T) const;
704
705  /// getMemberPointerType - Return the uniqued reference to the type for a
706  /// member pointer to the specified type in the specified class. The class
707  /// is a Type because it could be a dependent name.
708  QualType getMemberPointerType(QualType T, const Type *Cls) const;
709
710  /// getVariableArrayType - Returns a non-unique reference to the type for a
711  /// variable array of the specified element type.
712  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
713                                ArrayType::ArraySizeModifier ASM,
714                                unsigned IndexTypeQuals,
715                                SourceRange Brackets) const;
716
717  /// getDependentSizedArrayType - Returns a non-unique reference to
718  /// the type for a dependently-sized array of the specified element
719  /// type. FIXME: We will need these to be uniqued, or at least
720  /// comparable, at some point.
721  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
722                                      ArrayType::ArraySizeModifier ASM,
723                                      unsigned IndexTypeQuals,
724                                      SourceRange Brackets) const;
725
726  /// getIncompleteArrayType - Returns a unique reference to the type for a
727  /// incomplete array of the specified element type.
728  QualType getIncompleteArrayType(QualType EltTy,
729                                  ArrayType::ArraySizeModifier ASM,
730                                  unsigned IndexTypeQuals) const;
731
732  /// getConstantArrayType - Return the unique reference to the type for a
733  /// constant array of the specified element type.
734  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
735                                ArrayType::ArraySizeModifier ASM,
736                                unsigned IndexTypeQuals) const;
737
738  /// getVariableArrayDecayedType - Returns a vla type where known sizes
739  /// are replaced with [*].
740  QualType getVariableArrayDecayedType(QualType Ty) const;
741
742  /// getVectorType - Return the unique reference to a vector type of
743  /// the specified element type and size. VectorType must be a built-in type.
744  QualType getVectorType(QualType VectorType, unsigned NumElts,
745                         VectorType::VectorKind VecKind) const;
746
747  /// getExtVectorType - Return the unique reference to an extended vector type
748  /// of the specified element type and size.  VectorType must be a built-in
749  /// type.
750  QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
751
752  /// getDependentSizedExtVectorType - Returns a non-unique reference to
753  /// the type for a dependently-sized vector of the specified element
754  /// type. FIXME: We will need these to be uniqued, or at least
755  /// comparable, at some point.
756  QualType getDependentSizedExtVectorType(QualType VectorType,
757                                          Expr *SizeExpr,
758                                          SourceLocation AttrLoc) const;
759
760  /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
761  ///
762  QualType getFunctionNoProtoType(QualType ResultTy,
763                                  const FunctionType::ExtInfo &Info) const;
764
765  QualType getFunctionNoProtoType(QualType ResultTy) const {
766    return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
767  }
768
769  /// getFunctionType - Return a normal function type with a typed
770  /// argument list.
771  QualType getFunctionType(QualType ResultTy,
772                           const QualType *Args, unsigned NumArgs,
773                           const FunctionProtoType::ExtProtoInfo &EPI) const;
774
775  /// getTypeDeclType - Return the unique reference to the type for
776  /// the specified type declaration.
777  QualType getTypeDeclType(const TypeDecl *Decl,
778                           const TypeDecl *PrevDecl = 0) const {
779    assert(Decl && "Passed null for Decl param");
780    if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
781
782    if (PrevDecl) {
783      assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
784      Decl->TypeForDecl = PrevDecl->TypeForDecl;
785      return QualType(PrevDecl->TypeForDecl, 0);
786    }
787
788    return getTypeDeclTypeSlow(Decl);
789  }
790
791  /// getTypedefType - Return the unique reference to the type for the
792  /// specified typedef-name decl.
793  QualType getTypedefType(const TypedefNameDecl *Decl,
794                          QualType Canon = QualType()) const;
795
796  QualType getRecordType(const RecordDecl *Decl) const;
797
798  QualType getEnumType(const EnumDecl *Decl) const;
799
800  QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
801
802  QualType getAttributedType(AttributedType::Kind attrKind,
803                             QualType modifiedType,
804                             QualType equivalentType);
805
806  QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
807                                        QualType Replacement) const;
808  QualType getSubstTemplateTypeParmPackType(
809                                          const TemplateTypeParmType *Replaced,
810                                            const TemplateArgument &ArgPack);
811
812  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
813                                   bool ParameterPack,
814                                   TemplateTypeParmDecl *ParmDecl = 0) const;
815
816  QualType getTemplateSpecializationType(TemplateName T,
817                                         const TemplateArgument *Args,
818                                         unsigned NumArgs,
819                                         QualType Canon = QualType()) const;
820
821  QualType getCanonicalTemplateSpecializationType(TemplateName T,
822                                                  const TemplateArgument *Args,
823                                                  unsigned NumArgs) const;
824
825  QualType getTemplateSpecializationType(TemplateName T,
826                                         const TemplateArgumentListInfo &Args,
827                                         QualType Canon = QualType()) const;
828
829  TypeSourceInfo *
830  getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
831                                    const TemplateArgumentListInfo &Args,
832                                    QualType Canon = QualType()) const;
833
834  QualType getParenType(QualType NamedType) const;
835
836  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
837                             NestedNameSpecifier *NNS,
838                             QualType NamedType) const;
839  QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
840                                NestedNameSpecifier *NNS,
841                                const IdentifierInfo *Name,
842                                QualType Canon = QualType()) const;
843
844  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
845                                                  NestedNameSpecifier *NNS,
846                                                  const IdentifierInfo *Name,
847                                    const TemplateArgumentListInfo &Args) const;
848  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
849                                                  NestedNameSpecifier *NNS,
850                                                  const IdentifierInfo *Name,
851                                                  unsigned NumArgs,
852                                            const TemplateArgument *Args) const;
853
854  QualType getPackExpansionType(QualType Pattern,
855                                llvm::Optional<unsigned> NumExpansions);
856
857  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
858                                ObjCInterfaceDecl *PrevDecl = 0) const;
859
860  QualType getObjCObjectType(QualType Base,
861                             ObjCProtocolDecl * const *Protocols,
862                             unsigned NumProtocols) const;
863
864  /// getObjCObjectPointerType - Return a ObjCObjectPointerType type
865  /// for the given ObjCObjectType.
866  QualType getObjCObjectPointerType(QualType OIT) const;
867
868  /// getTypeOfType - GCC extension.
869  QualType getTypeOfExprType(Expr *e) const;
870  QualType getTypeOfType(QualType t) const;
871
872  /// getDecltypeType - C++0x decltype.
873  QualType getDecltypeType(Expr *e) const;
874
875  /// getUnaryTransformType - unary type transforms
876  QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
877                                 UnaryTransformType::UTTKind UKind) const;
878
879  /// getAutoType - C++0x deduced auto type.
880  QualType getAutoType(QualType DeducedType) const;
881
882  /// getAutoDeductType - C++0x deduction pattern for 'auto' type.
883  QualType getAutoDeductType() const;
884
885  /// getAutoRRefDeductType - C++0x deduction pattern for 'auto &&' type.
886  QualType getAutoRRefDeductType() const;
887
888  /// getTagDeclType - Return the unique reference to the type for the
889  /// specified TagDecl (struct/union/class/enum) decl.
890  QualType getTagDeclType(const TagDecl *Decl) const;
891
892  /// getSizeType - Return the unique type for "size_t" (C99 7.17), defined
893  /// in <stddef.h>. The sizeof operator requires this (C99 6.5.3.4p4).
894  CanQualType getSizeType() const;
895
896  /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5),
897  /// defined in <stdint.h>.
898  CanQualType getIntMaxType() const;
899
900  /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5),
901  /// defined in <stdint.h>.
902  CanQualType getUIntMaxType() const;
903
904  /// getWCharType - In C++, this returns the unique wchar_t type.  In C99, this
905  /// returns a type compatible with the type defined in <stddef.h> as defined
906  /// by the target.
907  QualType getWCharType() const { return WCharTy; }
908
909  /// getSignedWCharType - Return the type of "signed wchar_t".
910  /// Used when in C++, as a GCC extension.
911  QualType getSignedWCharType() const;
912
913  /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
914  /// Used when in C++, as a GCC extension.
915  QualType getUnsignedWCharType() const;
916
917  /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
918  /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
919  QualType getPointerDiffType() const;
920
921  // getCFConstantStringType - Return the C structure type used to represent
922  // constant CFStrings.
923  QualType getCFConstantStringType() const;
924
925  /// Get the structure type used to representation CFStrings, or NULL
926  /// if it hasn't yet been built.
927  QualType getRawCFConstantStringType() const {
928    if (CFConstantStringTypeDecl)
929      return getTagDeclType(CFConstantStringTypeDecl);
930    return QualType();
931  }
932  void setCFConstantStringType(QualType T);
933
934  // This setter/getter represents the ObjC type for an NSConstantString.
935  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
936  QualType getObjCConstantStringInterface() const {
937    return ObjCConstantStringType;
938  }
939
940  /// \brief Retrieve the type that 'id' has been defined to, which may be
941  /// different from the built-in 'id' if 'id' has been typedef'd.
942  QualType getObjCIdRedefinitionType() const {
943    if (ObjCIdRedefinitionType.isNull())
944      return getObjCIdType();
945    return ObjCIdRedefinitionType;
946  }
947
948  /// \brief Set the user-written type that redefines 'id'.
949  void setObjCIdRedefinitionType(QualType RedefType) {
950    ObjCIdRedefinitionType = RedefType;
951  }
952
953  /// \brief Retrieve the type that 'Class' has been defined to, which may be
954  /// different from the built-in 'Class' if 'Class' has been typedef'd.
955  QualType getObjCClassRedefinitionType() const {
956    if (ObjCClassRedefinitionType.isNull())
957      return getObjCClassType();
958    return ObjCClassRedefinitionType;
959  }
960
961  /// \brief Set the user-written type that redefines 'SEL'.
962  void setObjCClassRedefinitionType(QualType RedefType) {
963    ObjCClassRedefinitionType = RedefType;
964  }
965
966  /// \brief Retrieve the type that 'SEL' has been defined to, which may be
967  /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
968  QualType getObjCSelRedefinitionType() const {
969    if (ObjCSelRedefinitionType.isNull())
970      return getObjCSelType();
971    return ObjCSelRedefinitionType;
972  }
973
974
975  /// \brief Set the user-written type that redefines 'SEL'.
976  void setObjCSelRedefinitionType(QualType RedefType) {
977    ObjCSelRedefinitionType = RedefType;
978  }
979
980  /// \brief Retrieve the Objective-C "instancetype" type, if already known;
981  /// otherwise, returns a NULL type;
982  QualType getObjCInstanceType() {
983    return getTypeDeclType(getObjCInstanceTypeDecl());
984  }
985
986  /// \brief Retrieve the typedef declaration corresponding to the Objective-C
987  /// "instancetype" type.
988  TypedefDecl *getObjCInstanceTypeDecl();
989
990  /// \brief Set the type for the C FILE type.
991  void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
992
993  /// \brief Retrieve the C FILE type.
994  QualType getFILEType() const {
995    if (FILEDecl)
996      return getTypeDeclType(FILEDecl);
997    return QualType();
998  }
999
1000  /// \brief Set the type for the C jmp_buf type.
1001  void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1002    this->jmp_bufDecl = jmp_bufDecl;
1003  }
1004
1005  /// \brief Retrieve the C jmp_buf type.
1006  QualType getjmp_bufType() const {
1007    if (jmp_bufDecl)
1008      return getTypeDeclType(jmp_bufDecl);
1009    return QualType();
1010  }
1011
1012  /// \brief Set the type for the C sigjmp_buf type.
1013  void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1014    this->sigjmp_bufDecl = sigjmp_bufDecl;
1015  }
1016
1017  /// \brief Retrieve the C sigjmp_buf type.
1018  QualType getsigjmp_bufType() const {
1019    if (sigjmp_bufDecl)
1020      return getTypeDeclType(sigjmp_bufDecl);
1021    return QualType();
1022  }
1023
1024  /// \brief Set the type for the C ucontext_t type.
1025  void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1026    this->ucontext_tDecl = ucontext_tDecl;
1027  }
1028
1029  /// \brief Retrieve the C ucontext_t type.
1030  QualType getucontext_tType() const {
1031    if (ucontext_tDecl)
1032      return getTypeDeclType(ucontext_tDecl);
1033    return QualType();
1034  }
1035
1036  /// \brief The result type of logical operations, '<', '>', '!=', etc.
1037  QualType getLogicalOperationType() const {
1038    return getLangOptions().CPlusPlus ? BoolTy : IntTy;
1039  }
1040
1041  /// getObjCEncodingForType - Emit the ObjC type encoding for the
1042  /// given type into \arg S. If \arg NameFields is specified then
1043  /// record field names are also encoded.
1044  void getObjCEncodingForType(QualType t, std::string &S,
1045                              const FieldDecl *Field=0) const;
1046
1047  void getLegacyIntegralTypeEncoding(QualType &t) const;
1048
1049  // Put the string version of type qualifiers into S.
1050  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1051                                       std::string &S) const;
1052
1053  /// getObjCEncodingForFunctionDecl - Returns the encoded type for this
1054  /// function.  This is in the same format as Objective-C method encodings.
1055  ///
1056  /// \returns true if an error occurred (e.g., because one of the parameter
1057  /// types is incomplete), false otherwise.
1058  bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1059
1060  /// getObjCEncodingForMethodDecl - Return the encoded type for this method
1061  /// declaration.
1062  ///
1063  /// \returns true if an error occurred (e.g., because one of the parameter
1064  /// types is incomplete), false otherwise.
1065  bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1066                                    bool Extended = false)
1067    const;
1068
1069  /// getObjCEncodingForBlock - Return the encoded type for this block
1070  /// declaration.
1071  std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1072
1073  /// getObjCEncodingForPropertyDecl - Return the encoded type for
1074  /// this method declaration. If non-NULL, Container must be either
1075  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1076  /// only be NULL when getting encodings for protocol properties.
1077  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1078                                      const Decl *Container,
1079                                      std::string &S) const;
1080
1081  bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1082                                      ObjCProtocolDecl *rProto) const;
1083
1084  /// getObjCEncodingTypeSize returns size of type for objective-c encoding
1085  /// purpose in characters.
1086  CharUnits getObjCEncodingTypeSize(QualType t) const;
1087
1088  /// \brief Retrieve the typedef corresponding to the predefined 'id' type
1089  /// in Objective-C.
1090  TypedefDecl *getObjCIdDecl() const;
1091
1092  /// This setter/getter represents the ObjC 'id' type. It is setup lazily, by
1093  /// Sema.  id is always a (typedef for a) pointer type, a pointer to a struct.
1094  QualType getObjCIdType() const {
1095    return getTypeDeclType(getObjCIdDecl());
1096  }
1097
1098  /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1099  /// in Objective-C.
1100  TypedefDecl *getObjCSelDecl() const;
1101
1102  /// \brief Retrieve the type that corresponds to the predefined Objective-C
1103  /// 'SEL' type.
1104  QualType getObjCSelType() const {
1105    return getTypeDeclType(getObjCSelDecl());
1106  }
1107
1108  /// \brief Retrieve the typedef declaration corresponding to the predefined
1109  /// Objective-C 'Class' type.
1110  TypedefDecl *getObjCClassDecl() const;
1111
1112  /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by
1113  /// Sema.  'Class' is always a (typedef for a) pointer type, a pointer to a
1114  /// struct.
1115  QualType getObjCClassType() const {
1116    return getTypeDeclType(getObjCClassDecl());
1117  }
1118
1119  /// \brief Retrieve the Objective-C class declaration corresponding to
1120  /// the predefined 'Protocol' class.
1121  ObjCInterfaceDecl *getObjCProtocolDecl() const;
1122
1123  /// \brief Retrieve the type of the Objective-C "Protocol" class.
1124  QualType getObjCProtoType() const {
1125    return getObjCInterfaceType(getObjCProtocolDecl());
1126  }
1127
1128  void setBuiltinVaListType(QualType T);
1129  QualType getBuiltinVaListType() const { return BuiltinVaListType; }
1130
1131  /// getCVRQualifiedType - Returns a type with additional const,
1132  /// volatile, or restrict qualifiers.
1133  QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1134    return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1135  }
1136
1137  /// getQualifiedType - Returns a type with additional qualifiers.
1138  QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1139    if (!Qs.hasNonFastQualifiers())
1140      return T.withFastQualifiers(Qs.getFastQualifiers());
1141    QualifierCollector Qc(Qs);
1142    const Type *Ptr = Qc.strip(T);
1143    return getExtQualType(Ptr, Qc);
1144  }
1145
1146  /// getQualifiedType - Returns a type with additional qualifiers.
1147  QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1148    if (!Qs.hasNonFastQualifiers())
1149      return QualType(T, Qs.getFastQualifiers());
1150    return getExtQualType(T, Qs);
1151  }
1152
1153  /// getLifetimeQualifiedType - Returns a type with the given
1154  /// lifetime qualifier.
1155  QualType getLifetimeQualifiedType(QualType type,
1156                                    Qualifiers::ObjCLifetime lifetime) {
1157    assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1158    assert(lifetime != Qualifiers::OCL_None);
1159
1160    Qualifiers qs;
1161    qs.addObjCLifetime(lifetime);
1162    return getQualifiedType(type, qs);
1163  }
1164
1165  DeclarationNameInfo getNameForTemplate(TemplateName Name,
1166                                         SourceLocation NameLoc) const;
1167
1168  TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1169                                         UnresolvedSetIterator End) const;
1170
1171  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1172                                        bool TemplateKeyword,
1173                                        TemplateDecl *Template) const;
1174
1175  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1176                                        const IdentifierInfo *Name) const;
1177  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1178                                        OverloadedOperatorKind Operator) const;
1179  TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1180                                            TemplateName replacement) const;
1181  TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1182                                        const TemplateArgument &ArgPack) const;
1183
1184  enum GetBuiltinTypeError {
1185    GE_None,              //< No error
1186    GE_Missing_stdio,     //< Missing a type from <stdio.h>
1187    GE_Missing_setjmp,    //< Missing a type from <setjmp.h>
1188    GE_Missing_ucontext   //< Missing a type from <ucontext.h>
1189  };
1190
1191  /// GetBuiltinType - Return the type for the specified builtin.  If
1192  /// IntegerConstantArgs is non-null, it is filled in with a bitmask of
1193  /// arguments to the builtin that are required to be integer constant
1194  /// expressions.
1195  QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1196                          unsigned *IntegerConstantArgs = 0) const;
1197
1198private:
1199  CanQualType getFromTargetType(unsigned Type) const;
1200
1201  //===--------------------------------------------------------------------===//
1202  //                         Type Predicates.
1203  //===--------------------------------------------------------------------===//
1204
1205public:
1206  /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
1207  /// garbage collection attribute.
1208  ///
1209  Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1210
1211  /// areCompatibleVectorTypes - Return true if the given vector types
1212  /// are of the same unqualified type or if they are equivalent to the same
1213  /// GCC vector type, ignoring whether they are target-specific (AltiVec or
1214  /// Neon) types.
1215  bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1216
1217  /// isObjCNSObjectType - Return true if this is an NSObject object with
1218  /// its NSObject attribute set.
1219  static bool isObjCNSObjectType(QualType Ty) {
1220    return Ty->isObjCNSObjectType();
1221  }
1222
1223  //===--------------------------------------------------------------------===//
1224  //                         Type Sizing and Analysis
1225  //===--------------------------------------------------------------------===//
1226
1227  /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1228  /// scalar floating point type.
1229  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1230
1231  /// getTypeInfo - Get the size and alignment of the specified complete type in
1232  /// bits.
1233  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T) const;
1234  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) const {
1235    return getTypeInfo(T.getTypePtr());
1236  }
1237
1238  /// getTypeSize - Return the size of the specified type, in bits.  This method
1239  /// does not work on incomplete types.
1240  uint64_t getTypeSize(QualType T) const {
1241    return getTypeInfo(T).first;
1242  }
1243  uint64_t getTypeSize(const Type *T) const {
1244    return getTypeInfo(T).first;
1245  }
1246
1247  /// getCharWidth - Return the size of the character type, in bits
1248  uint64_t getCharWidth() const {
1249    return getTypeSize(CharTy);
1250  }
1251
1252  /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1253  CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1254
1255  /// toBits - Convert a size in characters to a size in bits.
1256  int64_t toBits(CharUnits CharSize) const;
1257
1258  /// getTypeSizeInChars - Return the size of the specified type, in characters.
1259  /// This method does not work on incomplete types.
1260  CharUnits getTypeSizeInChars(QualType T) const;
1261  CharUnits getTypeSizeInChars(const Type *T) const;
1262
1263  /// getTypeAlign - Return the ABI-specified alignment of a type, in bits.
1264  /// This method does not work on incomplete types.
1265  unsigned getTypeAlign(QualType T) const {
1266    return getTypeInfo(T).second;
1267  }
1268  unsigned getTypeAlign(const Type *T) const {
1269    return getTypeInfo(T).second;
1270  }
1271
1272  /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1273  /// characters. This method does not work on incomplete types.
1274  CharUnits getTypeAlignInChars(QualType T) const;
1275  CharUnits getTypeAlignInChars(const Type *T) const;
1276
1277  std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1278  std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1279
1280  /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1281  /// type for the current target in bits.  This can be different than the ABI
1282  /// alignment in cases where it is beneficial for performance to overalign
1283  /// a data type.
1284  unsigned getPreferredTypeAlign(const Type *T) const;
1285
1286  /// getDeclAlign - Return a conservative estimate of the alignment of
1287  /// the specified decl.  Note that bitfields do not have a valid alignment, so
1288  /// this method will assert on them.
1289  /// If @p RefAsPointee, references are treated like their underlying type
1290  /// (for alignof), else they're treated like pointers (for CodeGen).
1291  CharUnits getDeclAlign(const Decl *D, bool RefAsPointee = false) const;
1292
1293  /// getASTRecordLayout - Get or compute information about the layout of the
1294  /// specified record (struct/union/class), which indicates its size and field
1295  /// position information.
1296  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1297
1298  /// getASTObjCInterfaceLayout - Get or compute information about the
1299  /// layout of the specified Objective-C interface.
1300  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1301    const;
1302
1303  void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS) const;
1304
1305  /// getASTObjCImplementationLayout - Get or compute information about
1306  /// the layout of the specified Objective-C implementation. This may
1307  /// differ from the interface if synthesized ivars are present.
1308  const ASTRecordLayout &
1309  getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1310
1311  /// getKeyFunction - Get the key function for the given record decl, or NULL
1312  /// if there isn't one.  The key function is, according to the Itanium C++ ABI
1313  /// section 5.2.3:
1314  ///
1315  /// ...the first non-pure virtual function that is not inline at the point
1316  /// of class definition.
1317  const CXXMethodDecl *getKeyFunction(const CXXRecordDecl *RD);
1318
1319  /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1320  uint64_t getFieldOffset(const ValueDecl *FD) const;
1321
1322  bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1323
1324  MangleContext *createMangleContext();
1325
1326  void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1327                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1328
1329  unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1330  void CollectInheritedProtocols(const Decl *CDecl,
1331                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1332
1333  //===--------------------------------------------------------------------===//
1334  //                            Type Operators
1335  //===--------------------------------------------------------------------===//
1336
1337  /// getCanonicalType - Return the canonical (structural) type corresponding to
1338  /// the specified potentially non-canonical type.  The non-canonical version
1339  /// of a type may have many "decorated" versions of types.  Decorators can
1340  /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1341  /// to be free of any of these, allowing two canonical types to be compared
1342  /// for exact equality with a simple pointer comparison.
1343  CanQualType getCanonicalType(QualType T) const {
1344    return CanQualType::CreateUnsafe(T.getCanonicalType());
1345  }
1346
1347  const Type *getCanonicalType(const Type *T) const {
1348    return T->getCanonicalTypeInternal().getTypePtr();
1349  }
1350
1351  /// getCanonicalParamType - Return the canonical parameter type
1352  /// corresponding to the specific potentially non-canonical one.
1353  /// Qualifiers are stripped off, functions are turned into function
1354  /// pointers, and arrays decay one level into pointers.
1355  CanQualType getCanonicalParamType(QualType T) const;
1356
1357  /// \brief Determine whether the given types are equivalent.
1358  bool hasSameType(QualType T1, QualType T2) const {
1359    return getCanonicalType(T1) == getCanonicalType(T2);
1360  }
1361
1362  /// \brief Returns this type as a completely-unqualified array type,
1363  /// capturing the qualifiers in Quals. This will remove the minimal amount of
1364  /// sugaring from the types, similar to the behavior of
1365  /// QualType::getUnqualifiedType().
1366  ///
1367  /// \param T is the qualified type, which may be an ArrayType
1368  ///
1369  /// \param Quals will receive the full set of qualifiers that were
1370  /// applied to the array.
1371  ///
1372  /// \returns if this is an array type, the completely unqualified array type
1373  /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1374  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1375
1376  /// \brief Determine whether the given types are equivalent after
1377  /// cvr-qualifiers have been removed.
1378  bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
1379    return getCanonicalType(T1).getTypePtr() ==
1380           getCanonicalType(T2).getTypePtr();
1381  }
1382
1383  bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1384
1385  /// \brief Retrieves the "canonical" nested name specifier for a
1386  /// given nested name specifier.
1387  ///
1388  /// The canonical nested name specifier is a nested name specifier
1389  /// that uniquely identifies a type or namespace within the type
1390  /// system. For example, given:
1391  ///
1392  /// \code
1393  /// namespace N {
1394  ///   struct S {
1395  ///     template<typename T> struct X { typename T* type; };
1396  ///   };
1397  /// }
1398  ///
1399  /// template<typename T> struct Y {
1400  ///   typename N::S::X<T>::type member;
1401  /// };
1402  /// \endcode
1403  ///
1404  /// Here, the nested-name-specifier for N::S::X<T>:: will be
1405  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1406  /// by declarations in the type system and the canonical type for
1407  /// the template type parameter 'T' is template-param-0-0.
1408  NestedNameSpecifier *
1409  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
1410
1411  /// \brief Retrieves the default calling convention to use for
1412  /// C++ instance methods.
1413  CallingConv getDefaultMethodCallConv();
1414
1415  /// \brief Retrieves the canonical representation of the given
1416  /// calling convention.
1417  CallingConv getCanonicalCallConv(CallingConv CC) const {
1418    if (!LangOpts.MRTD && CC == CC_C)
1419      return CC_Default;
1420    return CC;
1421  }
1422
1423  /// \brief Determines whether two calling conventions name the same
1424  /// calling convention.
1425  bool isSameCallConv(CallingConv lcc, CallingConv rcc) {
1426    return (getCanonicalCallConv(lcc) == getCanonicalCallConv(rcc));
1427  }
1428
1429  /// \brief Retrieves the "canonical" template name that refers to a
1430  /// given template.
1431  ///
1432  /// The canonical template name is the simplest expression that can
1433  /// be used to refer to a given template. For most templates, this
1434  /// expression is just the template declaration itself. For example,
1435  /// the template std::vector can be referred to via a variety of
1436  /// names---std::vector, ::std::vector, vector (if vector is in
1437  /// scope), etc.---but all of these names map down to the same
1438  /// TemplateDecl, which is used to form the canonical template name.
1439  ///
1440  /// Dependent template names are more interesting. Here, the
1441  /// template name could be something like T::template apply or
1442  /// std::allocator<T>::template rebind, where the nested name
1443  /// specifier itself is dependent. In this case, the canonical
1444  /// template name uses the shortest form of the dependent
1445  /// nested-name-specifier, which itself contains all canonical
1446  /// types, values, and templates.
1447  TemplateName getCanonicalTemplateName(TemplateName Name) const;
1448
1449  /// \brief Determine whether the given template names refer to the same
1450  /// template.
1451  bool hasSameTemplateName(TemplateName X, TemplateName Y);
1452
1453  /// \brief Retrieve the "canonical" template argument.
1454  ///
1455  /// The canonical template argument is the simplest template argument
1456  /// (which may be a type, value, expression, or declaration) that
1457  /// expresses the value of the argument.
1458  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
1459    const;
1460
1461  /// Type Query functions.  If the type is an instance of the specified class,
1462  /// return the Type pointer for the underlying maximally pretty type.  This
1463  /// is a member of ASTContext because this may need to do some amount of
1464  /// canonicalization, e.g. to move type qualifiers into the element type.
1465  const ArrayType *getAsArrayType(QualType T) const;
1466  const ConstantArrayType *getAsConstantArrayType(QualType T) const {
1467    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1468  }
1469  const VariableArrayType *getAsVariableArrayType(QualType T) const {
1470    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1471  }
1472  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
1473    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1474  }
1475  const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
1476    const {
1477    return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1478  }
1479
1480  /// getBaseElementType - Returns the innermost element type of an array type.
1481  /// For example, will return "int" for int[m][n]
1482  QualType getBaseElementType(const ArrayType *VAT) const;
1483
1484  /// getBaseElementType - Returns the innermost element type of a type
1485  /// (which needn't actually be an array type).
1486  QualType getBaseElementType(QualType QT) const;
1487
1488  /// getConstantArrayElementCount - Returns number of constant array elements.
1489  uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1490
1491  /// \brief Perform adjustment on the parameter type of a function.
1492  ///
1493  /// This routine adjusts the given parameter type @p T to the actual
1494  /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
1495  /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
1496  QualType getAdjustedParameterType(QualType T);
1497
1498  /// \brief Retrieve the parameter type as adjusted for use in the signature
1499  /// of a function, decaying array and function types and removing top-level
1500  /// cv-qualifiers.
1501  QualType getSignatureParameterType(QualType T);
1502
1503  /// getArrayDecayedType - Return the properly qualified result of decaying the
1504  /// specified array type to a pointer.  This operation is non-trivial when
1505  /// handling typedefs etc.  The canonical type of "T" must be an array type,
1506  /// this returns a pointer to a properly qualified element of the array.
1507  ///
1508  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1509  QualType getArrayDecayedType(QualType T) const;
1510
1511  /// getPromotedIntegerType - Returns the type that Promotable will
1512  /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
1513  /// integer type.
1514  QualType getPromotedIntegerType(QualType PromotableType) const;
1515
1516  /// \brief Recurses in pointer/array types until it finds an objc retainable
1517  /// type and returns its ownership.
1518  Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
1519
1520  /// \brief Whether this is a promotable bitfield reference according
1521  /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1522  ///
1523  /// \returns the type this bit-field will promote to, or NULL if no
1524  /// promotion occurs.
1525  QualType isPromotableBitField(Expr *E) const;
1526
1527  /// getIntegerTypeOrder - Returns the highest ranked integer type:
1528  /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1529  /// LHS < RHS, return -1.
1530  int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
1531
1532  /// getFloatingTypeOrder - Compare the rank of the two specified floating
1533  /// point types, ignoring the domain of the type (i.e. 'double' ==
1534  /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1535  /// LHS < RHS, return -1.
1536  int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
1537
1538  /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1539  /// point or a complex type (based on typeDomain/typeSize).
1540  /// 'typeDomain' is a real floating point or complex type.
1541  /// 'typeSize' is a real floating point or complex type.
1542  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1543                                             QualType typeDomain) const;
1544
1545  unsigned getTargetAddressSpace(QualType T) const {
1546    return getTargetAddressSpace(T.getQualifiers());
1547  }
1548
1549  unsigned getTargetAddressSpace(Qualifiers Q) const {
1550    return getTargetAddressSpace(Q.getAddressSpace());
1551  }
1552
1553  unsigned getTargetAddressSpace(unsigned AS) const {
1554    if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
1555      return AS;
1556    else
1557      return (*AddrSpaceMap)[AS - LangAS::Offset];
1558  }
1559
1560private:
1561  // Helper for integer ordering
1562  unsigned getIntegerRank(const Type *T) const;
1563
1564public:
1565
1566  //===--------------------------------------------------------------------===//
1567  //                    Type Compatibility Predicates
1568  //===--------------------------------------------------------------------===//
1569
1570  /// Compatibility predicates used to check assignment expressions.
1571  bool typesAreCompatible(QualType T1, QualType T2,
1572                          bool CompareUnqualified = false); // C99 6.2.7p1
1573
1574  bool propertyTypesAreCompatible(QualType, QualType);
1575  bool typesAreBlockPointerCompatible(QualType, QualType);
1576
1577  bool isObjCIdType(QualType T) const {
1578    return T == getObjCIdType();
1579  }
1580  bool isObjCClassType(QualType T) const {
1581    return T == getObjCClassType();
1582  }
1583  bool isObjCSelType(QualType T) const {
1584    return T == getObjCSelType();
1585  }
1586  bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
1587  bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
1588                                         bool ForCompare);
1589
1590  bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
1591
1592  // Check the safety of assignment from LHS to RHS
1593  bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
1594                               const ObjCObjectPointerType *RHSOPT);
1595  bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
1596                               const ObjCObjectType *RHS);
1597  bool canAssignObjCInterfacesInBlockPointer(
1598                                          const ObjCObjectPointerType *LHSOPT,
1599                                          const ObjCObjectPointerType *RHSOPT,
1600                                          bool BlockReturnType);
1601  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
1602  QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
1603                                   const ObjCObjectPointerType *RHSOPT);
1604  bool canBindObjCObjectType(QualType To, QualType From);
1605
1606  // Functions for calculating composite types
1607  QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
1608                      bool Unqualified = false, bool BlockReturnType = false);
1609  QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
1610                              bool Unqualified = false);
1611  QualType mergeFunctionArgumentTypes(QualType, QualType,
1612                                      bool OfBlockPointer=false,
1613                                      bool Unqualified = false);
1614  QualType mergeTransparentUnionType(QualType, QualType,
1615                                     bool OfBlockPointer=false,
1616                                     bool Unqualified = false);
1617
1618  QualType mergeObjCGCQualifiers(QualType, QualType);
1619
1620  bool FunctionTypesMatchOnNSConsumedAttrs(
1621         const FunctionProtoType *FromFunctionType,
1622         const FunctionProtoType *ToFunctionType);
1623
1624  void ResetObjCLayout(const ObjCContainerDecl *CD) {
1625    ObjCLayouts[CD] = 0;
1626  }
1627
1628  //===--------------------------------------------------------------------===//
1629  //                    Integer Predicates
1630  //===--------------------------------------------------------------------===//
1631
1632  // The width of an integer, as defined in C99 6.2.6.2. This is the number
1633  // of bits in an integer type excluding any padding bits.
1634  unsigned getIntWidth(QualType T) const;
1635
1636  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
1637  // unsigned integer type.  This method takes a signed type, and returns the
1638  // corresponding unsigned integer type.
1639  QualType getCorrespondingUnsignedType(QualType T);
1640
1641  //===--------------------------------------------------------------------===//
1642  //                    Type Iterators.
1643  //===--------------------------------------------------------------------===//
1644
1645  typedef std::vector<Type*>::iterator       type_iterator;
1646  typedef std::vector<Type*>::const_iterator const_type_iterator;
1647
1648  type_iterator types_begin() { return Types.begin(); }
1649  type_iterator types_end() { return Types.end(); }
1650  const_type_iterator types_begin() const { return Types.begin(); }
1651  const_type_iterator types_end() const { return Types.end(); }
1652
1653  //===--------------------------------------------------------------------===//
1654  //                    Integer Values
1655  //===--------------------------------------------------------------------===//
1656
1657  /// MakeIntValue - Make an APSInt of the appropriate width and
1658  /// signedness for the given \arg Value and integer \arg Type.
1659  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
1660    llvm::APSInt Res(getIntWidth(Type),
1661                     !Type->isSignedIntegerOrEnumerationType());
1662    Res = Value;
1663    return Res;
1664  }
1665
1666  /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1667  ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
1668  /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1669  ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
1670
1671  /// \brief returns true if there is at lease one @implementation in TU.
1672  bool AnyObjCImplementation() {
1673    return !ObjCImpls.empty();
1674  }
1675
1676  /// \brief Set the implementation of ObjCInterfaceDecl.
1677  void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1678                             ObjCImplementationDecl *ImplD);
1679  /// \brief Set the implementation of ObjCCategoryDecl.
1680  void setObjCImplementation(ObjCCategoryDecl *CatD,
1681                             ObjCCategoryImplDecl *ImplD);
1682
1683  /// \brief Get the duplicate declaration of a ObjCMethod in the same
1684  /// interface, or null if non exists.
1685  const ObjCMethodDecl *getObjCMethodRedeclaration(
1686                                               const ObjCMethodDecl *MD) const {
1687    llvm::DenseMap<const ObjCMethodDecl*, const ObjCMethodDecl*>::const_iterator
1688      I = ObjCMethodRedecls.find(MD);
1689    if (I == ObjCMethodRedecls.end())
1690      return 0;
1691    return I->second;
1692  }
1693
1694  void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
1695                                  const ObjCMethodDecl *Redecl) {
1696    ObjCMethodRedecls[MD] = Redecl;
1697  }
1698
1699  /// \brief Returns the objc interface that \arg ND belongs to if it is a
1700  /// objc method/property/ivar etc. that is part of an interface,
1701  /// otherwise returns null.
1702  ObjCInterfaceDecl *getObjContainingInterface(NamedDecl *ND) const;
1703
1704  /// \brief Set the copy inialization expression of a block var decl.
1705  void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
1706  /// \brief Get the copy initialization expression of VarDecl,or NULL if
1707  /// none exists.
1708  Expr *getBlockVarCopyInits(const VarDecl*VD);
1709
1710  /// \brief Allocate an uninitialized TypeSourceInfo.
1711  ///
1712  /// The caller should initialize the memory held by TypeSourceInfo using
1713  /// the TypeLoc wrappers.
1714  ///
1715  /// \param T the type that will be the basis for type source info. This type
1716  /// should refer to how the declarator was written in source code, not to
1717  /// what type semantic analysis resolved the declarator to.
1718  ///
1719  /// \param Size the size of the type info to create, or 0 if the size
1720  /// should be calculated based on the type.
1721  TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
1722
1723  /// \brief Allocate a TypeSourceInfo where all locations have been
1724  /// initialized to a given location, which defaults to the empty
1725  /// location.
1726  TypeSourceInfo *
1727  getTrivialTypeSourceInfo(QualType T,
1728                           SourceLocation Loc = SourceLocation()) const;
1729
1730  TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
1731
1732  /// \brief Add a deallocation callback that will be invoked when the
1733  /// ASTContext is destroyed.
1734  ///
1735  /// \brief Callback A callback function that will be invoked on destruction.
1736  ///
1737  /// \brief Data Pointer data that will be provided to the callback function
1738  /// when it is called.
1739  void AddDeallocation(void (*Callback)(void*), void *Data);
1740
1741  GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD);
1742  GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
1743
1744  /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
1745  /// lazily, only when used; this is only relevant for function or file scoped
1746  /// var definitions.
1747  ///
1748  /// \returns true if the function/var must be CodeGen'ed/deserialized even if
1749  /// it is not used.
1750  bool DeclMustBeEmitted(const Decl *D);
1751
1752
1753  /// \brief Used by ParmVarDecl to store on the side the
1754  /// index of the parameter when it exceeds the size of the normal bitfield.
1755  void setParameterIndex(const ParmVarDecl *D, unsigned index);
1756
1757  /// \brief Used by ParmVarDecl to retrieve on the side the
1758  /// index of the parameter when it exceeds the size of the normal bitfield.
1759  unsigned getParameterIndex(const ParmVarDecl *D) const;
1760
1761  //===--------------------------------------------------------------------===//
1762  //                    Statistics
1763  //===--------------------------------------------------------------------===//
1764
1765  /// \brief The number of implicitly-declared default constructors.
1766  static unsigned NumImplicitDefaultConstructors;
1767
1768  /// \brief The number of implicitly-declared default constructors for
1769  /// which declarations were built.
1770  static unsigned NumImplicitDefaultConstructorsDeclared;
1771
1772  /// \brief The number of implicitly-declared copy constructors.
1773  static unsigned NumImplicitCopyConstructors;
1774
1775  /// \brief The number of implicitly-declared copy constructors for
1776  /// which declarations were built.
1777  static unsigned NumImplicitCopyConstructorsDeclared;
1778
1779  /// \brief The number of implicitly-declared move constructors.
1780  static unsigned NumImplicitMoveConstructors;
1781
1782  /// \brief The number of implicitly-declared move constructors for
1783  /// which declarations were built.
1784  static unsigned NumImplicitMoveConstructorsDeclared;
1785
1786  /// \brief The number of implicitly-declared copy assignment operators.
1787  static unsigned NumImplicitCopyAssignmentOperators;
1788
1789  /// \brief The number of implicitly-declared copy assignment operators for
1790  /// which declarations were built.
1791  static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
1792
1793  /// \brief The number of implicitly-declared move assignment operators.
1794  static unsigned NumImplicitMoveAssignmentOperators;
1795
1796  /// \brief The number of implicitly-declared move assignment operators for
1797  /// which declarations were built.
1798  static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
1799
1800  /// \brief The number of implicitly-declared destructors.
1801  static unsigned NumImplicitDestructors;
1802
1803  /// \brief The number of implicitly-declared destructors for which
1804  /// declarations were built.
1805  static unsigned NumImplicitDestructorsDeclared;
1806
1807private:
1808  ASTContext(const ASTContext&); // DO NOT IMPLEMENT
1809  void operator=(const ASTContext&); // DO NOT IMPLEMENT
1810
1811public:
1812  /// \brief Initialize built-in types.
1813  ///
1814  /// This routine may only be invoked once for a given ASTContext object.
1815  /// It is normally invoked by the ASTContext constructor. However, the
1816  /// constructor can be asked to delay initialization, which places the burden
1817  /// of calling this function on the user of that object.
1818  ///
1819  /// \param Target The target
1820  void InitBuiltinTypes(const TargetInfo &Target);
1821
1822private:
1823  void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
1824
1825  // Return the ObjC type encoding for a given type.
1826  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
1827                                  bool ExpandPointedToStructures,
1828                                  bool ExpandStructures,
1829                                  const FieldDecl *Field,
1830                                  bool OutermostType = false,
1831                                  bool EncodingProperty = false,
1832                                  bool StructField = false,
1833                                  bool EncodeBlockParameters = false,
1834                                  bool EncodeClassNames = false) const;
1835
1836  // Adds the encoding of the structure's members.
1837  void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
1838                                       const FieldDecl *Field,
1839                                       bool includeVBases = true) const;
1840
1841  // Adds the encoding of a method parameter or return type.
1842  void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
1843                                         QualType T, std::string& S,
1844                                         bool Extended) const;
1845
1846  const ASTRecordLayout &
1847  getObjCLayout(const ObjCInterfaceDecl *D,
1848                const ObjCImplementationDecl *Impl) const;
1849
1850private:
1851  /// \brief A set of deallocations that should be performed when the
1852  /// ASTContext is destroyed.
1853  SmallVector<std::pair<void (*)(void*), void *>, 16> Deallocations;
1854
1855  // FIXME: This currently contains the set of StoredDeclMaps used
1856  // by DeclContext objects.  This probably should not be in ASTContext,
1857  // but we include it here so that ASTContext can quickly deallocate them.
1858  llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
1859
1860  /// \brief A counter used to uniquely identify "blocks".
1861  mutable unsigned int UniqueBlockByRefTypeID;
1862
1863  friend class DeclContext;
1864  friend class DeclarationNameTable;
1865  void ReleaseDeclContextMaps();
1866};
1867
1868/// @brief Utility function for constructing a nullary selector.
1869static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
1870  IdentifierInfo* II = &Ctx.Idents.get(name);
1871  return Ctx.Selectors.getSelector(0, &II);
1872}
1873
1874/// @brief Utility function for constructing an unary selector.
1875static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
1876  IdentifierInfo* II = &Ctx.Idents.get(name);
1877  return Ctx.Selectors.getSelector(1, &II);
1878}
1879
1880}  // end namespace clang
1881
1882// operator new and delete aren't allowed inside namespaces.
1883// The throw specifications are mandated by the standard.
1884/// @brief Placement new for using the ASTContext's allocator.
1885///
1886/// This placement form of operator new uses the ASTContext's allocator for
1887/// obtaining memory. It is a non-throwing new, which means that it returns
1888/// null on error. (If that is what the allocator does. The current does, so if
1889/// this ever changes, this operator will have to be changed, too.)
1890/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
1891/// @code
1892/// // Default alignment (8)
1893/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
1894/// // Specific alignment
1895/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
1896/// @endcode
1897/// Please note that you cannot use delete on the pointer; it must be
1898/// deallocated using an explicit destructor call followed by
1899/// @c Context.Deallocate(Ptr).
1900///
1901/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
1902/// @param C The ASTContext that provides the allocator.
1903/// @param Alignment The alignment of the allocated memory (if the underlying
1904///                  allocator supports it).
1905/// @return The allocated memory. Could be NULL.
1906inline void *operator new(size_t Bytes, const clang::ASTContext &C,
1907                          size_t Alignment) throw () {
1908  return C.Allocate(Bytes, Alignment);
1909}
1910/// @brief Placement delete companion to the new above.
1911///
1912/// This operator is just a companion to the new above. There is no way of
1913/// invoking it directly; see the new operator for more details. This operator
1914/// is called implicitly by the compiler if a placement new expression using
1915/// the ASTContext throws in the object constructor.
1916inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t)
1917              throw () {
1918  C.Deallocate(Ptr);
1919}
1920
1921/// This placement form of operator new[] uses the ASTContext's allocator for
1922/// obtaining memory. It is a non-throwing new[], which means that it returns
1923/// null on error.
1924/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
1925/// @code
1926/// // Default alignment (8)
1927/// char *data = new (Context) char[10];
1928/// // Specific alignment
1929/// char *data = new (Context, 4) char[10];
1930/// @endcode
1931/// Please note that you cannot use delete on the pointer; it must be
1932/// deallocated using an explicit destructor call followed by
1933/// @c Context.Deallocate(Ptr).
1934///
1935/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
1936/// @param C The ASTContext that provides the allocator.
1937/// @param Alignment The alignment of the allocated memory (if the underlying
1938///                  allocator supports it).
1939/// @return The allocated memory. Could be NULL.
1940inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
1941                            size_t Alignment = 8) throw () {
1942  return C.Allocate(Bytes, Alignment);
1943}
1944
1945/// @brief Placement delete[] companion to the new[] above.
1946///
1947/// This operator is just a companion to the new[] above. There is no way of
1948/// invoking it directly; see the new[] operator for more details. This operator
1949/// is called implicitly by the compiler if a placement new[] expression using
1950/// the ASTContext throws in the object constructor.
1951inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t)
1952              throw () {
1953  C.Deallocate(Ptr);
1954}
1955
1956#endif
1957