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