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