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