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