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