ASTContext.h revision 1ceee5c42d5c410217f67d384eecc6ea4a2bba9b
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/Basic/OperatorKinds.h"
20#include "clang/Basic/PartialDiagnostic.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/PrettyPrinter.h"
24#include "clang/AST/TemplateName.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/CanonicalType.h"
27#include "clang/AST/UsuallyTinyPtrVector.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/FoldingSet.h"
30#include "llvm/ADT/OwningPtr.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/Support/Allocator.h"
33#include <vector>
34
35namespace llvm {
36  struct fltSemantics;
37  class raw_ostream;
38}
39
40namespace clang {
41  class FileManager;
42  class ASTRecordLayout;
43  class BlockExpr;
44  class CharUnits;
45  class Diagnostic;
46  class Expr;
47  class ExternalASTSource;
48  class ASTMutationListener;
49  class IdentifierTable;
50  class SelectorTable;
51  class SourceManager;
52  class TargetInfo;
53  class CXXABI;
54  // Decls
55  class DeclContext;
56  class CXXMethodDecl;
57  class CXXRecordDecl;
58  class Decl;
59  class FieldDecl;
60  class ObjCIvarDecl;
61  class ObjCIvarRefExpr;
62  class ObjCPropertyDecl;
63  class RecordDecl;
64  class StoredDeclsMap;
65  class TagDecl;
66  class TemplateTemplateParmDecl;
67  class TemplateTypeParmDecl;
68  class TranslationUnitDecl;
69  class TypeDecl;
70  class TypedefDecl;
71  class UsingDecl;
72  class UsingShadowDecl;
73  class UnresolvedSetIterator;
74
75  namespace Builtin { class Context; }
76
77/// ASTContext - This class holds long-lived AST nodes (such as types and
78/// decls) that can be referred to throughout the semantic analysis of a file.
79class ASTContext {
80  ASTContext &this_() { return *this; }
81
82  std::vector<Type*> Types;
83  llvm::FoldingSet<ExtQuals> ExtQualNodes;
84  llvm::FoldingSet<ComplexType> ComplexTypes;
85  llvm::FoldingSet<PointerType> PointerTypes;
86  llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
87  llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
88  llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
89  llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
90  llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
91  llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
92  std::vector<VariableArrayType*> VariableArrayTypes;
93  llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
94  llvm::FoldingSet<DependentSizedExtVectorType> DependentSizedExtVectorTypes;
95  llvm::FoldingSet<VectorType> VectorTypes;
96  llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
97  llvm::FoldingSet<FunctionProtoType> FunctionProtoTypes;
98  llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
99  llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
100  llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
101  llvm::FoldingSet<SubstTemplateTypeParmType> SubstTemplateTypeParmTypes;
102  llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
103    TemplateSpecializationTypes;
104  llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
105  llvm::FoldingSet<DependentNameType> DependentNameTypes;
106  llvm::ContextualFoldingSet<DependentTemplateSpecializationType, ASTContext&>
107    DependentTemplateSpecializationTypes;
108  llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
109  llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
110
111  llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
112  llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
113
114  /// \brief The set of nested name specifiers.
115  ///
116  /// This set is managed by the NestedNameSpecifier class.
117  llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
118  NestedNameSpecifier *GlobalNestedNameSpecifier;
119  friend class NestedNameSpecifier;
120
121  /// ASTRecordLayouts - A cache mapping from RecordDecls to ASTRecordLayouts.
122  ///  This is lazily created.  This is intentionally not serialized.
123  llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*> ASTRecordLayouts;
124  llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*> ObjCLayouts;
125
126  /// KeyFunctions - A cache mapping from CXXRecordDecls to key functions.
127  llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*> KeyFunctions;
128
129  /// \brief Mapping from ObjCContainers to their ObjCImplementations.
130  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
131
132  /// \brief Mapping from __block VarDecls to their copy initialization expr.
133  llvm::DenseMap<VarDecl*, Expr*> BlockVarCopyInits;
134
135  /// \brief Representation of a "canonical" template template parameter that
136  /// is used in canonical template names.
137  class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
138    TemplateTemplateParmDecl *Parm;
139
140  public:
141    CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
142      : Parm(Parm) { }
143
144    TemplateTemplateParmDecl *getParam() const { return Parm; }
145
146    void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
147
148    static void Profile(llvm::FoldingSetNodeID &ID,
149                        TemplateTemplateParmDecl *Parm);
150  };
151  llvm::FoldingSet<CanonicalTemplateTemplateParm> CanonTemplateTemplateParms;
152
153  TemplateTemplateParmDecl *getCanonicalTemplateTemplateParmDecl(
154                                               TemplateTemplateParmDecl *TTP);
155
156  /// \brief Whether __[u]int128_t identifier is installed.
157  bool IsInt128Installed;
158
159  /// BuiltinVaListType - built-in va list type.
160  /// This is initially null and set by Sema::LazilyCreateBuiltin when
161  /// a builtin that takes a valist is encountered.
162  QualType BuiltinVaListType;
163
164  /// ObjCIdType - a pseudo built-in typedef type (set by Sema).
165  QualType ObjCIdTypedefType;
166
167  /// ObjCSelType - another pseudo built-in typedef type (set by Sema).
168  QualType ObjCSelTypedefType;
169
170  /// ObjCProtoType - another pseudo built-in typedef type (set by Sema).
171  QualType ObjCProtoType;
172  const RecordType *ProtoStructType;
173
174  /// ObjCClassType - another pseudo built-in typedef type (set by Sema).
175  QualType ObjCClassTypedefType;
176
177  QualType ObjCConstantStringType;
178  RecordDecl *CFConstantStringTypeDecl;
179
180  RecordDecl *NSConstantStringTypeDecl;
181
182  RecordDecl *ObjCFastEnumerationStateTypeDecl;
183
184  /// \brief The type for the C FILE type.
185  TypeDecl *FILEDecl;
186
187  /// \brief The type for the C jmp_buf type.
188  TypeDecl *jmp_bufDecl;
189
190  /// \brief The type for the C sigjmp_buf type.
191  TypeDecl *sigjmp_bufDecl;
192
193  /// \brief Type for the Block descriptor for Blocks CodeGen.
194  RecordDecl *BlockDescriptorType;
195
196  /// \brief Type for the Block descriptor for Blocks CodeGen.
197  RecordDecl *BlockDescriptorExtendedType;
198
199  TypeSourceInfo NullTypeSourceInfo;
200
201  /// \brief Keeps track of all declaration attributes.
202  ///
203  /// Since so few decls have attrs, we keep them in a hash map instead of
204  /// wasting space in the Decl class.
205  llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
206
207  /// \brief Keeps track of the static data member templates from which
208  /// static data members of class template specializations were instantiated.
209  ///
210  /// This data structure stores the mapping from instantiations of static
211  /// data members to the static data member representations within the
212  /// class template from which they were instantiated along with the kind
213  /// of instantiation or specialization (a TemplateSpecializationKind - 1).
214  ///
215  /// Given the following example:
216  ///
217  /// \code
218  /// template<typename T>
219  /// struct X {
220  ///   static T value;
221  /// };
222  ///
223  /// template<typename T>
224  ///   T X<T>::value = T(17);
225  ///
226  /// int *x = &X<int>::value;
227  /// \endcode
228  ///
229  /// This mapping will contain an entry that maps from the VarDecl for
230  /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
231  /// class template X) and will be marked TSK_ImplicitInstantiation.
232  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>
233    InstantiatedFromStaticDataMember;
234
235  /// \brief Keeps track of the declaration from which a UsingDecl was
236  /// created during instantiation.  The source declaration is always
237  /// a UsingDecl, an UnresolvedUsingValueDecl, or an
238  /// UnresolvedUsingTypenameDecl.
239  ///
240  /// For example:
241  /// \code
242  /// template<typename T>
243  /// struct A {
244  ///   void f();
245  /// };
246  ///
247  /// template<typename T>
248  /// struct B : A<T> {
249  ///   using A<T>::f;
250  /// };
251  ///
252  /// template struct B<int>;
253  /// \endcode
254  ///
255  /// This mapping will contain an entry that maps from the UsingDecl in
256  /// B<int> to the UnresolvedUsingDecl in B<T>.
257  llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
258
259  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
260    InstantiatedFromUsingShadowDecl;
261
262  llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
263
264  /// \brief Mapping that stores the methods overridden by a given C++
265  /// member function.
266  ///
267  /// Since most C++ member functions aren't virtual and therefore
268  /// don't override anything, we store the overridden functions in
269  /// this map on the side rather than within the CXXMethodDecl structure.
270  typedef UsuallyTinyPtrVector<const CXXMethodDecl> CXXMethodVector;
271  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
272
273  TranslationUnitDecl *TUDecl;
274
275  /// SourceMgr - The associated SourceManager object.
276  SourceManager &SourceMgr;
277
278  /// LangOpts - The language options used to create the AST associated with
279  ///  this ASTContext object.
280  LangOptions LangOpts;
281
282  /// \brief The allocator used to create AST objects.
283  ///
284  /// AST objects are never destructed; rather, all memory associated with the
285  /// AST objects will be released when the ASTContext itself is destroyed.
286  llvm::BumpPtrAllocator BumpAlloc;
287
288  /// \brief Allocator for partial diagnostics.
289  PartialDiagnostic::StorageAllocator DiagAllocator;
290
291  /// \brief The current C++ ABI.
292  llvm::OwningPtr<CXXABI> ABI;
293  CXXABI *createCXXABI(const TargetInfo &T);
294
295  friend class ASTDeclReader;
296
297public:
298  const TargetInfo &Target;
299  IdentifierTable &Idents;
300  SelectorTable &Selectors;
301  Builtin::Context &BuiltinInfo;
302  DeclarationNameTable DeclarationNames;
303  llvm::OwningPtr<ExternalASTSource> ExternalSource;
304  ASTMutationListener *Listener;
305  clang::PrintingPolicy PrintingPolicy;
306
307  // Typedefs which may be provided defining the structure of Objective-C
308  // pseudo-builtins
309  QualType ObjCIdRedefinitionType;
310  QualType ObjCClassRedefinitionType;
311  QualType ObjCSelRedefinitionType;
312
313  SourceManager& getSourceManager() { return SourceMgr; }
314  const SourceManager& getSourceManager() const { return SourceMgr; }
315  void *Allocate(unsigned Size, unsigned Align = 8) {
316    return BumpAlloc.Allocate(Size, Align);
317  }
318  void Deallocate(void *Ptr) { }
319
320  PartialDiagnostic::StorageAllocator &getDiagAllocator() {
321    return DiagAllocator;
322  }
323
324  const LangOptions& getLangOptions() const { return LangOpts; }
325
326  Diagnostic &getDiagnostics() const;
327
328  FullSourceLoc getFullLoc(SourceLocation Loc) const {
329    return FullSourceLoc(Loc,SourceMgr);
330  }
331
332  /// \brief Retrieve the attributes for the given declaration.
333  AttrVec& getDeclAttrs(const Decl *D);
334
335  /// \brief Erase the attributes corresponding to the given declaration.
336  void eraseDeclAttrs(const Decl *D);
337
338  /// \brief If this variable is an instantiated static data member of a
339  /// class template specialization, returns the templated static data member
340  /// from which it was instantiated.
341  MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
342                                                           const VarDecl *Var);
343
344  /// \brief Note that the static data member \p Inst is an instantiation of
345  /// the static data member template \p Tmpl of a class template.
346  void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
347                                           TemplateSpecializationKind TSK,
348                        SourceLocation PointOfInstantiation = SourceLocation());
349
350  /// \brief If the given using decl is an instantiation of a
351  /// (possibly unresolved) using decl from a template instantiation,
352  /// return it.
353  NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
354
355  /// \brief Remember that the using decl \p Inst is an instantiation
356  /// of the using decl \p Pattern of a class template.
357  void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
358
359  void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
360                                          UsingShadowDecl *Pattern);
361  UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
362
363  FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
364
365  void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
366
367  // Access to the set of methods overridden by the given C++ method.
368  typedef CXXMethodVector::iterator overridden_cxx_method_iterator;
369  overridden_cxx_method_iterator
370  overridden_methods_begin(const CXXMethodDecl *Method) const;
371
372  overridden_cxx_method_iterator
373  overridden_methods_end(const CXXMethodDecl *Method) const;
374
375  unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
376
377  /// \brief Note that the given C++ \p Method overrides the given \p
378  /// Overridden method.
379  void addOverriddenMethod(const CXXMethodDecl *Method,
380                           const CXXMethodDecl *Overridden);
381
382  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
383
384
385  // Builtin Types.
386  CanQualType VoidTy;
387  CanQualType BoolTy;
388  CanQualType CharTy;
389  CanQualType WCharTy;  // [C++ 3.9.1p5], integer type in C99.
390  CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
391  CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
392  CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
393  CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
394  CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
395  CanQualType FloatTy, DoubleTy, LongDoubleTy;
396  CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
397  CanQualType VoidPtrTy, NullPtrTy;
398  CanQualType OverloadTy, UndeducedAutoTy;
399  CanQualType DependentTy;
400  CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
401
402  ASTContext(const LangOptions& LOpts, SourceManager &SM, const TargetInfo &t,
403             IdentifierTable &idents, SelectorTable &sels,
404             Builtin::Context &builtins,
405             unsigned size_reserve);
406
407  ~ASTContext();
408
409  /// \brief Attach an external AST source to the AST context.
410  ///
411  /// The external AST source provides the ability to load parts of
412  /// the abstract syntax tree as needed from some external storage,
413  /// e.g., a precompiled header.
414  void setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source);
415
416  /// \brief Retrieve a pointer to the external AST source associated
417  /// with this AST context, if any.
418  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
419
420  /// \brief Attach an AST mutation listener to the AST context.
421  ///
422  /// The AST mutation listener provides the ability to track modifications to
423  /// the abstract syntax tree entities committed after they were initially
424  /// created.
425  void setASTMutationListener(ASTMutationListener *Listener) {
426    this->Listener = Listener;
427  }
428
429  /// \brief Retrieve a pointer to the AST mutation listener associated
430  /// with this AST context, if any.
431  ASTMutationListener *getASTMutationListener() const { return Listener; }
432
433  void PrintStats() const;
434  const std::vector<Type*>& getTypes() const { return Types; }
435
436  //===--------------------------------------------------------------------===//
437  //                           Type Constructors
438  //===--------------------------------------------------------------------===//
439
440private:
441  /// getExtQualType - Return a type with extended qualifiers.
442  QualType getExtQualType(const Type *Base, Qualifiers Quals);
443
444  QualType getTypeDeclTypeSlow(const TypeDecl *Decl);
445
446public:
447  /// getAddSpaceQualType - Return the uniqued reference to the type for an
448  /// address space qualified type with the specified type and address space.
449  /// The resulting type has a union of the qualifiers from T and the address
450  /// space. If T already has an address space specifier, it is silently
451  /// replaced.
452  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace);
453
454  /// getObjCGCQualType - Returns the uniqued reference to the type for an
455  /// objc gc qualified type. The retulting type has a union of the qualifiers
456  /// from T and the gc attribute.
457  QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr);
458
459  /// getRestrictType - Returns the uniqued reference to the type for a
460  /// 'restrict' qualified type.  The resulting type has a union of the
461  /// qualifiers from T and 'restrict'.
462  QualType getRestrictType(QualType T) {
463    return T.withFastQualifiers(Qualifiers::Restrict);
464  }
465
466  /// getVolatileType - Returns the uniqued reference to the type for a
467  /// 'volatile' qualified type.  The resulting type has a union of the
468  /// qualifiers from T and 'volatile'.
469  QualType getVolatileType(QualType T);
470
471  /// getConstType - Returns the uniqued reference to the type for a
472  /// 'const' qualified type.  The resulting type has a union of the
473  /// qualifiers from T and 'const'.
474  ///
475  /// It can be reasonably expected that this will always be
476  /// equivalent to calling T.withConst().
477  QualType getConstType(QualType T) { return T.withConst(); }
478
479  /// getNoReturnType - Add or remove the noreturn attribute to the given type
480  /// which must be a FunctionType or a pointer to an allowable type or a
481  /// BlockPointer.
482  QualType getNoReturnType(QualType T, bool AddNoReturn = true);
483
484  /// getCallConvType - Adds the specified calling convention attribute to
485  /// the given type, which must be a FunctionType or a pointer to an
486  /// allowable type.
487  QualType getCallConvType(QualType T, CallingConv CallConv);
488
489  /// getRegParmType - Sets the specified regparm attribute to
490  /// the given type, which must be a FunctionType or a pointer to an
491  /// allowable type.
492  QualType getRegParmType(QualType T, unsigned RegParm);
493
494  /// getComplexType - Return the uniqued reference to the type for a complex
495  /// number with the specified element type.
496  QualType getComplexType(QualType T);
497  CanQualType getComplexType(CanQualType T) {
498    return CanQualType::CreateUnsafe(getComplexType((QualType) T));
499  }
500
501  /// getPointerType - Return the uniqued reference to the type for a pointer to
502  /// the specified type.
503  QualType getPointerType(QualType T);
504  CanQualType getPointerType(CanQualType T) {
505    return CanQualType::CreateUnsafe(getPointerType((QualType) T));
506  }
507
508  /// getBlockPointerType - Return the uniqued reference to the type for a block
509  /// of the specified type.
510  QualType getBlockPointerType(QualType T);
511
512  /// This gets the struct used to keep track of the descriptor for pointer to
513  /// blocks.
514  QualType getBlockDescriptorType();
515
516  // Set the type for a Block descriptor type.
517  void setBlockDescriptorType(QualType T);
518  /// Get the BlockDescriptorType type, or NULL if it hasn't yet been built.
519  QualType getRawBlockdescriptorType() {
520    if (BlockDescriptorType)
521      return getTagDeclType(BlockDescriptorType);
522    return QualType();
523  }
524
525  /// This gets the struct used to keep track of the extended descriptor for
526  /// pointer to blocks.
527  QualType getBlockDescriptorExtendedType();
528
529  // Set the type for a Block descriptor extended type.
530  void setBlockDescriptorExtendedType(QualType T);
531  /// Get the BlockDescriptorExtendedType type, or NULL if it hasn't yet been
532  /// built.
533  QualType getRawBlockdescriptorExtendedType() {
534    if (BlockDescriptorExtendedType)
535      return getTagDeclType(BlockDescriptorExtendedType);
536    return QualType();
537  }
538
539  /// This gets the struct used to keep track of pointer to blocks, complete
540  /// with captured variables.
541  QualType getBlockParmType(bool BlockHasCopyDispose,
542                            llvm::SmallVectorImpl<const Expr *> &Layout);
543
544  /// This builds the struct used for __block variables.
545  QualType BuildByRefType(llvm::StringRef DeclName, QualType Ty);
546
547  /// Returns true iff we need copy/dispose helpers for the given type.
548  bool BlockRequiresCopying(QualType Ty);
549
550  /// getLValueReferenceType - Return the uniqued reference to the type for an
551  /// lvalue reference to the specified type.
552  QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true);
553
554  /// getRValueReferenceType - Return the uniqued reference to the type for an
555  /// rvalue reference to the specified type.
556  QualType getRValueReferenceType(QualType T);
557
558  /// getMemberPointerType - Return the uniqued reference to the type for a
559  /// member pointer to the specified type in the specified class. The class
560  /// is a Type because it could be a dependent name.
561  QualType getMemberPointerType(QualType T, const Type *Cls);
562
563  /// getVariableArrayType - Returns a non-unique reference to the type for a
564  /// variable array of the specified element type.
565  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
566                                ArrayType::ArraySizeModifier ASM,
567                                unsigned EltTypeQuals,
568                                SourceRange Brackets);
569
570  /// getDependentSizedArrayType - Returns a non-unique reference to
571  /// the type for a dependently-sized array of the specified element
572  /// type. FIXME: We will need these to be uniqued, or at least
573  /// comparable, at some point.
574  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
575                                      ArrayType::ArraySizeModifier ASM,
576                                      unsigned EltTypeQuals,
577                                      SourceRange Brackets);
578
579  /// getIncompleteArrayType - Returns a unique reference to the type for a
580  /// incomplete array of the specified element type.
581  QualType getIncompleteArrayType(QualType EltTy,
582                                  ArrayType::ArraySizeModifier ASM,
583                                  unsigned EltTypeQuals);
584
585  /// getConstantArrayType - Return the unique reference to the type for a
586  /// constant array of the specified element type.
587  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
588                                ArrayType::ArraySizeModifier ASM,
589                                unsigned EltTypeQuals);
590
591  /// getUnknownSizeVariableArrayType - Return a variable array type with
592  /// all variable indices replaced with unknow [*] size.
593  QualType getUnknownSizeVariableArrayType(QualType Ty);
594
595  /// getVariableArrayDecayedType - Returns a vla type where known sizes
596  /// are replaced with [*]
597  QualType getVariableArrayDecayedType(QualType Ty);
598
599  /// getVectorType - Return the unique reference to a vector type of
600  /// the specified element type and size. VectorType must be a built-in type.
601  QualType getVectorType(QualType VectorType, unsigned NumElts,
602                         VectorType::VectorKind VecKind);
603
604  /// getExtVectorType - Return the unique reference to an extended vector type
605  /// of the specified element type and size.  VectorType must be a built-in
606  /// type.
607  QualType getExtVectorType(QualType VectorType, unsigned NumElts);
608
609  /// getDependentSizedExtVectorType - Returns a non-unique reference to
610  /// the type for a dependently-sized vector of the specified element
611  /// type. FIXME: We will need these to be uniqued, or at least
612  /// comparable, at some point.
613  QualType getDependentSizedExtVectorType(QualType VectorType,
614                                          Expr *SizeExpr,
615                                          SourceLocation AttrLoc);
616
617  /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
618  ///
619  QualType getFunctionNoProtoType(QualType ResultTy,
620                                  const FunctionType::ExtInfo &Info);
621
622  QualType getFunctionNoProtoType(QualType ResultTy) {
623    return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
624  }
625
626  /// getFunctionType - Return a normal function type with a typed argument
627  /// list.  isVariadic indicates whether the argument list includes '...'.
628  QualType getFunctionType(QualType ResultTy, const QualType *ArgArray,
629                           unsigned NumArgs, bool isVariadic,
630                           unsigned TypeQuals, bool hasExceptionSpec,
631                           bool hasAnyExceptionSpec,
632                           unsigned NumExs, const QualType *ExArray,
633                           const FunctionType::ExtInfo &Info);
634
635  /// getTypeDeclType - Return the unique reference to the type for
636  /// the specified type declaration.
637  QualType getTypeDeclType(const TypeDecl *Decl,
638                           const TypeDecl *PrevDecl = 0) {
639    assert(Decl && "Passed null for Decl param");
640    if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
641
642    if (PrevDecl) {
643      assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
644      Decl->TypeForDecl = PrevDecl->TypeForDecl;
645      return QualType(PrevDecl->TypeForDecl, 0);
646    }
647
648    return getTypeDeclTypeSlow(Decl);
649  }
650
651  /// getTypedefType - Return the unique reference to the type for the
652  /// specified typename decl.
653  QualType getTypedefType(const TypedefDecl *Decl, QualType Canon = QualType());
654
655  QualType getRecordType(const RecordDecl *Decl);
656
657  QualType getEnumType(const EnumDecl *Decl);
658
659  QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST);
660
661  QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
662                                        QualType Replacement);
663
664  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
665                                   bool ParameterPack,
666                                   IdentifierInfo *Name = 0);
667
668  QualType getTemplateSpecializationType(TemplateName T,
669                                         const TemplateArgument *Args,
670                                         unsigned NumArgs,
671                                         QualType Canon = QualType());
672
673  QualType getCanonicalTemplateSpecializationType(TemplateName T,
674                                                  const TemplateArgument *Args,
675                                                  unsigned NumArgs);
676
677  QualType getTemplateSpecializationType(TemplateName T,
678                                         const TemplateArgumentListInfo &Args,
679                                         QualType Canon = QualType());
680
681  TypeSourceInfo *
682  getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
683                                    const TemplateArgumentListInfo &Args,
684                                    QualType Canon = QualType());
685
686  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
687                             NestedNameSpecifier *NNS,
688                             QualType NamedType);
689  QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
690                                NestedNameSpecifier *NNS,
691                                const IdentifierInfo *Name,
692                                QualType Canon = QualType());
693
694  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
695                                                  NestedNameSpecifier *NNS,
696                                                  const IdentifierInfo *Name,
697                                          const TemplateArgumentListInfo &Args);
698  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
699                                                  NestedNameSpecifier *NNS,
700                                                  const IdentifierInfo *Name,
701                                                  unsigned NumArgs,
702                                                  const TemplateArgument *Args);
703
704  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl);
705
706  QualType getObjCObjectType(QualType Base,
707                             ObjCProtocolDecl * const *Protocols,
708                             unsigned NumProtocols);
709
710  /// getObjCObjectPointerType - Return a ObjCObjectPointerType type
711  /// for the given ObjCObjectType.
712  QualType getObjCObjectPointerType(QualType OIT);
713
714  /// getTypeOfType - GCC extension.
715  QualType getTypeOfExprType(Expr *e);
716  QualType getTypeOfType(QualType t);
717
718  /// getDecltypeType - C++0x decltype.
719  QualType getDecltypeType(Expr *e);
720
721  /// getTagDeclType - Return the unique reference to the type for the
722  /// specified TagDecl (struct/union/class/enum) decl.
723  QualType getTagDeclType(const TagDecl *Decl);
724
725  /// getSizeType - Return the unique type for "size_t" (C99 7.17), defined
726  /// in <stddef.h>. The sizeof operator requires this (C99 6.5.3.4p4).
727  CanQualType getSizeType() const;
728
729  /// getWCharType - In C++, this returns the unique wchar_t type.  In C99, this
730  /// returns a type compatible with the type defined in <stddef.h> as defined
731  /// by the target.
732  QualType getWCharType() const { return WCharTy; }
733
734  /// getSignedWCharType - Return the type of "signed wchar_t".
735  /// Used when in C++, as a GCC extension.
736  QualType getSignedWCharType() const;
737
738  /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
739  /// Used when in C++, as a GCC extension.
740  QualType getUnsignedWCharType() const;
741
742  /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
743  /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
744  QualType getPointerDiffType() const;
745
746  // getCFConstantStringType - Return the C structure type used to represent
747  // constant CFStrings.
748  QualType getCFConstantStringType();
749
750  // getNSConstantStringType - Return the C structure type used to represent
751  // constant NSStrings.
752  QualType getNSConstantStringType();
753  /// Get the structure type used to representation NSStrings, or NULL
754  /// if it hasn't yet been built.
755  QualType getRawNSConstantStringType() {
756    if (NSConstantStringTypeDecl)
757      return getTagDeclType(NSConstantStringTypeDecl);
758    return QualType();
759  }
760  void setNSConstantStringType(QualType T);
761
762
763  /// Get the structure type used to representation CFStrings, or NULL
764  /// if it hasn't yet been built.
765  QualType getRawCFConstantStringType() {
766    if (CFConstantStringTypeDecl)
767      return getTagDeclType(CFConstantStringTypeDecl);
768    return QualType();
769  }
770  void setCFConstantStringType(QualType T);
771
772  // This setter/getter represents the ObjC type for an NSConstantString.
773  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
774  QualType getObjCConstantStringInterface() const {
775    return ObjCConstantStringType;
776  }
777
778  //// This gets the struct used to keep track of fast enumerations.
779  QualType getObjCFastEnumerationStateType();
780
781  /// Get the ObjCFastEnumerationState type, or NULL if it hasn't yet
782  /// been built.
783  QualType getRawObjCFastEnumerationStateType() {
784    if (ObjCFastEnumerationStateTypeDecl)
785      return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
786    return QualType();
787  }
788
789  void setObjCFastEnumerationStateType(QualType T);
790
791  /// \brief Set the type for the C FILE type.
792  void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
793
794  /// \brief Retrieve the C FILE type.
795  QualType getFILEType() {
796    if (FILEDecl)
797      return getTypeDeclType(FILEDecl);
798    return QualType();
799  }
800
801  /// \brief Set the type for the C jmp_buf type.
802  void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
803    this->jmp_bufDecl = jmp_bufDecl;
804  }
805
806  /// \brief Retrieve the C jmp_buf type.
807  QualType getjmp_bufType() {
808    if (jmp_bufDecl)
809      return getTypeDeclType(jmp_bufDecl);
810    return QualType();
811  }
812
813  /// \brief Set the type for the C sigjmp_buf type.
814  void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
815    this->sigjmp_bufDecl = sigjmp_bufDecl;
816  }
817
818  /// \brief Retrieve the C sigjmp_buf type.
819  QualType getsigjmp_bufType() {
820    if (sigjmp_bufDecl)
821      return getTypeDeclType(sigjmp_bufDecl);
822    return QualType();
823  }
824
825  /// getObjCEncodingForType - Emit the ObjC type encoding for the
826  /// given type into \arg S. If \arg NameFields is specified then
827  /// record field names are also encoded.
828  void getObjCEncodingForType(QualType t, std::string &S,
829                              const FieldDecl *Field=0);
830
831  void getLegacyIntegralTypeEncoding(QualType &t) const;
832
833  // Put the string version of type qualifiers into S.
834  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
835                                       std::string &S) const;
836
837  /// getObjCEncodingForMethodDecl - Return the encoded type for this method
838  /// declaration.
839  void getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S);
840
841  /// getObjCEncodingForBlockDecl - Return the encoded type for this block
842  /// declaration.
843  void getObjCEncodingForBlock(const BlockExpr *Expr, std::string& S);
844
845  /// getObjCEncodingForPropertyDecl - Return the encoded type for
846  /// this method declaration. If non-NULL, Container must be either
847  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
848  /// only be NULL when getting encodings for protocol properties.
849  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
850                                      const Decl *Container,
851                                      std::string &S);
852
853  bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
854                                      ObjCProtocolDecl *rProto);
855
856  /// getObjCEncodingTypeSize returns size of type for objective-c encoding
857  /// purpose in characters.
858  CharUnits getObjCEncodingTypeSize(QualType t);
859
860  /// \brief Whether __[u]int128_t identifier is installed.
861  bool isInt128Installed() const { return IsInt128Installed; }
862  void setInt128Installed() { IsInt128Installed = true; }
863
864  /// This setter/getter represents the ObjC 'id' type. It is setup lazily, by
865  /// Sema.  id is always a (typedef for a) pointer type, a pointer to a struct.
866  QualType getObjCIdType() const { return ObjCIdTypedefType; }
867  void setObjCIdType(QualType T);
868
869  void setObjCSelType(QualType T);
870  QualType getObjCSelType() const { return ObjCSelTypedefType; }
871
872  void setObjCProtoType(QualType QT);
873  QualType getObjCProtoType() const { return ObjCProtoType; }
874
875  /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by
876  /// Sema.  'Class' is always a (typedef for a) pointer type, a pointer to a
877  /// struct.
878  QualType getObjCClassType() const { return ObjCClassTypedefType; }
879  void setObjCClassType(QualType T);
880
881  void setBuiltinVaListType(QualType T);
882  QualType getBuiltinVaListType() const { return BuiltinVaListType; }
883
884  /// getCVRQualifiedType - Returns a type with additional const,
885  /// volatile, or restrict qualifiers.
886  QualType getCVRQualifiedType(QualType T, unsigned CVR) {
887    return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
888  }
889
890  /// getQualifiedType - Returns a type with additional qualifiers.
891  QualType getQualifiedType(QualType T, Qualifiers Qs) {
892    if (!Qs.hasNonFastQualifiers())
893      return T.withFastQualifiers(Qs.getFastQualifiers());
894    QualifierCollector Qc(Qs);
895    const Type *Ptr = Qc.strip(T);
896    return getExtQualType(Ptr, Qc);
897  }
898
899  /// getQualifiedType - Returns a type with additional qualifiers.
900  QualType getQualifiedType(const Type *T, Qualifiers Qs) {
901    if (!Qs.hasNonFastQualifiers())
902      return QualType(T, Qs.getFastQualifiers());
903    return getExtQualType(T, Qs);
904  }
905
906  DeclarationNameInfo getNameForTemplate(TemplateName Name,
907                                         SourceLocation NameLoc);
908
909  TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
910                                         UnresolvedSetIterator End);
911
912  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
913                                        bool TemplateKeyword,
914                                        TemplateDecl *Template);
915
916  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
917                                        const IdentifierInfo *Name);
918  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
919                                        OverloadedOperatorKind Operator);
920
921  enum GetBuiltinTypeError {
922    GE_None,              //< No error
923    GE_Missing_stdio,     //< Missing a type from <stdio.h>
924    GE_Missing_setjmp     //< Missing a type from <setjmp.h>
925  };
926
927  /// GetBuiltinType - Return the type for the specified builtin.  If
928  /// IntegerConstantArgs is non-null, it is filled in with a bitmask of
929  /// arguments to the builtin that are required to be integer constant
930  /// expressions.
931  QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
932                          unsigned *IntegerConstantArgs = 0);
933
934private:
935  CanQualType getFromTargetType(unsigned Type) const;
936
937  //===--------------------------------------------------------------------===//
938  //                         Type Predicates.
939  //===--------------------------------------------------------------------===//
940
941public:
942  /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
943  /// garbage collection attribute.
944  ///
945  Qualifiers::GC getObjCGCAttrKind(const QualType &Ty) const;
946
947  /// areCompatibleVectorTypes - Return true if the given vector types
948  /// are of the same unqualified type or if they are equivalent to the same
949  /// GCC vector type, ignoring whether they are target-specific (AltiVec or
950  /// Neon) types.
951  bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
952
953  /// isObjCNSObjectType - Return true if this is an NSObject object with
954  /// its NSObject attribute set.
955  bool isObjCNSObjectType(QualType Ty) const;
956
957  //===--------------------------------------------------------------------===//
958  //                         Type Sizing and Analysis
959  //===--------------------------------------------------------------------===//
960
961  /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
962  /// scalar floating point type.
963  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
964
965  /// getTypeInfo - Get the size and alignment of the specified complete type in
966  /// bits.
967  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T);
968  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) {
969    return getTypeInfo(T.getTypePtr());
970  }
971
972  /// getTypeSize - Return the size of the specified type, in bits.  This method
973  /// does not work on incomplete types.
974  uint64_t getTypeSize(QualType T) {
975    return getTypeInfo(T).first;
976  }
977  uint64_t getTypeSize(const Type *T) {
978    return getTypeInfo(T).first;
979  }
980
981  /// getCharWidth - Return the size of the character type, in bits
982  uint64_t getCharWidth() {
983    return getTypeSize(CharTy);
984  }
985
986  /// getTypeSizeInChars - Return the size of the specified type, in characters.
987  /// This method does not work on incomplete types.
988  CharUnits getTypeSizeInChars(QualType T);
989  CharUnits getTypeSizeInChars(const Type *T);
990
991  /// getTypeAlign - Return the ABI-specified alignment of a type, in bits.
992  /// This method does not work on incomplete types.
993  unsigned getTypeAlign(QualType T) {
994    return getTypeInfo(T).second;
995  }
996  unsigned getTypeAlign(const Type *T) {
997    return getTypeInfo(T).second;
998  }
999
1000  /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1001  /// characters. This method does not work on incomplete types.
1002  CharUnits getTypeAlignInChars(QualType T);
1003  CharUnits getTypeAlignInChars(const Type *T);
1004
1005  std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T);
1006  std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T);
1007
1008  /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1009  /// type for the current target in bits.  This can be different than the ABI
1010  /// alignment in cases where it is beneficial for performance to overalign
1011  /// a data type.
1012  unsigned getPreferredTypeAlign(const Type *T);
1013
1014  /// getDeclAlign - Return a conservative estimate of the alignment of
1015  /// the specified decl.  Note that bitfields do not have a valid alignment, so
1016  /// this method will assert on them.
1017  /// If @p RefAsPointee, references are treated like their underlying type
1018  /// (for alignof), else they're treated like pointers (for CodeGen).
1019  CharUnits getDeclAlign(const Decl *D, bool RefAsPointee = false);
1020
1021  /// getASTRecordLayout - Get or compute information about the layout of the
1022  /// specified record (struct/union/class), which indicates its size and field
1023  /// position information.
1024  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D);
1025
1026  /// getASTObjCInterfaceLayout - Get or compute information about the
1027  /// layout of the specified Objective-C interface.
1028  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D);
1029
1030  void DumpRecordLayout(const RecordDecl *RD, llvm::raw_ostream &OS);
1031
1032  /// getASTObjCImplementationLayout - Get or compute information about
1033  /// the layout of the specified Objective-C implementation. This may
1034  /// differ from the interface if synthesized ivars are present.
1035  const ASTRecordLayout &
1036  getASTObjCImplementationLayout(const ObjCImplementationDecl *D);
1037
1038  /// getKeyFunction - Get the key function for the given record decl, or NULL
1039  /// if there isn't one.  The key function is, according to the Itanium C++ ABI
1040  /// section 5.2.3:
1041  ///
1042  /// ...the first non-pure virtual function that is not inline at the point
1043  /// of class definition.
1044  const CXXMethodDecl *getKeyFunction(const CXXRecordDecl *RD);
1045
1046  bool isNearlyEmpty(const CXXRecordDecl *RD);
1047
1048  void ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
1049                               llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
1050
1051  void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1052                            llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
1053
1054  unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI);
1055  void CollectInheritedProtocols(const Decl *CDecl,
1056                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1057
1058  //===--------------------------------------------------------------------===//
1059  //                            Type Operators
1060  //===--------------------------------------------------------------------===//
1061
1062  /// getCanonicalType - Return the canonical (structural) type corresponding to
1063  /// the specified potentially non-canonical type.  The non-canonical version
1064  /// of a type may have many "decorated" versions of types.  Decorators can
1065  /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1066  /// to be free of any of these, allowing two canonical types to be compared
1067  /// for exact equality with a simple pointer comparison.
1068  CanQualType getCanonicalType(QualType T);
1069  const Type *getCanonicalType(const Type *T) {
1070    return T->getCanonicalTypeInternal().getTypePtr();
1071  }
1072
1073  /// getCanonicalParamType - Return the canonical parameter type
1074  /// corresponding to the specific potentially non-canonical one.
1075  /// Qualifiers are stripped off, functions are turned into function
1076  /// pointers, and arrays decay one level into pointers.
1077  CanQualType getCanonicalParamType(QualType T);
1078
1079  /// \brief Determine whether the given types are equivalent.
1080  bool hasSameType(QualType T1, QualType T2) {
1081    return getCanonicalType(T1) == getCanonicalType(T2);
1082  }
1083
1084  /// \brief Returns this type as a completely-unqualified array type,
1085  /// capturing the qualifiers in Quals. This will remove the minimal amount of
1086  /// sugaring from the types, similar to the behavior of
1087  /// QualType::getUnqualifiedType().
1088  ///
1089  /// \param T is the qualified type, which may be an ArrayType
1090  ///
1091  /// \param Quals will receive the full set of qualifiers that were
1092  /// applied to the array.
1093  ///
1094  /// \returns if this is an array type, the completely unqualified array type
1095  /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1096  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1097
1098  /// \brief Determine whether the given types are equivalent after
1099  /// cvr-qualifiers have been removed.
1100  bool hasSameUnqualifiedType(QualType T1, QualType T2) {
1101    CanQualType CT1 = getCanonicalType(T1);
1102    CanQualType CT2 = getCanonicalType(T2);
1103
1104    Qualifiers Quals;
1105    QualType UnqualT1 = getUnqualifiedArrayType(CT1, Quals);
1106    QualType UnqualT2 = getUnqualifiedArrayType(CT2, Quals);
1107    return UnqualT1 == UnqualT2;
1108  }
1109
1110  bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1111
1112  /// \brief Retrieves the "canonical" nested name specifier for a
1113  /// given nested name specifier.
1114  ///
1115  /// The canonical nested name specifier is a nested name specifier
1116  /// that uniquely identifies a type or namespace within the type
1117  /// system. For example, given:
1118  ///
1119  /// \code
1120  /// namespace N {
1121  ///   struct S {
1122  ///     template<typename T> struct X { typename T* type; };
1123  ///   };
1124  /// }
1125  ///
1126  /// template<typename T> struct Y {
1127  ///   typename N::S::X<T>::type member;
1128  /// };
1129  /// \endcode
1130  ///
1131  /// Here, the nested-name-specifier for N::S::X<T>:: will be
1132  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1133  /// by declarations in the type system and the canonical type for
1134  /// the template type parameter 'T' is template-param-0-0.
1135  NestedNameSpecifier *
1136  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS);
1137
1138  /// \brief Retrieves the default calling convention to use for
1139  /// C++ instance methods.
1140  CallingConv getDefaultMethodCallConv();
1141
1142  /// \brief Retrieves the canonical representation of the given
1143  /// calling convention.
1144  CallingConv getCanonicalCallConv(CallingConv CC) {
1145    if (CC == CC_C)
1146      return CC_Default;
1147    return CC;
1148  }
1149
1150  /// \brief Determines whether two calling conventions name the same
1151  /// calling convention.
1152  bool isSameCallConv(CallingConv lcc, CallingConv rcc) {
1153    return (getCanonicalCallConv(lcc) == getCanonicalCallConv(rcc));
1154  }
1155
1156  /// \brief Retrieves the "canonical" template name that refers to a
1157  /// given template.
1158  ///
1159  /// The canonical template name is the simplest expression that can
1160  /// be used to refer to a given template. For most templates, this
1161  /// expression is just the template declaration itself. For example,
1162  /// the template std::vector can be referred to via a variety of
1163  /// names---std::vector, ::std::vector, vector (if vector is in
1164  /// scope), etc.---but all of these names map down to the same
1165  /// TemplateDecl, which is used to form the canonical template name.
1166  ///
1167  /// Dependent template names are more interesting. Here, the
1168  /// template name could be something like T::template apply or
1169  /// std::allocator<T>::template rebind, where the nested name
1170  /// specifier itself is dependent. In this case, the canonical
1171  /// template name uses the shortest form of the dependent
1172  /// nested-name-specifier, which itself contains all canonical
1173  /// types, values, and templates.
1174  TemplateName getCanonicalTemplateName(TemplateName Name);
1175
1176  /// \brief Determine whether the given template names refer to the same
1177  /// template.
1178  bool hasSameTemplateName(TemplateName X, TemplateName Y);
1179
1180  /// \brief Retrieve the "canonical" template argument.
1181  ///
1182  /// The canonical template argument is the simplest template argument
1183  /// (which may be a type, value, expression, or declaration) that
1184  /// expresses the value of the argument.
1185  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg);
1186
1187  /// Type Query functions.  If the type is an instance of the specified class,
1188  /// return the Type pointer for the underlying maximally pretty type.  This
1189  /// is a member of ASTContext because this may need to do some amount of
1190  /// canonicalization, e.g. to move type qualifiers into the element type.
1191  const ArrayType *getAsArrayType(QualType T);
1192  const ConstantArrayType *getAsConstantArrayType(QualType T) {
1193    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1194  }
1195  const VariableArrayType *getAsVariableArrayType(QualType T) {
1196    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1197  }
1198  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) {
1199    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1200  }
1201  const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T) {
1202    return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1203  }
1204
1205  /// getBaseElementType - Returns the innermost element type of an array type.
1206  /// For example, will return "int" for int[m][n]
1207  QualType getBaseElementType(const ArrayType *VAT);
1208
1209  /// getBaseElementType - Returns the innermost element type of a type
1210  /// (which needn't actually be an array type).
1211  QualType getBaseElementType(QualType QT);
1212
1213  /// getConstantArrayElementCount - Returns number of constant array elements.
1214  uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1215
1216  /// getArrayDecayedType - Return the properly qualified result of decaying the
1217  /// specified array type to a pointer.  This operation is non-trivial when
1218  /// handling typedefs etc.  The canonical type of "T" must be an array type,
1219  /// this returns a pointer to a properly qualified element of the array.
1220  ///
1221  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1222  QualType getArrayDecayedType(QualType T);
1223
1224  /// getPromotedIntegerType - Returns the type that Promotable will
1225  /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
1226  /// integer type.
1227  QualType getPromotedIntegerType(QualType PromotableType);
1228
1229  /// \brief Whether this is a promotable bitfield reference according
1230  /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1231  ///
1232  /// \returns the type this bit-field will promote to, or NULL if no
1233  /// promotion occurs.
1234  QualType isPromotableBitField(Expr *E);
1235
1236  /// getIntegerTypeOrder - Returns the highest ranked integer type:
1237  /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1238  /// LHS < RHS, return -1.
1239  int getIntegerTypeOrder(QualType LHS, QualType RHS);
1240
1241  /// getFloatingTypeOrder - Compare the rank of the two specified floating
1242  /// point types, ignoring the domain of the type (i.e. 'double' ==
1243  /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1244  /// LHS < RHS, return -1.
1245  int getFloatingTypeOrder(QualType LHS, QualType RHS);
1246
1247  /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1248  /// point or a complex type (based on typeDomain/typeSize).
1249  /// 'typeDomain' is a real floating point or complex type.
1250  /// 'typeSize' is a real floating point or complex type.
1251  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1252                                             QualType typeDomain) const;
1253
1254private:
1255  // Helper for integer ordering
1256  unsigned getIntegerRank(Type* T);
1257
1258public:
1259
1260  //===--------------------------------------------------------------------===//
1261  //                    Type Compatibility Predicates
1262  //===--------------------------------------------------------------------===//
1263
1264  /// Compatibility predicates used to check assignment expressions.
1265  bool typesAreCompatible(QualType T1, QualType T2,
1266                          bool CompareUnqualified = false); // C99 6.2.7p1
1267
1268  bool typesAreBlockPointerCompatible(QualType, QualType);
1269
1270  bool isObjCIdType(QualType T) const {
1271    return T == ObjCIdTypedefType;
1272  }
1273  bool isObjCClassType(QualType T) const {
1274    return T == ObjCClassTypedefType;
1275  }
1276  bool isObjCSelType(QualType T) const {
1277    return T == ObjCSelTypedefType;
1278  }
1279  bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
1280  bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
1281                                         bool ForCompare);
1282
1283  bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
1284
1285  // Check the safety of assignment from LHS to RHS
1286  bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
1287                               const ObjCObjectPointerType *RHSOPT);
1288  bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
1289                               const ObjCObjectType *RHS);
1290  bool canAssignObjCInterfacesInBlockPointer(
1291                                          const ObjCObjectPointerType *LHSOPT,
1292                                          const ObjCObjectPointerType *RHSOPT);
1293  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
1294  QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
1295                                   const ObjCObjectPointerType *RHSOPT);
1296  bool canBindObjCObjectType(QualType To, QualType From);
1297
1298  // Functions for calculating composite types
1299  QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
1300                      bool Unqualified = false);
1301  QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
1302                              bool Unqualified = false);
1303  QualType mergeFunctionArgumentTypes(QualType, QualType,
1304                                      bool OfBlockPointer=false,
1305                                      bool Unqualified = false);
1306  QualType mergeTransparentUnionType(QualType, QualType,
1307                                     bool OfBlockPointer=false,
1308                                     bool Unqualified = false);
1309
1310  QualType mergeObjCGCQualifiers(QualType, QualType);
1311
1312  void ResetObjCLayout(const ObjCContainerDecl *CD) {
1313    ObjCLayouts[CD] = 0;
1314  }
1315
1316  //===--------------------------------------------------------------------===//
1317  //                    Integer Predicates
1318  //===--------------------------------------------------------------------===//
1319
1320  // The width of an integer, as defined in C99 6.2.6.2. This is the number
1321  // of bits in an integer type excluding any padding bits.
1322  unsigned getIntWidth(QualType T);
1323
1324  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
1325  // unsigned integer type.  This method takes a signed type, and returns the
1326  // corresponding unsigned integer type.
1327  QualType getCorrespondingUnsignedType(QualType T);
1328
1329  //===--------------------------------------------------------------------===//
1330  //                    Type Iterators.
1331  //===--------------------------------------------------------------------===//
1332
1333  typedef std::vector<Type*>::iterator       type_iterator;
1334  typedef std::vector<Type*>::const_iterator const_type_iterator;
1335
1336  type_iterator types_begin() { return Types.begin(); }
1337  type_iterator types_end() { return Types.end(); }
1338  const_type_iterator types_begin() const { return Types.begin(); }
1339  const_type_iterator types_end() const { return Types.end(); }
1340
1341  //===--------------------------------------------------------------------===//
1342  //                    Integer Values
1343  //===--------------------------------------------------------------------===//
1344
1345  /// MakeIntValue - Make an APSInt of the appropriate width and
1346  /// signedness for the given \arg Value and integer \arg Type.
1347  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) {
1348    llvm::APSInt Res(getIntWidth(Type), !Type->isSignedIntegerType());
1349    Res = Value;
1350    return Res;
1351  }
1352
1353  /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1354  ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
1355  /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1356  ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
1357
1358  /// \brief Set the implementation of ObjCInterfaceDecl.
1359  void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1360                             ObjCImplementationDecl *ImplD);
1361  /// \brief Set the implementation of ObjCCategoryDecl.
1362  void setObjCImplementation(ObjCCategoryDecl *CatD,
1363                             ObjCCategoryImplDecl *ImplD);
1364
1365  /// \brief Set the copy inialization expression of a block var decl.
1366  void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
1367  /// \brief Get the copy initialization expression of VarDecl,or NULL if
1368  /// none exists.
1369  Expr *getBlockVarCopyInits(VarDecl*VD);
1370
1371  /// \brief Allocate an uninitialized TypeSourceInfo.
1372  ///
1373  /// The caller should initialize the memory held by TypeSourceInfo using
1374  /// the TypeLoc wrappers.
1375  ///
1376  /// \param T the type that will be the basis for type source info. This type
1377  /// should refer to how the declarator was written in source code, not to
1378  /// what type semantic analysis resolved the declarator to.
1379  ///
1380  /// \param Size the size of the type info to create, or 0 if the size
1381  /// should be calculated based on the type.
1382  TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0);
1383
1384  /// \brief Allocate a TypeSourceInfo where all locations have been
1385  /// initialized to a given location, which defaults to the empty
1386  /// location.
1387  TypeSourceInfo *
1388  getTrivialTypeSourceInfo(QualType T, SourceLocation Loc = SourceLocation());
1389
1390  TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
1391
1392  /// \brief Add a deallocation callback that will be invoked when the
1393  /// ASTContext is destroyed.
1394  ///
1395  /// \brief Callback A callback function that will be invoked on destruction.
1396  ///
1397  /// \brief Data Pointer data that will be provided to the callback function
1398  /// when it is called.
1399  void AddDeallocation(void (*Callback)(void*), void *Data);
1400
1401  GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD);
1402  GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
1403
1404  /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
1405  /// lazily, only when used; this is only relevant for function or file scoped
1406  /// var definitions.
1407  ///
1408  /// \returns true if the function/var must be CodeGen'ed/deserialized even if
1409  /// it is not used.
1410  bool DeclMustBeEmitted(const Decl *D);
1411
1412  //===--------------------------------------------------------------------===//
1413  //                    Statistics
1414  //===--------------------------------------------------------------------===//
1415
1416  /// \brief The number of implicitly-declared default constructors.
1417  static unsigned NumImplicitDefaultConstructors;
1418
1419  /// \brief The number of implicitly-declared default constructors for
1420  /// which declarations were built.
1421  static unsigned NumImplicitDefaultConstructorsDeclared;
1422
1423  /// \brief The number of implicitly-declared copy constructors.
1424  static unsigned NumImplicitCopyConstructors;
1425
1426  /// \brief The number of implicitly-declared copy constructors for
1427  /// which declarations were built.
1428  static unsigned NumImplicitCopyConstructorsDeclared;
1429
1430  /// \brief The number of implicitly-declared copy assignment operators.
1431  static unsigned NumImplicitCopyAssignmentOperators;
1432
1433  /// \brief The number of implicitly-declared copy assignment operators for
1434  /// which declarations were built.
1435  static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
1436
1437  /// \brief The number of implicitly-declared destructors.
1438  static unsigned NumImplicitDestructors;
1439
1440  /// \brief The number of implicitly-declared destructors for which
1441  /// declarations were built.
1442  static unsigned NumImplicitDestructorsDeclared;
1443
1444private:
1445  ASTContext(const ASTContext&); // DO NOT IMPLEMENT
1446  void operator=(const ASTContext&); // DO NOT IMPLEMENT
1447
1448  void InitBuiltinTypes();
1449  void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
1450
1451  // Return the ObjC type encoding for a given type.
1452  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
1453                                  bool ExpandPointedToStructures,
1454                                  bool ExpandStructures,
1455                                  const FieldDecl *Field,
1456                                  bool OutermostType = false,
1457                                  bool EncodingProperty = false);
1458
1459  const ASTRecordLayout &getObjCLayout(const ObjCInterfaceDecl *D,
1460                                       const ObjCImplementationDecl *Impl);
1461
1462private:
1463  /// \brief A set of deallocations that should be performed when the
1464  /// ASTContext is destroyed.
1465  llvm::SmallVector<std::pair<void (*)(void*), void *>, 16> Deallocations;
1466
1467  // FIXME: This currently contains the set of StoredDeclMaps used
1468  // by DeclContext objects.  This probably should not be in ASTContext,
1469  // but we include it here so that ASTContext can quickly deallocate them.
1470  llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
1471
1472  /// \brief A counter used to uniquely identify "blocks".
1473  unsigned int UniqueBlockByRefTypeID;
1474  unsigned int UniqueBlockParmTypeID;
1475
1476  friend class DeclContext;
1477  friend class DeclarationNameTable;
1478  void ReleaseDeclContextMaps();
1479};
1480
1481/// @brief Utility function for constructing a nullary selector.
1482static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
1483  IdentifierInfo* II = &Ctx.Idents.get(name);
1484  return Ctx.Selectors.getSelector(0, &II);
1485}
1486
1487/// @brief Utility function for constructing an unary selector.
1488static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
1489  IdentifierInfo* II = &Ctx.Idents.get(name);
1490  return Ctx.Selectors.getSelector(1, &II);
1491}
1492
1493}  // end namespace clang
1494
1495// operator new and delete aren't allowed inside namespaces.
1496// The throw specifications are mandated by the standard.
1497/// @brief Placement new for using the ASTContext's allocator.
1498///
1499/// This placement form of operator new uses the ASTContext's allocator for
1500/// obtaining memory. It is a non-throwing new, which means that it returns
1501/// null on error. (If that is what the allocator does. The current does, so if
1502/// this ever changes, this operator will have to be changed, too.)
1503/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
1504/// @code
1505/// // Default alignment (8)
1506/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
1507/// // Specific alignment
1508/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
1509/// @endcode
1510/// Please note that you cannot use delete on the pointer; it must be
1511/// deallocated using an explicit destructor call followed by
1512/// @c Context.Deallocate(Ptr).
1513///
1514/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
1515/// @param C The ASTContext that provides the allocator.
1516/// @param Alignment The alignment of the allocated memory (if the underlying
1517///                  allocator supports it).
1518/// @return The allocated memory. Could be NULL.
1519inline void *operator new(size_t Bytes, clang::ASTContext &C,
1520                          size_t Alignment) throw () {
1521  return C.Allocate(Bytes, Alignment);
1522}
1523/// @brief Placement delete companion to the new above.
1524///
1525/// This operator is just a companion to the new above. There is no way of
1526/// invoking it directly; see the new operator for more details. This operator
1527/// is called implicitly by the compiler if a placement new expression using
1528/// the ASTContext throws in the object constructor.
1529inline void operator delete(void *Ptr, clang::ASTContext &C, size_t)
1530              throw () {
1531  C.Deallocate(Ptr);
1532}
1533
1534/// This placement form of operator new[] uses the ASTContext's allocator for
1535/// obtaining memory. It is a non-throwing new[], which means that it returns
1536/// null on error.
1537/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
1538/// @code
1539/// // Default alignment (8)
1540/// char *data = new (Context) char[10];
1541/// // Specific alignment
1542/// char *data = new (Context, 4) char[10];
1543/// @endcode
1544/// Please note that you cannot use delete on the pointer; it must be
1545/// deallocated using an explicit destructor call followed by
1546/// @c Context.Deallocate(Ptr).
1547///
1548/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
1549/// @param C The ASTContext that provides the allocator.
1550/// @param Alignment The alignment of the allocated memory (if the underlying
1551///                  allocator supports it).
1552/// @return The allocated memory. Could be NULL.
1553inline void *operator new[](size_t Bytes, clang::ASTContext& C,
1554                            size_t Alignment = 8) throw () {
1555  return C.Allocate(Bytes, Alignment);
1556}
1557
1558/// @brief Placement delete[] companion to the new[] above.
1559///
1560/// This operator is just a companion to the new[] above. There is no way of
1561/// invoking it directly; see the new[] operator for more details. This operator
1562/// is called implicitly by the compiler if a placement new[] expression using
1563/// the ASTContext throws in the object constructor.
1564inline void operator delete[](void *Ptr, clang::ASTContext &C, size_t)
1565              throw () {
1566  C.Deallocate(Ptr);
1567}
1568
1569#endif
1570