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