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