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