ASTContext.h revision 8a1d722f13df383600f36d77f842957c8adb5f1b
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/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/PrettyPrinter.h"
23#include "clang/AST/TemplateName.h"
24#include "clang/AST/Type.h"
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/FoldingSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/Support/Allocator.h"
29#include <vector>
30
31namespace llvm {
32  struct fltSemantics;
33}
34
35namespace clang {
36  class FileManager;
37  class ASTRecordLayout;
38  class Expr;
39  class ExternalASTSource;
40  class IdentifierTable;
41  class SelectorTable;
42  class SourceManager;
43  class TargetInfo;
44  // Decls
45  class Decl;
46  class ObjCPropertyDecl;
47  class RecordDecl;
48  class TagDecl;
49  class TranslationUnitDecl;
50  class TypeDecl;
51  class TypedefDecl;
52  class TemplateTypeParmDecl;
53  class FieldDecl;
54  class ObjCIvarRefExpr;
55  class ObjCIvarDecl;
56
57  namespace Builtin { class Context; }
58
59/// ASTContext - This class holds long-lived AST nodes (such as types and
60/// decls) that can be referred to throughout the semantic analysis of a file.
61class ASTContext {
62  std::vector<Type*> Types;
63  llvm::FoldingSet<ExtQualType> ExtQualTypes;
64  llvm::FoldingSet<ComplexType> ComplexTypes;
65  llvm::FoldingSet<PointerType> PointerTypes;
66  llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
67  llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
68  llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
69  llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
70  llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
71  llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
72  std::vector<VariableArrayType*> VariableArrayTypes;
73  std::vector<DependentSizedArrayType*> DependentSizedArrayTypes;
74  std::vector<DependentSizedExtVectorType*> DependentSizedExtVectorTypes;
75  llvm::FoldingSet<VectorType> VectorTypes;
76  llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
77  llvm::FoldingSet<FunctionProtoType> FunctionProtoTypes;
78  llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
79  llvm::FoldingSet<TemplateSpecializationType> TemplateSpecializationTypes;
80  llvm::FoldingSet<QualifiedNameType> QualifiedNameTypes;
81  llvm::FoldingSet<TypenameType> TypenameTypes;
82  llvm::FoldingSet<ObjCInterfaceType> ObjCInterfaceTypes;
83  llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
84
85  llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
86  llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
87
88  /// \brief The set of nested name specifiers.
89  ///
90  /// This set is managed by the NestedNameSpecifier class.
91  llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
92  NestedNameSpecifier *GlobalNestedNameSpecifier;
93  friend class NestedNameSpecifier;
94
95  /// ASTRecordLayouts - A cache mapping from RecordDecls to ASTRecordLayouts.
96  ///  This is lazily created.  This is intentionally not serialized.
97  llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*> ASTRecordLayouts;
98  llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*> ObjCLayouts;
99
100  /// \brief Mapping from ObjCContainers to their ObjCImplementations.
101  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
102
103  llvm::DenseMap<unsigned, FixedWidthIntType*> SignedFixedWidthIntTypes;
104  llvm::DenseMap<unsigned, FixedWidthIntType*> UnsignedFixedWidthIntTypes;
105
106  /// BuiltinVaListType - built-in va list type.
107  /// This is initially null and set by Sema::LazilyCreateBuiltin when
108  /// a builtin that takes a valist is encountered.
109  QualType BuiltinVaListType;
110
111  /// ObjCIdType - a pseudo built-in typedef type (set by Sema).
112  QualType ObjCIdTypedefType;
113
114  /// ObjCSelType - another pseudo built-in typedef type (set by Sema).
115  QualType ObjCSelType;
116  const RecordType *SelStructType;
117
118  /// ObjCProtoType - another pseudo built-in typedef type (set by Sema).
119  QualType ObjCProtoType;
120  const RecordType *ProtoStructType;
121
122  /// ObjCClassType - another pseudo built-in typedef type (set by Sema).
123  QualType ObjCClassTypedefType;
124
125  QualType ObjCConstantStringType;
126  RecordDecl *CFConstantStringTypeDecl;
127
128  RecordDecl *ObjCFastEnumerationStateTypeDecl;
129
130  /// \brief The type for the C FILE type.
131  TypeDecl *FILEDecl;
132
133  /// \brief Keeps track of all declaration attributes.
134  ///
135  /// Since so few decls have attrs, we keep them in a hash map instead of
136  /// wasting space in the Decl class.
137  llvm::DenseMap<const Decl*, Attr*> DeclAttrs;
138
139  TranslationUnitDecl *TUDecl;
140
141  /// SourceMgr - The associated SourceManager object.
142  SourceManager &SourceMgr;
143
144  /// LangOpts - The language options used to create the AST associated with
145  ///  this ASTContext object.
146  LangOptions LangOpts;
147
148  /// \brief Whether we have already loaded comment source ranges from an
149  /// external source.
150  bool LoadedExternalComments;
151
152  /// MallocAlloc/BumpAlloc - The allocator objects used to create AST objects.
153  bool FreeMemory;
154  llvm::MallocAllocator MallocAlloc;
155  llvm::BumpPtrAllocator BumpAlloc;
156
157  /// \brief Mapping from declarations to their comments, once we have
158  /// already looked up the comment associated with a given declaration.
159  llvm::DenseMap<const Decl *, std::string> DeclComments;
160
161public:
162  TargetInfo &Target;
163  IdentifierTable &Idents;
164  SelectorTable &Selectors;
165  Builtin::Context &BuiltinInfo;
166  DeclarationNameTable DeclarationNames;
167  llvm::OwningPtr<ExternalASTSource> ExternalSource;
168  clang::PrintingPolicy PrintingPolicy;
169
170  /// \brief Source ranges for all of the comments in the source file,
171  /// sorted in order of appearance in the translation unit.
172  std::vector<SourceRange> Comments;
173
174  SourceManager& getSourceManager() { return SourceMgr; }
175  const SourceManager& getSourceManager() const { return SourceMgr; }
176  void *Allocate(unsigned Size, unsigned Align = 8) {
177    return FreeMemory ? MallocAlloc.Allocate(Size, Align) :
178                        BumpAlloc.Allocate(Size, Align);
179  }
180  void Deallocate(void *Ptr) {
181    if (FreeMemory)
182      MallocAlloc.Deallocate(Ptr);
183  }
184  const LangOptions& getLangOptions() const { return LangOpts; }
185
186  FullSourceLoc getFullLoc(SourceLocation Loc) const {
187    return FullSourceLoc(Loc,SourceMgr);
188  }
189
190  /// \brief Retrieve the attributes for the given declaration.
191  Attr*& getDeclAttrs(const Decl *D) { return DeclAttrs[D]; }
192
193  /// \brief Erase the attributes corresponding to the given declaration.
194  void eraseDeclAttrs(const Decl *D) { DeclAttrs.erase(D); }
195
196  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
197
198  const char *getCommentForDecl(const Decl *D);
199
200  // Builtin Types.
201  QualType VoidTy;
202  QualType BoolTy;
203  QualType CharTy;
204  QualType WCharTy;  // [C++ 3.9.1p5], integer type in C99.
205  QualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
206  QualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
207  QualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
208  QualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
209  QualType UnsignedLongLongTy, UnsignedInt128Ty;
210  QualType FloatTy, DoubleTy, LongDoubleTy;
211  QualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
212  QualType VoidPtrTy, NullPtrTy;
213  QualType OverloadTy;
214  QualType DependentTy;
215  QualType UndeducedAutoTy;
216  QualType ObjCBuiltinIdTy, ObjCBuiltinClassTy;
217
218  ASTContext(const LangOptions& LOpts, SourceManager &SM, TargetInfo &t,
219             IdentifierTable &idents, SelectorTable &sels,
220             Builtin::Context &builtins,
221             bool FreeMemory = true, unsigned size_reserve=0);
222
223  ~ASTContext();
224
225  /// \brief Attach an external AST source to the AST context.
226  ///
227  /// The external AST source provides the ability to load parts of
228  /// the abstract syntax tree as needed from some external storage,
229  /// e.g., a precompiled header.
230  void setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source);
231
232  /// \brief Retrieve a pointer to the external AST source associated
233  /// with this AST context, if any.
234  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
235
236  void PrintStats() const;
237  const std::vector<Type*>& getTypes() const { return Types; }
238
239  //===--------------------------------------------------------------------===//
240  //                           Type Constructors
241  //===--------------------------------------------------------------------===//
242
243  /// getAddSpaceQualType - Return the uniqued reference to the type for an
244  /// address space qualified type with the specified type and address space.
245  /// The resulting type has a union of the qualifiers from T and the address
246  /// space. If T already has an address space specifier, it is silently
247  /// replaced.
248  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace);
249
250  /// getObjCGCQualType - Returns the uniqued reference to the type for an
251  /// objc gc qualified type. The retulting type has a union of the qualifiers
252  /// from T and the gc attribute.
253  QualType getObjCGCQualType(QualType T, QualType::GCAttrTypes gcAttr);
254
255  /// getComplexType - Return the uniqued reference to the type for a complex
256  /// number with the specified element type.
257  QualType getComplexType(QualType T);
258
259  /// getPointerType - Return the uniqued reference to the type for a pointer to
260  /// the specified type.
261  QualType getPointerType(QualType T);
262
263  /// getBlockPointerType - Return the uniqued reference to the type for a block
264  /// of the specified type.
265  QualType getBlockPointerType(QualType T);
266
267  /// getLValueReferenceType - Return the uniqued reference to the type for an
268  /// lvalue reference to the specified type.
269  QualType getLValueReferenceType(QualType T);
270
271  /// getRValueReferenceType - Return the uniqued reference to the type for an
272  /// rvalue reference to the specified type.
273  QualType getRValueReferenceType(QualType T);
274
275  /// getMemberPointerType - Return the uniqued reference to the type for a
276  /// member pointer to the specified type in the specified class. The class
277  /// is a Type because it could be a dependent name.
278  QualType getMemberPointerType(QualType T, const Type *Cls);
279
280  /// getVariableArrayType - Returns a non-unique reference to the type for a
281  /// variable array of the specified element type.
282  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
283                                ArrayType::ArraySizeModifier ASM,
284                                unsigned EltTypeQuals,
285                                SourceRange Brackets);
286
287  /// getDependentSizedArrayType - Returns a non-unique reference to
288  /// the type for a dependently-sized array of the specified element
289  /// type. FIXME: We will need these to be uniqued, or at least
290  /// comparable, at some point.
291  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
292                                      ArrayType::ArraySizeModifier ASM,
293                                      unsigned EltTypeQuals,
294                                      SourceRange Brackets);
295
296  /// getIncompleteArrayType - Returns a unique reference to the type for a
297  /// incomplete array of the specified element type.
298  QualType getIncompleteArrayType(QualType EltTy,
299                                  ArrayType::ArraySizeModifier ASM,
300                                  unsigned EltTypeQuals);
301
302  /// getConstantArrayType - Return the unique reference to the type for a
303  /// constant array of the specified element type.
304  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
305                                ArrayType::ArraySizeModifier ASM,
306                                unsigned EltTypeQuals);
307
308  /// getConstantArrayWithExprType - Return a reference to the type for a
309  /// constant array of the specified element type.
310  QualType getConstantArrayWithExprType(QualType EltTy,
311                                        const llvm::APInt &ArySize,
312                                        Expr *ArySizeExpr,
313                                        ArrayType::ArraySizeModifier ASM,
314                                        unsigned EltTypeQuals,
315                                        SourceRange Brackets);
316
317  /// getConstantArrayWithoutExprType - Return a reference to the type
318  /// for a constant array of the specified element type.
319  QualType getConstantArrayWithoutExprType(QualType EltTy,
320                                           const llvm::APInt &ArySize,
321                                           ArrayType::ArraySizeModifier ASM,
322                                           unsigned EltTypeQuals);
323
324  /// getVectorType - Return the unique reference to a vector type of
325  /// the specified element type and size. VectorType must be a built-in type.
326  QualType getVectorType(QualType VectorType, unsigned NumElts);
327
328  /// getExtVectorType - Return the unique reference to an extended vector type
329  /// of the specified element type and size.  VectorType must be a built-in
330  /// type.
331  QualType getExtVectorType(QualType VectorType, unsigned NumElts);
332
333  /// getDependentSizedExtVectorType - Returns a non-unique reference to
334  /// the type for a dependently-sized vector of the specified element
335  /// type. FIXME: We will need these to be uniqued, or at least
336  /// comparable, at some point.
337  QualType getDependentSizedExtVectorType(QualType VectorType,
338                                          Expr *SizeExpr,
339                                          SourceLocation AttrLoc);
340
341  /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
342  ///
343  QualType getFunctionNoProtoType(QualType ResultTy);
344
345  /// getFunctionType - Return a normal function type with a typed argument
346  /// list.  isVariadic indicates whether the argument list includes '...'.
347  QualType getFunctionType(QualType ResultTy, const QualType *ArgArray,
348                           unsigned NumArgs, bool isVariadic,
349                           unsigned TypeQuals, bool hasExceptionSpec = false,
350                           bool hasAnyExceptionSpec = false,
351                           unsigned NumExs = 0, const QualType *ExArray = 0);
352
353  /// getTypeDeclType - Return the unique reference to the type for
354  /// the specified type declaration.
355  QualType getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl=0);
356
357  /// getTypedefType - Return the unique reference to the type for the
358  /// specified typename decl.
359  QualType getTypedefType(TypedefDecl *Decl);
360
361  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
362                                   bool ParameterPack,
363                                   IdentifierInfo *Name = 0);
364
365  QualType getTemplateSpecializationType(TemplateName T,
366                                         const TemplateArgument *Args,
367                                         unsigned NumArgs,
368                                         QualType Canon = QualType());
369
370  QualType getQualifiedNameType(NestedNameSpecifier *NNS,
371                                QualType NamedType);
372  QualType getTypenameType(NestedNameSpecifier *NNS,
373                           const IdentifierInfo *Name,
374                           QualType Canon = QualType());
375  QualType getTypenameType(NestedNameSpecifier *NNS,
376                           const TemplateSpecializationType *TemplateId,
377                           QualType Canon = QualType());
378
379  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
380                                ObjCProtocolDecl **Protocols = 0,
381                                unsigned NumProtocols = 0);
382
383  /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for the
384  /// given interface decl and the conforming protocol list.
385  QualType getObjCObjectPointerType(QualType OIT,
386                                    ObjCProtocolDecl **ProtocolList = 0,
387                                    unsigned NumProtocols = 0);
388
389  /// getTypeOfType - GCC extension.
390  QualType getTypeOfExprType(Expr *e);
391  QualType getTypeOfType(QualType t);
392
393  /// getDecltypeType - C++0x decltype.
394  QualType getDecltypeType(Expr *e);
395
396  /// getTagDeclType - Return the unique reference to the type for the
397  /// specified TagDecl (struct/union/class/enum) decl.
398  QualType getTagDeclType(TagDecl *Decl);
399
400  /// getSizeType - Return the unique type for "size_t" (C99 7.17), defined
401  /// in <stddef.h>. The sizeof operator requires this (C99 6.5.3.4p4).
402  QualType getSizeType() const;
403
404  /// getWCharType - In C++, this returns the unique wchar_t type.  In C99, this
405  /// returns a type compatible with the type defined in <stddef.h> as defined
406  /// by the target.
407  QualType getWCharType() const { return WCharTy; }
408
409  /// getSignedWCharType - Return the type of "signed wchar_t".
410  /// Used when in C++, as a GCC extension.
411  QualType getSignedWCharType() const;
412
413  /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
414  /// Used when in C++, as a GCC extension.
415  QualType getUnsignedWCharType() const;
416
417  /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
418  /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
419  QualType getPointerDiffType() const;
420
421  // getCFConstantStringType - Return the C structure type used to represent
422  // constant CFStrings.
423  QualType getCFConstantStringType();
424
425  /// Get the structure type used to representation CFStrings, or NULL
426  /// if it hasn't yet been built.
427  QualType getRawCFConstantStringType() {
428    if (CFConstantStringTypeDecl)
429      return getTagDeclType(CFConstantStringTypeDecl);
430    return QualType();
431  }
432  void setCFConstantStringType(QualType T);
433
434  // This setter/getter represents the ObjC type for an NSConstantString.
435  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
436  QualType getObjCConstantStringInterface() const {
437    return ObjCConstantStringType;
438  }
439
440  //// This gets the struct used to keep track of fast enumerations.
441  QualType getObjCFastEnumerationStateType();
442
443  /// Get the ObjCFastEnumerationState type, or NULL if it hasn't yet
444  /// been built.
445  QualType getRawObjCFastEnumerationStateType() {
446    if (ObjCFastEnumerationStateTypeDecl)
447      return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
448    return QualType();
449  }
450
451  void setObjCFastEnumerationStateType(QualType T);
452
453  /// \brief Set the type for the C FILE type.
454  void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
455
456  /// \brief Retrieve the C FILE type.
457  QualType getFILEType() {
458    if (FILEDecl)
459      return getTypeDeclType(FILEDecl);
460    return QualType();
461  }
462
463  /// getObjCEncodingForType - Emit the ObjC type encoding for the
464  /// given type into \arg S. If \arg NameFields is specified then
465  /// record field names are also encoded.
466  void getObjCEncodingForType(QualType t, std::string &S,
467                              const FieldDecl *Field=0);
468
469  void getLegacyIntegralTypeEncoding(QualType &t) const;
470
471  // Put the string version of type qualifiers into S.
472  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
473                                       std::string &S) const;
474
475  /// getObjCEncodingForMethodDecl - Return the encoded type for this method
476  /// declaration.
477  void getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S);
478
479  /// getObjCEncodingForPropertyDecl - Return the encoded type for
480  /// this method declaration. If non-NULL, Container must be either
481  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
482  /// only be NULL when getting encodings for protocol properties.
483  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
484                                      const Decl *Container,
485                                      std::string &S);
486
487  /// getObjCEncodingTypeSize returns size of type for objective-c encoding
488  /// purpose.
489  int getObjCEncodingTypeSize(QualType t);
490
491  /// This setter/getter represents the ObjC 'id' type. It is setup lazily, by
492  /// Sema.  id is always a (typedef for a) pointer type, a pointer to a struct.
493  QualType getObjCIdType() const { return ObjCIdTypedefType; }
494  void setObjCIdType(QualType T);
495
496  void setObjCSelType(QualType T);
497  QualType getObjCSelType() const { return ObjCSelType; }
498
499  void setObjCProtoType(QualType QT);
500  QualType getObjCProtoType() const { return ObjCProtoType; }
501
502  /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by
503  /// Sema.  'Class' is always a (typedef for a) pointer type, a pointer to a
504  /// struct.
505  QualType getObjCClassType() const { return ObjCClassTypedefType; }
506  void setObjCClassType(QualType T);
507
508  void setBuiltinVaListType(QualType T);
509  QualType getBuiltinVaListType() const { return BuiltinVaListType; }
510
511  QualType getFixedWidthIntType(unsigned Width, bool Signed);
512
513  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
514                                        bool TemplateKeyword,
515                                        TemplateDecl *Template);
516
517  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
518                                        const IdentifierInfo *Name);
519
520  enum GetBuiltinTypeError {
521    GE_None,        //< No error
522    GE_Missing_FILE //< Missing the FILE type from <stdio.h>
523  };
524
525  /// GetBuiltinType - Return the type for the specified builtin.
526  QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error);
527
528private:
529  QualType getFromTargetType(unsigned Type) const;
530
531  //===--------------------------------------------------------------------===//
532  //                         Type Predicates.
533  //===--------------------------------------------------------------------===//
534
535public:
536  /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
537  /// garbage collection attribute.
538  ///
539  QualType::GCAttrTypes getObjCGCAttrKind(const QualType &Ty) const;
540
541  /// isObjCNSObjectType - Return true if this is an NSObject object with
542  /// its NSObject attribute set.
543  bool isObjCNSObjectType(QualType Ty) const;
544
545  //===--------------------------------------------------------------------===//
546  //                         Type Sizing and Analysis
547  //===--------------------------------------------------------------------===//
548
549  /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
550  /// scalar floating point type.
551  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
552
553  /// getTypeInfo - Get the size and alignment of the specified complete type in
554  /// bits.
555  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T);
556  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) {
557    return getTypeInfo(T.getTypePtr());
558  }
559
560  /// getTypeSize - Return the size of the specified type, in bits.  This method
561  /// does not work on incomplete types.
562  uint64_t getTypeSize(QualType T) {
563    return getTypeInfo(T).first;
564  }
565  uint64_t getTypeSize(const Type *T) {
566    return getTypeInfo(T).first;
567  }
568
569  /// getTypeAlign - Return the ABI-specified alignment of a type, in bits.
570  /// This method does not work on incomplete types.
571  unsigned getTypeAlign(QualType T) {
572    return getTypeInfo(T).second;
573  }
574  unsigned getTypeAlign(const Type *T) {
575    return getTypeInfo(T).second;
576  }
577
578  /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
579  /// type for the current target in bits.  This can be different than the ABI
580  /// alignment in cases where it is beneficial for performance to overalign
581  /// a data type.
582  unsigned getPreferredTypeAlign(const Type *T);
583
584  /// getDeclAlignInBytes - Return the alignment of the specified decl
585  /// that should be returned by __alignof().  Note that bitfields do
586  /// not have a valid alignment, so this method will assert on them.
587  unsigned getDeclAlignInBytes(const Decl *D);
588
589  /// getASTRecordLayout - Get or compute information about the layout of the
590  /// specified record (struct/union/class), which indicates its size and field
591  /// position information.
592  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D);
593
594  /// getASTObjCInterfaceLayout - Get or compute information about the
595  /// layout of the specified Objective-C interface.
596  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D);
597
598  /// getASTObjCImplementationLayout - Get or compute information about
599  /// the layout of the specified Objective-C implementation. This may
600  /// differ from the interface if synthesized ivars are present.
601  const ASTRecordLayout &
602  getASTObjCImplementationLayout(const ObjCImplementationDecl *D);
603
604  void CollectObjCIvars(const ObjCInterfaceDecl *OI,
605                        llvm::SmallVectorImpl<FieldDecl*> &Fields);
606
607  void ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
608                               llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
609                               bool CollectSynthesized = true);
610  void CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
611                               llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
612  void CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
613                               llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
614  unsigned CountSynthesizedIvars(const ObjCInterfaceDecl *OI);
615  unsigned CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD);
616
617  //===--------------------------------------------------------------------===//
618  //                            Type Operators
619  //===--------------------------------------------------------------------===//
620
621  /// getCanonicalType - Return the canonical (structural) type corresponding to
622  /// the specified potentially non-canonical type.  The non-canonical version
623  /// of a type may have many "decorated" versions of types.  Decorators can
624  /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
625  /// to be free of any of these, allowing two canonical types to be compared
626  /// for exact equality with a simple pointer comparison.
627  QualType getCanonicalType(QualType T);
628  const Type *getCanonicalType(const Type *T) {
629    return T->getCanonicalTypeInternal().getTypePtr();
630  }
631
632  /// \brief Determine whether the given types are equivalent.
633  bool hasSameType(QualType T1, QualType T2) {
634    return getCanonicalType(T1) == getCanonicalType(T2);
635  }
636
637  /// \brief Determine whether the given types are equivalent after
638  /// cvr-qualifiers have been removed.
639  bool hasSameUnqualifiedType(QualType T1, QualType T2) {
640    T1 = getCanonicalType(T1);
641    T2 = getCanonicalType(T2);
642    return T1.getUnqualifiedType() == T2.getUnqualifiedType();
643  }
644
645  /// \brief Retrieves the "canonical" declaration of
646
647  /// \brief Retrieves the "canonical" nested name specifier for a
648  /// given nested name specifier.
649  ///
650  /// The canonical nested name specifier is a nested name specifier
651  /// that uniquely identifies a type or namespace within the type
652  /// system. For example, given:
653  ///
654  /// \code
655  /// namespace N {
656  ///   struct S {
657  ///     template<typename T> struct X { typename T* type; };
658  ///   };
659  /// }
660  ///
661  /// template<typename T> struct Y {
662  ///   typename N::S::X<T>::type member;
663  /// };
664  /// \endcode
665  ///
666  /// Here, the nested-name-specifier for N::S::X<T>:: will be
667  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
668  /// by declarations in the type system and the canonical type for
669  /// the template type parameter 'T' is template-param-0-0.
670  NestedNameSpecifier *
671  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS);
672
673  /// \brief Retrieves the "canonical" template name that refers to a
674  /// given template.
675  ///
676  /// The canonical template name is the simplest expression that can
677  /// be used to refer to a given template. For most templates, this
678  /// expression is just the template declaration itself. For example,
679  /// the template std::vector can be referred to via a variety of
680  /// names---std::vector, ::std::vector, vector (if vector is in
681  /// scope), etc.---but all of these names map down to the same
682  /// TemplateDecl, which is used to form the canonical template name.
683  ///
684  /// Dependent template names are more interesting. Here, the
685  /// template name could be something like T::template apply or
686  /// std::allocator<T>::template rebind, where the nested name
687  /// specifier itself is dependent. In this case, the canonical
688  /// template name uses the shortest form of the dependent
689  /// nested-name-specifier, which itself contains all canonical
690  /// types, values, and templates.
691  TemplateName getCanonicalTemplateName(TemplateName Name);
692
693  /// Type Query functions.  If the type is an instance of the specified class,
694  /// return the Type pointer for the underlying maximally pretty type.  This
695  /// is a member of ASTContext because this may need to do some amount of
696  /// canonicalization, e.g. to move type qualifiers into the element type.
697  const ArrayType *getAsArrayType(QualType T);
698  const ConstantArrayType *getAsConstantArrayType(QualType T) {
699    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
700  }
701  const VariableArrayType *getAsVariableArrayType(QualType T) {
702    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
703  }
704  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) {
705    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
706  }
707
708  /// getBaseElementType - Returns the innermost element type of a variable
709  /// length array type. For example, will return "int" for int[m][n]
710  QualType getBaseElementType(const VariableArrayType *VAT);
711
712  /// getArrayDecayedType - Return the properly qualified result of decaying the
713  /// specified array type to a pointer.  This operation is non-trivial when
714  /// handling typedefs etc.  The canonical type of "T" must be an array type,
715  /// this returns a pointer to a properly qualified element of the array.
716  ///
717  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
718  QualType getArrayDecayedType(QualType T);
719
720  /// getIntegerTypeOrder - Returns the highest ranked integer type:
721  /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
722  /// LHS < RHS, return -1.
723  int getIntegerTypeOrder(QualType LHS, QualType RHS);
724
725  /// getFloatingTypeOrder - Compare the rank of the two specified floating
726  /// point types, ignoring the domain of the type (i.e. 'double' ==
727  /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
728  /// LHS < RHS, return -1.
729  int getFloatingTypeOrder(QualType LHS, QualType RHS);
730
731  /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
732  /// point or a complex type (based on typeDomain/typeSize).
733  /// 'typeDomain' is a real floating point or complex type.
734  /// 'typeSize' is a real floating point or complex type.
735  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
736                                             QualType typeDomain) const;
737
738private:
739  // Helper for integer ordering
740  unsigned getIntegerRank(Type* T);
741
742public:
743
744  //===--------------------------------------------------------------------===//
745  //                    Type Compatibility Predicates
746  //===--------------------------------------------------------------------===//
747
748  /// Compatibility predicates used to check assignment expressions.
749  bool typesAreCompatible(QualType, QualType); // C99 6.2.7p1
750
751  bool isObjCIdType(QualType T) const {
752    return T == ObjCIdTypedefType;
753  }
754  bool isObjCClassType(QualType T) const {
755    return T == ObjCClassTypedefType;
756  }
757  bool isObjCSelType(QualType T) const {
758    assert(SelStructType && "isObjCSelType used before 'SEL' type is built");
759    return T->getAsStructureType() == SelStructType;
760  }
761
762  // Check the safety of assignment from LHS to RHS
763  bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
764                               const ObjCObjectPointerType *RHSOPT);
765  bool canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
766                               const ObjCInterfaceType *RHS);
767  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
768
769  // Functions for calculating composite types
770  QualType mergeTypes(QualType, QualType);
771  QualType mergeFunctionTypes(QualType, QualType);
772
773  //===--------------------------------------------------------------------===//
774  //                    Integer Predicates
775  //===--------------------------------------------------------------------===//
776
777  // The width of an integer, as defined in C99 6.2.6.2. This is the number
778  // of bits in an integer type excluding any padding bits.
779  unsigned getIntWidth(QualType T);
780
781  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
782  // unsigned integer type.  This method takes a signed type, and returns the
783  // corresponding unsigned integer type.
784  QualType getCorrespondingUnsignedType(QualType T);
785
786  //===--------------------------------------------------------------------===//
787  //                    Type Iterators.
788  //===--------------------------------------------------------------------===//
789
790  typedef std::vector<Type*>::iterator       type_iterator;
791  typedef std::vector<Type*>::const_iterator const_type_iterator;
792
793  type_iterator types_begin() { return Types.begin(); }
794  type_iterator types_end() { return Types.end(); }
795  const_type_iterator types_begin() const { return Types.begin(); }
796  const_type_iterator types_end() const { return Types.end(); }
797
798  //===--------------------------------------------------------------------===//
799  //                    Integer Values
800  //===--------------------------------------------------------------------===//
801
802  /// MakeIntValue - Make an APSInt of the appropriate width and
803  /// signedness for the given \arg Value and integer \arg Type.
804  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) {
805    llvm::APSInt Res(getIntWidth(Type), !Type->isSignedIntegerType());
806    Res = Value;
807    return Res;
808  }
809
810  /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
811  ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
812  /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
813  ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
814
815  /// \brief Set the implementation of ObjCInterfaceDecl.
816  void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
817                             ObjCImplementationDecl *ImplD);
818  /// \brief Set the implementation of ObjCCategoryDecl.
819  void setObjCImplementation(ObjCCategoryDecl *CatD,
820                             ObjCCategoryImplDecl *ImplD);
821
822private:
823  ASTContext(const ASTContext&); // DO NOT IMPLEMENT
824  void operator=(const ASTContext&); // DO NOT IMPLEMENT
825
826  void InitBuiltinTypes();
827  void InitBuiltinType(QualType &R, BuiltinType::Kind K);
828
829  // Return the ObjC type encoding for a given type.
830  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
831                                  bool ExpandPointedToStructures,
832                                  bool ExpandStructures,
833                                  const FieldDecl *Field,
834                                  bool OutermostType = false,
835                                  bool EncodingProperty = false);
836
837  const ASTRecordLayout &getObjCLayout(const ObjCInterfaceDecl *D,
838                                       const ObjCImplementationDecl *Impl);
839};
840
841}  // end namespace clang
842
843// operator new and delete aren't allowed inside namespaces.
844// The throw specifications are mandated by the standard.
845/// @brief Placement new for using the ASTContext's allocator.
846///
847/// This placement form of operator new uses the ASTContext's allocator for
848/// obtaining memory. It is a non-throwing new, which means that it returns
849/// null on error. (If that is what the allocator does. The current does, so if
850/// this ever changes, this operator will have to be changed, too.)
851/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
852/// @code
853/// // Default alignment (16)
854/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
855/// // Specific alignment
856/// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
857/// @endcode
858/// Please note that you cannot use delete on the pointer; it must be
859/// deallocated using an explicit destructor call followed by
860/// @c Context.Deallocate(Ptr).
861///
862/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
863/// @param C The ASTContext that provides the allocator.
864/// @param Alignment The alignment of the allocated memory (if the underlying
865///                  allocator supports it).
866/// @return The allocated memory. Could be NULL.
867inline void *operator new(size_t Bytes, clang::ASTContext &C,
868                          size_t Alignment) throw () {
869  return C.Allocate(Bytes, Alignment);
870}
871/// @brief Placement delete companion to the new above.
872///
873/// This operator is just a companion to the new above. There is no way of
874/// invoking it directly; see the new operator for more details. This operator
875/// is called implicitly by the compiler if a placement new expression using
876/// the ASTContext throws in the object constructor.
877inline void operator delete(void *Ptr, clang::ASTContext &C, size_t)
878              throw () {
879  C.Deallocate(Ptr);
880}
881
882/// This placement form of operator new[] uses the ASTContext's allocator for
883/// obtaining memory. It is a non-throwing new[], which means that it returns
884/// null on error.
885/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
886/// @code
887/// // Default alignment (16)
888/// char *data = new (Context) char[10];
889/// // Specific alignment
890/// char *data = new (Context, 8) char[10];
891/// @endcode
892/// Please note that you cannot use delete on the pointer; it must be
893/// deallocated using an explicit destructor call followed by
894/// @c Context.Deallocate(Ptr).
895///
896/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
897/// @param C The ASTContext that provides the allocator.
898/// @param Alignment The alignment of the allocated memory (if the underlying
899///                  allocator supports it).
900/// @return The allocated memory. Could be NULL.
901inline void *operator new[](size_t Bytes, clang::ASTContext& C,
902                            size_t Alignment = 16) throw () {
903  return C.Allocate(Bytes, Alignment);
904}
905
906/// @brief Placement delete[] companion to the new[] above.
907///
908/// This operator is just a companion to the new[] above. There is no way of
909/// invoking it directly; see the new[] operator for more details. This operator
910/// is called implicitly by the compiler if a placement new[] expression using
911/// the ASTContext throws in the object constructor.
912inline void operator delete[](void *Ptr, clang::ASTContext &C) throw () {
913  C.Deallocate(Ptr);
914}
915
916#endif
917