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