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