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