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