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