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