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