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