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