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