ASTContext.h revision 538bbe597b935a74d95c668ad209536753f13481
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/// \file
11/// \brief Defines the clang::ASTContext interface.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
16#define LLVM_CLANG_AST_ASTCONTEXT_H
17
18#include "clang/AST/ASTTypeTraits.h"
19#include "clang/AST/CanonicalType.h"
20#include "clang/AST/CommentCommandTraits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/LambdaMangleContext.h"
23#include "clang/AST/NestedNameSpecifier.h"
24#include "clang/AST/PrettyPrinter.h"
25#include "clang/AST/RawCommentList.h"
26#include "clang/AST/RecursiveASTVisitor.h"
27#include "clang/AST/TemplateName.h"
28#include "clang/AST/Type.h"
29#include "clang/Basic/AddressSpaces.h"
30#include "clang/Basic/IdentifierTable.h"
31#include "clang/Basic/LangOptions.h"
32#include "clang/Basic/OperatorKinds.h"
33#include "clang/Basic/PartialDiagnostic.h"
34#include "clang/Basic/VersionTuple.h"
35#include "llvm/ADT/DenseMap.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/IntrusiveRefCntPtr.h"
38#include "llvm/ADT/OwningPtr.h"
39#include "llvm/ADT/SmallPtrSet.h"
40#include "llvm/ADT/TinyPtrVector.h"
41#include "llvm/Support/Allocator.h"
42#include <vector>
43
44namespace llvm {
45  struct fltSemantics;
46}
47
48namespace clang {
49  class FileManager;
50  class ASTRecordLayout;
51  class BlockExpr;
52  class CharUnits;
53  class DiagnosticsEngine;
54  class Expr;
55  class ExternalASTSource;
56  class ASTMutationListener;
57  class IdentifierTable;
58  class SelectorTable;
59  class TargetInfo;
60  class CXXABI;
61  // Decls
62  class MangleContext;
63  class ObjCIvarDecl;
64  class ObjCPropertyDecl;
65  class UnresolvedSetIterator;
66  class UsingDecl;
67  class UsingShadowDecl;
68
69  namespace Builtin { class Context; }
70
71  namespace comments {
72    class FullComment;
73  }
74
75/// \brief Holds long-lived AST nodes (such as types and decls) that can be
76/// referred to throughout the semantic analysis of a file.
77class ASTContext : public RefCountedBase<ASTContext> {
78  ASTContext &this_() { return *this; }
79
80  mutable SmallVector<Type *, 0> Types;
81  mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
82  mutable llvm::FoldingSet<ComplexType> ComplexTypes;
83  mutable llvm::FoldingSet<PointerType> PointerTypes;
84  mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
85  mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
86  mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
87  mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
88  mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
89  mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
90  mutable std::vector<VariableArrayType*> VariableArrayTypes;
91  mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
92  mutable llvm::FoldingSet<DependentSizedExtVectorType>
93    DependentSizedExtVectorTypes;
94  mutable llvm::FoldingSet<VectorType> VectorTypes;
95  mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
96  mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
97    FunctionProtoTypes;
98  mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
99  mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
100  mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
101  mutable llvm::FoldingSet<SubstTemplateTypeParmType>
102    SubstTemplateTypeParmTypes;
103  mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
104    SubstTemplateTypeParmPackTypes;
105  mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
106    TemplateSpecializationTypes;
107  mutable llvm::FoldingSet<ParenType> ParenTypes;
108  mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
109  mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
110  mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
111                                     ASTContext&>
112    DependentTemplateSpecializationTypes;
113  llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
114  mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
115  mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
116  mutable llvm::FoldingSet<AutoType> AutoTypes;
117  mutable llvm::FoldingSet<AtomicType> AtomicTypes;
118  llvm::FoldingSet<AttributedType> AttributedTypes;
119
120  mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
121  mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
122  mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
123    SubstTemplateTemplateParms;
124  mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
125                                     ASTContext&>
126    SubstTemplateTemplateParmPacks;
127
128  /// \brief The set of nested name specifiers.
129  ///
130  /// This set is managed by the NestedNameSpecifier class.
131  mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
132  mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
133  friend class NestedNameSpecifier;
134
135  /// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
136  ///
137  /// This is lazily created.  This is intentionally not serialized.
138  mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
139    ASTRecordLayouts;
140  mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
141    ObjCLayouts;
142
143  /// \brief A cache from types to size and alignment information.
144  typedef llvm::DenseMap<const Type*,
145                         std::pair<uint64_t, unsigned> > TypeInfoMap;
146  mutable TypeInfoMap MemoizedTypeInfo;
147
148  /// \brief A cache mapping from CXXRecordDecls to key functions.
149  llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*> KeyFunctions;
150
151  /// \brief Mapping from ObjCContainers to their ObjCImplementations.
152  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
153
154  /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
155  /// interface.
156  llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
157
158  /// \brief Mapping from __block VarDecls to their copy initialization expr.
159  llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
160
161  /// \brief Mapping from class scope functions specialization to their
162  /// template patterns.
163  llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
164    ClassScopeSpecializationPattern;
165
166  /// \brief Representation of a "canonical" template template parameter that
167  /// is used in canonical template names.
168  class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
169    TemplateTemplateParmDecl *Parm;
170
171  public:
172    CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
173      : Parm(Parm) { }
174
175    TemplateTemplateParmDecl *getParam() const { return Parm; }
176
177    void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
178
179    static void Profile(llvm::FoldingSetNodeID &ID,
180                        TemplateTemplateParmDecl *Parm);
181  };
182  mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
183    CanonTemplateTemplateParms;
184
185  TemplateTemplateParmDecl *
186    getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
187
188  /// \brief The typedef for the __int128_t type.
189  mutable TypedefDecl *Int128Decl;
190
191  /// \brief The typedef for the __uint128_t type.
192  mutable TypedefDecl *UInt128Decl;
193
194  /// \brief The typedef for the target specific predefined
195  /// __builtin_va_list type.
196  mutable TypedefDecl *BuiltinVaListDecl;
197
198  /// \brief The typedef for the predefined \c id type.
199  mutable TypedefDecl *ObjCIdDecl;
200
201  /// \brief The typedef for the predefined \c SEL type.
202  mutable TypedefDecl *ObjCSelDecl;
203
204  /// \brief The typedef for the predefined \c Class type.
205  mutable TypedefDecl *ObjCClassDecl;
206
207  /// \brief The typedef for the predefined \c Protocol class in Objective-C.
208  mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
209
210  /// \brief The typedef for the predefined 'BOOL' type.
211  mutable TypedefDecl *BOOLDecl;
212
213  // Typedefs which may be provided defining the structure of Objective-C
214  // pseudo-builtins
215  QualType ObjCIdRedefinitionType;
216  QualType ObjCClassRedefinitionType;
217  QualType ObjCSelRedefinitionType;
218
219  QualType ObjCConstantStringType;
220  mutable RecordDecl *CFConstantStringTypeDecl;
221
222  mutable QualType ObjCSuperType;
223
224  QualType ObjCNSStringType;
225
226  /// \brief The typedef declaration for the Objective-C "instancetype" type.
227  TypedefDecl *ObjCInstanceTypeDecl;
228
229  /// \brief The type for the C FILE type.
230  TypeDecl *FILEDecl;
231
232  /// \brief The type for the C jmp_buf type.
233  TypeDecl *jmp_bufDecl;
234
235  /// \brief The type for the C sigjmp_buf type.
236  TypeDecl *sigjmp_bufDecl;
237
238  /// \brief The type for the C ucontext_t type.
239  TypeDecl *ucontext_tDecl;
240
241  /// \brief Type for the Block descriptor for Blocks CodeGen.
242  ///
243  /// Since this is only used for generation of debug info, it is not
244  /// serialized.
245  mutable RecordDecl *BlockDescriptorType;
246
247  /// \brief Type for the Block descriptor for Blocks CodeGen.
248  ///
249  /// Since this is only used for generation of debug info, it is not
250  /// serialized.
251  mutable RecordDecl *BlockDescriptorExtendedType;
252
253  /// \brief Declaration for the CUDA cudaConfigureCall function.
254  FunctionDecl *cudaConfigureCallDecl;
255
256  TypeSourceInfo NullTypeSourceInfo;
257
258  /// \brief Keeps track of all declaration attributes.
259  ///
260  /// Since so few decls have attrs, we keep them in a hash map instead of
261  /// wasting space in the Decl class.
262  llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
263
264  /// \brief Keeps track of the static data member templates from which
265  /// static data members of class template specializations were instantiated.
266  ///
267  /// This data structure stores the mapping from instantiations of static
268  /// data members to the static data member representations within the
269  /// class template from which they were instantiated along with the kind
270  /// of instantiation or specialization (a TemplateSpecializationKind - 1).
271  ///
272  /// Given the following example:
273  ///
274  /// \code
275  /// template<typename T>
276  /// struct X {
277  ///   static T value;
278  /// };
279  ///
280  /// template<typename T>
281  ///   T X<T>::value = T(17);
282  ///
283  /// int *x = &X<int>::value;
284  /// \endcode
285  ///
286  /// This mapping will contain an entry that maps from the VarDecl for
287  /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
288  /// class template X) and will be marked TSK_ImplicitInstantiation.
289  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>
290    InstantiatedFromStaticDataMember;
291
292  /// \brief Keeps track of the declaration from which a UsingDecl was
293  /// created during instantiation.
294  ///
295  /// The source declaration is always a UsingDecl, an UnresolvedUsingValueDecl,
296  /// or an UnresolvedUsingTypenameDecl.
297  ///
298  /// For example:
299  /// \code
300  /// template<typename T>
301  /// struct A {
302  ///   void f();
303  /// };
304  ///
305  /// template<typename T>
306  /// struct B : A<T> {
307  ///   using A<T>::f;
308  /// };
309  ///
310  /// template struct B<int>;
311  /// \endcode
312  ///
313  /// This mapping will contain an entry that maps from the UsingDecl in
314  /// B<int> to the UnresolvedUsingDecl in B<T>.
315  llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
316
317  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
318    InstantiatedFromUsingShadowDecl;
319
320  llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
321
322  /// \brief Mapping that stores the methods overridden by a given C++
323  /// member function.
324  ///
325  /// Since most C++ member functions aren't virtual and therefore
326  /// don't override anything, we store the overridden functions in
327  /// this map on the side rather than within the CXXMethodDecl structure.
328  typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
329  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
330
331  /// \brief Mapping from each declaration context to its corresponding lambda
332  /// mangling context.
333  llvm::DenseMap<const DeclContext *, LambdaMangleContext> LambdaMangleContexts;
334
335  llvm::DenseMap<const DeclContext *, unsigned> UnnamedMangleContexts;
336  llvm::DenseMap<const TagDecl *, unsigned> UnnamedMangleNumbers;
337
338  /// \brief Mapping that stores parameterIndex values for ParmVarDecls when
339  /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
340  typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
341  ParameterIndexTable ParamIndices;
342
343  ImportDecl *FirstLocalImport;
344  ImportDecl *LastLocalImport;
345
346  TranslationUnitDecl *TUDecl;
347
348  /// \brief The associated SourceManager object.a
349  SourceManager &SourceMgr;
350
351  /// \brief The language options used to create the AST associated with
352  ///  this ASTContext object.
353  LangOptions &LangOpts;
354
355  /// \brief The allocator used to create AST objects.
356  ///
357  /// AST objects are never destructed; rather, all memory associated with the
358  /// AST objects will be released when the ASTContext itself is destroyed.
359  mutable llvm::BumpPtrAllocator BumpAlloc;
360
361  /// \brief Allocator for partial diagnostics.
362  PartialDiagnostic::StorageAllocator DiagAllocator;
363
364  /// \brief The current C++ ABI.
365  OwningPtr<CXXABI> ABI;
366  CXXABI *createCXXABI(const TargetInfo &T);
367
368  /// \brief The logical -> physical address space map.
369  const LangAS::Map *AddrSpaceMap;
370
371  friend class ASTDeclReader;
372  friend class ASTReader;
373  friend class ASTWriter;
374  friend class CXXRecordDecl;
375
376  const TargetInfo *Target;
377  clang::PrintingPolicy PrintingPolicy;
378
379public:
380  IdentifierTable &Idents;
381  SelectorTable &Selectors;
382  Builtin::Context &BuiltinInfo;
383  mutable DeclarationNameTable DeclarationNames;
384  OwningPtr<ExternalASTSource> ExternalSource;
385  ASTMutationListener *Listener;
386
387  /// \brief Contains parents of a node.
388  typedef llvm::SmallVector<ast_type_traits::DynTypedNode, 1> ParentVector;
389
390  /// \brief Maps from a node to its parents.
391  typedef llvm::DenseMap<const void *, ParentVector> ParentMap;
392
393  /// \brief Returns the parents of the given node.
394  ///
395  /// Note that this will lazily compute the parents of all nodes
396  /// and store them for later retrieval. Thus, the first call is O(n)
397  /// in the number of AST nodes.
398  ///
399  /// Caveats and FIXMEs:
400  /// Calculating the parent map over all AST nodes will need to load the
401  /// full AST. This can be undesirable in the case where the full AST is
402  /// expensive to create (for example, when using precompiled header
403  /// preambles). Thus, there are good opportunities for optimization here.
404  /// One idea is to walk the given node downwards, looking for references
405  /// to declaration contexts - once a declaration context is found, compute
406  /// the parent map for the declaration context; if that can satisfy the
407  /// request, loading the whole AST can be avoided. Note that this is made
408  /// more complex by statements in templates having multiple parents - those
409  /// problems can be solved by building closure over the templated parts of
410  /// the AST, which also avoids touching large parts of the AST.
411  /// Additionally, we will want to add an interface to already give a hint
412  /// where to search for the parents, for example when looking at a statement
413  /// inside a certain function.
414  ///
415  /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
416  /// NestedNameSpecifier or NestedNameSpecifierLoc.
417  template <typename NodeT>
418  ParentVector getParents(const NodeT &Node) {
419    return getParents(ast_type_traits::DynTypedNode::create(Node));
420  }
421
422  ParentVector getParents(const ast_type_traits::DynTypedNode &Node) {
423    assert(Node.getMemoizationData() &&
424           "Invariant broken: only nodes that support memoization may be "
425           "used in the parent map.");
426    if (!AllParents) {
427      // We always need to run over the whole translation unit, as
428      // hasAncestor can escape any subtree.
429      AllParents.reset(
430          ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
431    }
432    ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
433    if (I == AllParents->end()) {
434      return ParentVector();
435    }
436    return I->second;
437  }
438
439  const clang::PrintingPolicy &getPrintingPolicy() const {
440    return PrintingPolicy;
441  }
442
443  void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
444    PrintingPolicy = Policy;
445  }
446
447  SourceManager& getSourceManager() { return SourceMgr; }
448  const SourceManager& getSourceManager() const { return SourceMgr; }
449
450  llvm::BumpPtrAllocator &getAllocator() const {
451    return BumpAlloc;
452  }
453
454  void *Allocate(unsigned Size, unsigned Align = 8) const {
455    return BumpAlloc.Allocate(Size, Align);
456  }
457  void Deallocate(void *Ptr) const { }
458
459  /// Return the total amount of physical memory allocated for representing
460  /// AST nodes and type information.
461  size_t getASTAllocatedMemory() const {
462    return BumpAlloc.getTotalMemory();
463  }
464  /// Return the total memory used for various side tables.
465  size_t getSideTableAllocatedMemory() const;
466
467  PartialDiagnostic::StorageAllocator &getDiagAllocator() {
468    return DiagAllocator;
469  }
470
471  const TargetInfo &getTargetInfo() const { return *Target; }
472
473  bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
474
475  const LangOptions& getLangOpts() const { return LangOpts; }
476
477  DiagnosticsEngine &getDiagnostics() const;
478
479  FullSourceLoc getFullLoc(SourceLocation Loc) const {
480    return FullSourceLoc(Loc,SourceMgr);
481  }
482
483  /// \brief All comments in this translation unit.
484  RawCommentList Comments;
485
486  /// \brief True if comments are already loaded from ExternalASTSource.
487  mutable bool CommentsLoaded;
488
489  class RawCommentAndCacheFlags {
490  public:
491    enum Kind {
492      /// We searched for a comment attached to the particular declaration, but
493      /// didn't find any.
494      ///
495      /// getRaw() == 0.
496      NoCommentInDecl = 0,
497
498      /// We have found a comment attached to this particular declaration.
499      ///
500      /// getRaw() != 0.
501      FromDecl,
502
503      /// This declaration does not have an attached comment, and we have
504      /// searched the redeclaration chain.
505      ///
506      /// If getRaw() == 0, the whole redeclaration chain does not have any
507      /// comments.
508      ///
509      /// If getRaw() != 0, it is a comment propagated from other
510      /// redeclaration.
511      FromRedecl
512    };
513
514    Kind getKind() const LLVM_READONLY {
515      return Data.getInt();
516    }
517
518    void setKind(Kind K) {
519      Data.setInt(K);
520    }
521
522    const RawComment *getRaw() const LLVM_READONLY {
523      return Data.getPointer();
524    }
525
526    void setRaw(const RawComment *RC) {
527      Data.setPointer(RC);
528    }
529
530    const Decl *getOriginalDecl() const LLVM_READONLY {
531      return OriginalDecl;
532    }
533
534    void setOriginalDecl(const Decl *Orig) {
535      OriginalDecl = Orig;
536    }
537
538  private:
539    llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
540    const Decl *OriginalDecl;
541  };
542
543  /// \brief Mapping from declarations to comments attached to any
544  /// redeclaration.
545  ///
546  /// Raw comments are owned by Comments list.  This mapping is populated
547  /// lazily.
548  mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
549
550  /// \brief Mapping from declarations to parsed comments attached to any
551  /// redeclaration.
552  mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
553
554  /// \brief Return the documentation comment attached to a given declaration,
555  /// without looking into cache.
556  RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
557
558public:
559  RawCommentList &getRawCommentList() {
560    return Comments;
561  }
562
563  void addComment(const RawComment &RC) {
564    assert(LangOpts.RetainCommentsFromSystemHeaders ||
565           !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
566    Comments.addComment(RC, BumpAlloc);
567  }
568
569  /// \brief Return the documentation comment attached to a given declaration.
570  /// Returns NULL if no comment is attached.
571  ///
572  /// \param OriginalDecl if not NULL, is set to declaration AST node that had
573  /// the comment, if the comment we found comes from a redeclaration.
574  const RawComment *getRawCommentForAnyRedecl(
575                                      const Decl *D,
576                                      const Decl **OriginalDecl = NULL) const;
577
578  /// Return parsed documentation comment attached to a given declaration.
579  /// Returns NULL if no comment is attached.
580  ///
581  /// \param PP the Preprocessor used with this TU.  Could be NULL if
582  /// preprocessor is not available.
583  comments::FullComment *getCommentForDecl(const Decl *D,
584                                           const Preprocessor *PP) const;
585
586  /// Return parsed documentation comment attached to a given declaration.
587  /// Returns NULL if no comment is attached. Does not look at any
588  /// redeclarations of the declaration.
589  comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
590
591  comments::FullComment *cloneFullComment(comments::FullComment *FC,
592                                         const Decl *D) const;
593
594private:
595  mutable comments::CommandTraits CommentCommandTraits;
596
597public:
598  comments::CommandTraits &getCommentCommandTraits() const {
599    return CommentCommandTraits;
600  }
601
602  /// \brief Retrieve the attributes for the given declaration.
603  AttrVec& getDeclAttrs(const Decl *D);
604
605  /// \brief Erase the attributes corresponding to the given declaration.
606  void eraseDeclAttrs(const Decl *D);
607
608  /// \brief If this variable is an instantiated static data member of a
609  /// class template specialization, returns the templated static data member
610  /// from which it was instantiated.
611  MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
612                                                           const VarDecl *Var);
613
614  FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
615
616  void setClassScopeSpecializationPattern(FunctionDecl *FD,
617                                          FunctionDecl *Pattern);
618
619  /// \brief Note that the static data member \p Inst is an instantiation of
620  /// the static data member template \p Tmpl of a class template.
621  void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
622                                           TemplateSpecializationKind TSK,
623                        SourceLocation PointOfInstantiation = SourceLocation());
624
625  /// \brief If the given using decl \p Inst is an instantiation of a
626  /// (possibly unresolved) using decl from a template instantiation,
627  /// return it.
628  NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
629
630  /// \brief Remember that the using decl \p Inst is an instantiation
631  /// of the using decl \p Pattern of a class template.
632  void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
633
634  void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
635                                          UsingShadowDecl *Pattern);
636  UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
637
638  FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
639
640  void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
641
642  /// \brief Return \c true if \p FD is a zero-length bitfield which follows
643  /// the non-bitfield \p LastFD.
644  bool ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
645                                      const FieldDecl *LastFD) const;
646
647  /// \brief Return \c true if \p FD is a zero-length bitfield which follows
648  /// the bitfield \p LastFD.
649  bool ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
650                                   const FieldDecl *LastFD) const;
651
652  /// \brief Return \c true if \p FD is a bitfield which follows the bitfield
653  /// \p LastFD.
654  bool BitfieldFollowsBitfield(const FieldDecl *FD,
655                               const FieldDecl *LastFD) const;
656
657  /// \brief Return \c true if \p FD is not a bitfield which follows the
658  /// bitfield \p LastFD.
659  bool NonBitfieldFollowsBitfield(const FieldDecl *FD,
660                                  const FieldDecl *LastFD) const;
661
662  /// \brief Return \c true if \p FD is a bitfield which follows the
663  /// non-bitfield \p LastFD.
664  bool BitfieldFollowsNonBitfield(const FieldDecl *FD,
665                                  const FieldDecl *LastFD) const;
666
667  // Access to the set of methods overridden by the given C++ method.
668  typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
669  overridden_cxx_method_iterator
670  overridden_methods_begin(const CXXMethodDecl *Method) const;
671
672  overridden_cxx_method_iterator
673  overridden_methods_end(const CXXMethodDecl *Method) const;
674
675  unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
676
677  /// \brief Note that the given C++ \p Method overrides the given \p
678  /// Overridden method.
679  void addOverriddenMethod(const CXXMethodDecl *Method,
680                           const CXXMethodDecl *Overridden);
681
682  /// \brief Return C++ or ObjC overridden methods for the given \p Method.
683  ///
684  /// An ObjC method is considered to override any method in the class's
685  /// base classes, its protocols, or its categories' protocols, that has
686  /// the same selector and is of the same kind (class or instance).
687  /// A method in an implementation is not considered as overriding the same
688  /// method in the interface or its categories.
689  void getOverriddenMethods(
690                        const NamedDecl *Method,
691                        SmallVectorImpl<const NamedDecl *> &Overridden) const;
692
693  /// \brief Notify the AST context that a new import declaration has been
694  /// parsed or implicitly created within this translation unit.
695  void addedLocalImportDecl(ImportDecl *Import);
696
697  static ImportDecl *getNextLocalImport(ImportDecl *Import) {
698    return Import->NextLocalImport;
699  }
700
701  /// \brief Iterator that visits import declarations.
702  class import_iterator {
703    ImportDecl *Import;
704
705  public:
706    typedef ImportDecl               *value_type;
707    typedef ImportDecl               *reference;
708    typedef ImportDecl               *pointer;
709    typedef int                       difference_type;
710    typedef std::forward_iterator_tag iterator_category;
711
712    import_iterator() : Import() { }
713    explicit import_iterator(ImportDecl *Import) : Import(Import) { }
714
715    reference operator*() const { return Import; }
716    pointer operator->() const { return Import; }
717
718    import_iterator &operator++() {
719      Import = ASTContext::getNextLocalImport(Import);
720      return *this;
721    }
722
723    import_iterator operator++(int) {
724      import_iterator Other(*this);
725      ++(*this);
726      return Other;
727    }
728
729    friend bool operator==(import_iterator X, import_iterator Y) {
730      return X.Import == Y.Import;
731    }
732
733    friend bool operator!=(import_iterator X, import_iterator Y) {
734      return X.Import != Y.Import;
735    }
736  };
737
738  import_iterator local_import_begin() const {
739    return import_iterator(FirstLocalImport);
740  }
741  import_iterator local_import_end() const { return import_iterator(); }
742
743  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
744
745
746  // Builtin Types.
747  CanQualType VoidTy;
748  CanQualType BoolTy;
749  CanQualType CharTy;
750  CanQualType WCharTy;  // [C++ 3.9.1p5].
751  CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
752  CanQualType WIntTy;   // [C99 7.24.1], integer type unchanged by default promotions.
753  CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
754  CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
755  CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
756  CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
757  CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
758  CanQualType FloatTy, DoubleTy, LongDoubleTy;
759  CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
760  CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
761  CanQualType VoidPtrTy, NullPtrTy;
762  CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
763  CanQualType BuiltinFnTy;
764  CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
765  CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
766  CanQualType ObjCBuiltinBoolTy;
767  CanQualType OCLImage1dTy, OCLImage1dArrayTy, OCLImage1dBufferTy;
768  CanQualType OCLImage2dTy, OCLImage2dArrayTy;
769  CanQualType OCLImage3dTy;
770  CanQualType OCLSamplerTy, OCLEventTy;
771
772  // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
773  mutable QualType AutoDeductTy;     // Deduction against 'auto'.
774  mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
775
776  // Type used to help define __builtin_va_list for some targets.
777  // The type is built when constructing 'BuiltinVaListDecl'.
778  mutable QualType VaListTagTy;
779
780  ASTContext(LangOptions& LOpts, SourceManager &SM, const TargetInfo *t,
781             IdentifierTable &idents, SelectorTable &sels,
782             Builtin::Context &builtins,
783             unsigned size_reserve,
784             bool DelayInitialization = false);
785
786  ~ASTContext();
787
788  /// \brief Attach an external AST source to the AST context.
789  ///
790  /// The external AST source provides the ability to load parts of
791  /// the abstract syntax tree as needed from some external storage,
792  /// e.g., a precompiled header.
793  void setExternalSource(OwningPtr<ExternalASTSource> &Source);
794
795  /// \brief Retrieve a pointer to the external AST source associated
796  /// with this AST context, if any.
797  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
798
799  /// \brief Attach an AST mutation listener to the AST context.
800  ///
801  /// The AST mutation listener provides the ability to track modifications to
802  /// the abstract syntax tree entities committed after they were initially
803  /// created.
804  void setASTMutationListener(ASTMutationListener *Listener) {
805    this->Listener = Listener;
806  }
807
808  /// \brief Retrieve a pointer to the AST mutation listener associated
809  /// with this AST context, if any.
810  ASTMutationListener *getASTMutationListener() const { return Listener; }
811
812  void PrintStats() const;
813  const SmallVectorImpl<Type *>& getTypes() const { return Types; }
814
815  /// \brief Retrieve the declaration for the 128-bit signed integer type.
816  TypedefDecl *getInt128Decl() const;
817
818  /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
819  TypedefDecl *getUInt128Decl() const;
820
821  //===--------------------------------------------------------------------===//
822  //                           Type Constructors
823  //===--------------------------------------------------------------------===//
824
825private:
826  /// \brief Return a type with extended qualifiers.
827  QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
828
829  QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
830
831public:
832  /// \brief Return the uniqued reference to the type for an address space
833  /// qualified type with the specified type and address space.
834  ///
835  /// The resulting type has a union of the qualifiers from T and the address
836  /// space. If T already has an address space specifier, it is silently
837  /// replaced.
838  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
839
840  /// \brief Return the uniqued reference to the type for an Objective-C
841  /// gc-qualified type.
842  ///
843  /// The retulting type has a union of the qualifiers from T and the gc
844  /// attribute.
845  QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
846
847  /// \brief Return the uniqued reference to the type for a \c restrict
848  /// qualified type.
849  ///
850  /// The resulting type has a union of the qualifiers from \p T and
851  /// \c restrict.
852  QualType getRestrictType(QualType T) const {
853    return T.withFastQualifiers(Qualifiers::Restrict);
854  }
855
856  /// \brief Return the uniqued reference to the type for a \c volatile
857  /// qualified type.
858  ///
859  /// The resulting type has a union of the qualifiers from \p T and
860  /// \c volatile.
861  QualType getVolatileType(QualType T) const {
862    return T.withFastQualifiers(Qualifiers::Volatile);
863  }
864
865  /// \brief Return the uniqued reference to the type for a \c const
866  /// qualified type.
867  ///
868  /// The resulting type has a union of the qualifiers from \p T and \c const.
869  ///
870  /// It can be reasonably expected that this will always be equivalent to
871  /// calling T.withConst().
872  QualType getConstType(QualType T) const { return T.withConst(); }
873
874  /// \brief Change the ExtInfo on a function type.
875  const FunctionType *adjustFunctionType(const FunctionType *Fn,
876                                         FunctionType::ExtInfo EInfo);
877
878  /// \brief Change the result type of a function type once it is deduced.
879  void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
880
881  /// \brief Return the uniqued reference to the type for a complex
882  /// number with the specified element type.
883  QualType getComplexType(QualType T) const;
884  CanQualType getComplexType(CanQualType T) const {
885    return CanQualType::CreateUnsafe(getComplexType((QualType) T));
886  }
887
888  /// \brief Return the uniqued reference to the type for a pointer to
889  /// the specified type.
890  QualType getPointerType(QualType T) const;
891  CanQualType getPointerType(CanQualType T) const {
892    return CanQualType::CreateUnsafe(getPointerType((QualType) T));
893  }
894
895  /// \brief Return the uniqued reference to the atomic type for the specified
896  /// type.
897  QualType getAtomicType(QualType T) const;
898
899  /// \brief Return the uniqued reference to the type for a block of the
900  /// specified type.
901  QualType getBlockPointerType(QualType T) const;
902
903  /// Gets the struct used to keep track of the descriptor for pointer to
904  /// blocks.
905  QualType getBlockDescriptorType() const;
906
907  /// Gets the struct used to keep track of the extended descriptor for
908  /// pointer to blocks.
909  QualType getBlockDescriptorExtendedType() const;
910
911  void setcudaConfigureCallDecl(FunctionDecl *FD) {
912    cudaConfigureCallDecl = FD;
913  }
914  FunctionDecl *getcudaConfigureCallDecl() {
915    return cudaConfigureCallDecl;
916  }
917
918  /// Returns true iff we need copy/dispose helpers for the given type.
919  bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
920
921
922  /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set
923  /// to false in this case. If HasByrefExtendedLayout returns true, byref variable
924  /// has extended lifetime.
925  bool getByrefLifetime(QualType Ty,
926                        Qualifiers::ObjCLifetime &Lifetime,
927                        bool &HasByrefExtendedLayout) const;
928
929  /// \brief Return the uniqued reference to the type for an lvalue reference
930  /// to the specified type.
931  QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
932    const;
933
934  /// \brief Return the uniqued reference to the type for an rvalue reference
935  /// to the specified type.
936  QualType getRValueReferenceType(QualType T) const;
937
938  /// \brief Return the uniqued reference to the type for a member pointer to
939  /// the specified type in the specified class.
940  ///
941  /// The class \p Cls is a \c Type because it could be a dependent name.
942  QualType getMemberPointerType(QualType T, const Type *Cls) const;
943
944  /// \brief Return a non-unique reference to the type for a variable array of
945  /// the specified element type.
946  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
947                                ArrayType::ArraySizeModifier ASM,
948                                unsigned IndexTypeQuals,
949                                SourceRange Brackets) const;
950
951  /// \brief Return a non-unique reference to the type for a dependently-sized
952  /// array of the specified element type.
953  ///
954  /// FIXME: We will need these to be uniqued, or at least comparable, at some
955  /// point.
956  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
957                                      ArrayType::ArraySizeModifier ASM,
958                                      unsigned IndexTypeQuals,
959                                      SourceRange Brackets) const;
960
961  /// \brief Return a unique reference to the type for an incomplete array of
962  /// the specified element type.
963  QualType getIncompleteArrayType(QualType EltTy,
964                                  ArrayType::ArraySizeModifier ASM,
965                                  unsigned IndexTypeQuals) const;
966
967  /// \brief Return the unique reference to the type for a constant array of
968  /// the specified element type.
969  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
970                                ArrayType::ArraySizeModifier ASM,
971                                unsigned IndexTypeQuals) const;
972
973  /// \brief Returns a vla type where known sizes are replaced with [*].
974  QualType getVariableArrayDecayedType(QualType Ty) const;
975
976  /// \brief Return the unique reference to a vector type of the specified
977  /// element type and size.
978  ///
979  /// \pre \p VectorType must be a built-in type.
980  QualType getVectorType(QualType VectorType, unsigned NumElts,
981                         VectorType::VectorKind VecKind) const;
982
983  /// \brief Return the unique reference to an extended vector type
984  /// of the specified element type and size.
985  ///
986  /// \pre \p VectorType must be a built-in type.
987  QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
988
989  /// \pre Return a non-unique reference to the type for a dependently-sized
990  /// vector of the specified element type.
991  ///
992  /// FIXME: We will need these to be uniqued, or at least comparable, at some
993  /// point.
994  QualType getDependentSizedExtVectorType(QualType VectorType,
995                                          Expr *SizeExpr,
996                                          SourceLocation AttrLoc) const;
997
998  /// \brief Return a K&R style C function type like 'int()'.
999  QualType getFunctionNoProtoType(QualType ResultTy,
1000                                  const FunctionType::ExtInfo &Info) const;
1001
1002  QualType getFunctionNoProtoType(QualType ResultTy) const {
1003    return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1004  }
1005
1006  /// \brief Return a normal function type with a typed argument list.
1007  QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1008                           const FunctionProtoType::ExtProtoInfo &EPI) const;
1009
1010  /// \brief Return the unique reference to the type for the specified type
1011  /// declaration.
1012  QualType getTypeDeclType(const TypeDecl *Decl,
1013                           const TypeDecl *PrevDecl = 0) const {
1014    assert(Decl && "Passed null for Decl param");
1015    if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1016
1017    if (PrevDecl) {
1018      assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1019      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1020      return QualType(PrevDecl->TypeForDecl, 0);
1021    }
1022
1023    return getTypeDeclTypeSlow(Decl);
1024  }
1025
1026  /// \brief Return the unique reference to the type for the specified
1027  /// typedef-name decl.
1028  QualType getTypedefType(const TypedefNameDecl *Decl,
1029                          QualType Canon = QualType()) const;
1030
1031  QualType getRecordType(const RecordDecl *Decl) const;
1032
1033  QualType getEnumType(const EnumDecl *Decl) const;
1034
1035  QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1036
1037  QualType getAttributedType(AttributedType::Kind attrKind,
1038                             QualType modifiedType,
1039                             QualType equivalentType);
1040
1041  QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1042                                        QualType Replacement) const;
1043  QualType getSubstTemplateTypeParmPackType(
1044                                          const TemplateTypeParmType *Replaced,
1045                                            const TemplateArgument &ArgPack);
1046
1047  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
1048                                   bool ParameterPack,
1049                                   TemplateTypeParmDecl *ParmDecl = 0) const;
1050
1051  QualType getTemplateSpecializationType(TemplateName T,
1052                                         const TemplateArgument *Args,
1053                                         unsigned NumArgs,
1054                                         QualType Canon = QualType()) const;
1055
1056  QualType getCanonicalTemplateSpecializationType(TemplateName T,
1057                                                  const TemplateArgument *Args,
1058                                                  unsigned NumArgs) const;
1059
1060  QualType getTemplateSpecializationType(TemplateName T,
1061                                         const TemplateArgumentListInfo &Args,
1062                                         QualType Canon = QualType()) const;
1063
1064  TypeSourceInfo *
1065  getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1066                                    const TemplateArgumentListInfo &Args,
1067                                    QualType Canon = QualType()) const;
1068
1069  QualType getParenType(QualType NamedType) const;
1070
1071  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1072                             NestedNameSpecifier *NNS,
1073                             QualType NamedType) const;
1074  QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1075                                NestedNameSpecifier *NNS,
1076                                const IdentifierInfo *Name,
1077                                QualType Canon = QualType()) const;
1078
1079  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1080                                                  NestedNameSpecifier *NNS,
1081                                                  const IdentifierInfo *Name,
1082                                    const TemplateArgumentListInfo &Args) const;
1083  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1084                                                  NestedNameSpecifier *NNS,
1085                                                  const IdentifierInfo *Name,
1086                                                  unsigned NumArgs,
1087                                            const TemplateArgument *Args) const;
1088
1089  QualType getPackExpansionType(QualType Pattern,
1090                                Optional<unsigned> NumExpansions);
1091
1092  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1093                                ObjCInterfaceDecl *PrevDecl = 0) const;
1094
1095  QualType getObjCObjectType(QualType Base,
1096                             ObjCProtocolDecl * const *Protocols,
1097                             unsigned NumProtocols) const;
1098
1099  /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1100  QualType getObjCObjectPointerType(QualType OIT) const;
1101
1102  /// \brief GCC extension.
1103  QualType getTypeOfExprType(Expr *e) const;
1104  QualType getTypeOfType(QualType t) const;
1105
1106  /// \brief C++11 decltype.
1107  QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1108
1109  /// \brief Unary type transforms
1110  QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1111                                 UnaryTransformType::UTTKind UKind) const;
1112
1113  /// \brief C++11 deduced auto type.
1114  QualType getAutoType(QualType DeducedType, bool IsDecltypeAuto,
1115                       bool IsDependent = false) const;
1116
1117  /// \brief C++11 deduction pattern for 'auto' type.
1118  QualType getAutoDeductType() const;
1119
1120  /// \brief C++11 deduction pattern for 'auto &&' type.
1121  QualType getAutoRRefDeductType() const;
1122
1123  /// \brief Return the unique reference to the type for the specified TagDecl
1124  /// (struct/union/class/enum) decl.
1125  QualType getTagDeclType(const TagDecl *Decl) const;
1126
1127  /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1128  /// <stddef.h>.
1129  ///
1130  /// The sizeof operator requires this (C99 6.5.3.4p4).
1131  CanQualType getSizeType() const;
1132
1133  /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1134  /// <stdint.h>.
1135  CanQualType getIntMaxType() const;
1136
1137  /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1138  /// <stdint.h>.
1139  CanQualType getUIntMaxType() const;
1140
1141  /// \brief Return the unique wchar_t type available in C++ (and available as
1142  /// __wchar_t as a Microsoft extension).
1143  QualType getWCharType() const { return WCharTy; }
1144
1145  /// \brief Return the type of wide characters. In C++, this returns the
1146  /// unique wchar_t type. In C99, this returns a type compatible with the type
1147  /// defined in <stddef.h> as defined by the target.
1148  QualType getWideCharType() const { return WideCharTy; }
1149
1150  /// \brief Return the type of "signed wchar_t".
1151  ///
1152  /// Used when in C++, as a GCC extension.
1153  QualType getSignedWCharType() const;
1154
1155  /// \brief Return the type of "unsigned wchar_t".
1156  ///
1157  /// Used when in C++, as a GCC extension.
1158  QualType getUnsignedWCharType() const;
1159
1160  /// \brief In C99, this returns a type compatible with the type
1161  /// defined in <stddef.h> as defined by the target.
1162  QualType getWIntType() const { return WIntTy; }
1163
1164  /// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4),
1165  /// as defined by the target.
1166  QualType getIntPtrType() const;
1167
1168  /// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1169  /// as defined by the target.
1170  QualType getUIntPtrType() const;
1171
1172  /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1173  /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1174  QualType getPointerDiffType() const;
1175
1176  /// \brief Return the unique type for "pid_t" defined in
1177  /// <sys/types.h>. We need this to compute the correct type for vfork().
1178  QualType getProcessIDType() const;
1179
1180  /// \brief Return the C structure type used to represent constant CFStrings.
1181  QualType getCFConstantStringType() const;
1182
1183  /// \brief Returns the C struct type for objc_super
1184  QualType getObjCSuperType() const;
1185  void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1186
1187  /// Get the structure type used to representation CFStrings, or NULL
1188  /// if it hasn't yet been built.
1189  QualType getRawCFConstantStringType() const {
1190    if (CFConstantStringTypeDecl)
1191      return getTagDeclType(CFConstantStringTypeDecl);
1192    return QualType();
1193  }
1194  void setCFConstantStringType(QualType T);
1195
1196  // This setter/getter represents the ObjC type for an NSConstantString.
1197  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1198  QualType getObjCConstantStringInterface() const {
1199    return ObjCConstantStringType;
1200  }
1201
1202  QualType getObjCNSStringType() const {
1203    return ObjCNSStringType;
1204  }
1205
1206  void setObjCNSStringType(QualType T) {
1207    ObjCNSStringType = T;
1208  }
1209
1210  /// \brief Retrieve the type that \c id has been defined to, which may be
1211  /// different from the built-in \c id if \c id has been typedef'd.
1212  QualType getObjCIdRedefinitionType() const {
1213    if (ObjCIdRedefinitionType.isNull())
1214      return getObjCIdType();
1215    return ObjCIdRedefinitionType;
1216  }
1217
1218  /// \brief Set the user-written type that redefines \c id.
1219  void setObjCIdRedefinitionType(QualType RedefType) {
1220    ObjCIdRedefinitionType = RedefType;
1221  }
1222
1223  /// \brief Retrieve the type that \c Class has been defined to, which may be
1224  /// different from the built-in \c Class if \c Class has been typedef'd.
1225  QualType getObjCClassRedefinitionType() const {
1226    if (ObjCClassRedefinitionType.isNull())
1227      return getObjCClassType();
1228    return ObjCClassRedefinitionType;
1229  }
1230
1231  /// \brief Set the user-written type that redefines 'SEL'.
1232  void setObjCClassRedefinitionType(QualType RedefType) {
1233    ObjCClassRedefinitionType = RedefType;
1234  }
1235
1236  /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1237  /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1238  QualType getObjCSelRedefinitionType() const {
1239    if (ObjCSelRedefinitionType.isNull())
1240      return getObjCSelType();
1241    return ObjCSelRedefinitionType;
1242  }
1243
1244
1245  /// \brief Set the user-written type that redefines 'SEL'.
1246  void setObjCSelRedefinitionType(QualType RedefType) {
1247    ObjCSelRedefinitionType = RedefType;
1248  }
1249
1250  /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1251  /// otherwise, returns a NULL type;
1252  QualType getObjCInstanceType() {
1253    return getTypeDeclType(getObjCInstanceTypeDecl());
1254  }
1255
1256  /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1257  /// "instancetype" type.
1258  TypedefDecl *getObjCInstanceTypeDecl();
1259
1260  /// \brief Set the type for the C FILE type.
1261  void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1262
1263  /// \brief Retrieve the C FILE type.
1264  QualType getFILEType() const {
1265    if (FILEDecl)
1266      return getTypeDeclType(FILEDecl);
1267    return QualType();
1268  }
1269
1270  /// \brief Set the type for the C jmp_buf type.
1271  void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1272    this->jmp_bufDecl = jmp_bufDecl;
1273  }
1274
1275  /// \brief Retrieve the C jmp_buf type.
1276  QualType getjmp_bufType() const {
1277    if (jmp_bufDecl)
1278      return getTypeDeclType(jmp_bufDecl);
1279    return QualType();
1280  }
1281
1282  /// \brief Set the type for the C sigjmp_buf type.
1283  void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1284    this->sigjmp_bufDecl = sigjmp_bufDecl;
1285  }
1286
1287  /// \brief Retrieve the C sigjmp_buf type.
1288  QualType getsigjmp_bufType() const {
1289    if (sigjmp_bufDecl)
1290      return getTypeDeclType(sigjmp_bufDecl);
1291    return QualType();
1292  }
1293
1294  /// \brief Set the type for the C ucontext_t type.
1295  void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1296    this->ucontext_tDecl = ucontext_tDecl;
1297  }
1298
1299  /// \brief Retrieve the C ucontext_t type.
1300  QualType getucontext_tType() const {
1301    if (ucontext_tDecl)
1302      return getTypeDeclType(ucontext_tDecl);
1303    return QualType();
1304  }
1305
1306  /// \brief The result type of logical operations, '<', '>', '!=', etc.
1307  QualType getLogicalOperationType() const {
1308    return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1309  }
1310
1311  /// \brief Emit the Objective-CC type encoding for the given type \p T into
1312  /// \p S.
1313  ///
1314  /// If \p Field is specified then record field names are also encoded.
1315  void getObjCEncodingForType(QualType T, std::string &S,
1316                              const FieldDecl *Field=0) const;
1317
1318  void getLegacyIntegralTypeEncoding(QualType &t) const;
1319
1320  /// \brief Put the string version of the type qualifiers \p QT into \p S.
1321  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1322                                       std::string &S) const;
1323
1324  /// \brief Emit the encoded type for the function \p Decl into \p S.
1325  ///
1326  /// This is in the same format as Objective-C method encodings.
1327  ///
1328  /// \returns true if an error occurred (e.g., because one of the parameter
1329  /// types is incomplete), false otherwise.
1330  bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1331
1332  /// \brief Emit the encoded type for the method declaration \p Decl into
1333  /// \p S.
1334  ///
1335  /// \returns true if an error occurred (e.g., because one of the parameter
1336  /// types is incomplete), false otherwise.
1337  bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1338                                    bool Extended = false)
1339    const;
1340
1341  /// \brief Return the encoded type for this block declaration.
1342  std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1343
1344  /// getObjCEncodingForPropertyDecl - Return the encoded type for
1345  /// this method declaration. If non-NULL, Container must be either
1346  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1347  /// only be NULL when getting encodings for protocol properties.
1348  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1349                                      const Decl *Container,
1350                                      std::string &S) const;
1351
1352  bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1353                                      ObjCProtocolDecl *rProto) const;
1354
1355  /// \brief Return the size of type \p T for Objective-C encoding purpose,
1356  /// in characters.
1357  CharUnits getObjCEncodingTypeSize(QualType T) const;
1358
1359  /// \brief Retrieve the typedef corresponding to the predefined \c id type
1360  /// in Objective-C.
1361  TypedefDecl *getObjCIdDecl() const;
1362
1363  /// \brief Represents the Objective-CC \c id type.
1364  ///
1365  /// This is set up lazily, by Sema.  \c id is always a (typedef for a)
1366  /// pointer type, a pointer to a struct.
1367  QualType getObjCIdType() const {
1368    return getTypeDeclType(getObjCIdDecl());
1369  }
1370
1371  /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1372  /// in Objective-C.
1373  TypedefDecl *getObjCSelDecl() const;
1374
1375  /// \brief Retrieve the type that corresponds to the predefined Objective-C
1376  /// 'SEL' type.
1377  QualType getObjCSelType() const {
1378    return getTypeDeclType(getObjCSelDecl());
1379  }
1380
1381  /// \brief Retrieve the typedef declaration corresponding to the predefined
1382  /// Objective-C 'Class' type.
1383  TypedefDecl *getObjCClassDecl() const;
1384
1385  /// \brief Represents the Objective-C \c Class type.
1386  ///
1387  /// This is set up lazily, by Sema.  \c Class is always a (typedef for a)
1388  /// pointer type, a pointer to a struct.
1389  QualType getObjCClassType() const {
1390    return getTypeDeclType(getObjCClassDecl());
1391  }
1392
1393  /// \brief Retrieve the Objective-C class declaration corresponding to
1394  /// the predefined \c Protocol class.
1395  ObjCInterfaceDecl *getObjCProtocolDecl() const;
1396
1397  /// \brief Retrieve declaration of 'BOOL' typedef
1398  TypedefDecl *getBOOLDecl() const {
1399    return BOOLDecl;
1400  }
1401
1402  /// \brief Save declaration of 'BOOL' typedef
1403  void setBOOLDecl(TypedefDecl *TD) {
1404    BOOLDecl = TD;
1405  }
1406
1407  /// \brief type of 'BOOL' type.
1408  QualType getBOOLType() const {
1409    return getTypeDeclType(getBOOLDecl());
1410  }
1411
1412  /// \brief Retrieve the type of the Objective-C \c Protocol class.
1413  QualType getObjCProtoType() const {
1414    return getObjCInterfaceType(getObjCProtocolDecl());
1415  }
1416
1417  /// \brief Retrieve the C type declaration corresponding to the predefined
1418  /// \c __builtin_va_list type.
1419  TypedefDecl *getBuiltinVaListDecl() const;
1420
1421  /// \brief Retrieve the type of the \c __builtin_va_list type.
1422  QualType getBuiltinVaListType() const {
1423    return getTypeDeclType(getBuiltinVaListDecl());
1424  }
1425
1426  /// \brief Retrieve the C type declaration corresponding to the predefined
1427  /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1428  /// for some targets.
1429  QualType getVaListTagType() const;
1430
1431  /// \brief Return a type with additional \c const, \c volatile, or
1432  /// \c restrict qualifiers.
1433  QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1434    return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1435  }
1436
1437  /// \brief Un-split a SplitQualType.
1438  QualType getQualifiedType(SplitQualType split) const {
1439    return getQualifiedType(split.Ty, split.Quals);
1440  }
1441
1442  /// \brief Return a type with additional qualifiers.
1443  QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1444    if (!Qs.hasNonFastQualifiers())
1445      return T.withFastQualifiers(Qs.getFastQualifiers());
1446    QualifierCollector Qc(Qs);
1447    const Type *Ptr = Qc.strip(T);
1448    return getExtQualType(Ptr, Qc);
1449  }
1450
1451  /// \brief Return a type with additional qualifiers.
1452  QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1453    if (!Qs.hasNonFastQualifiers())
1454      return QualType(T, Qs.getFastQualifiers());
1455    return getExtQualType(T, Qs);
1456  }
1457
1458  /// \brief Return a type with the given lifetime qualifier.
1459  ///
1460  /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1461  QualType getLifetimeQualifiedType(QualType type,
1462                                    Qualifiers::ObjCLifetime lifetime) {
1463    assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1464    assert(lifetime != Qualifiers::OCL_None);
1465
1466    Qualifiers qs;
1467    qs.addObjCLifetime(lifetime);
1468    return getQualifiedType(type, qs);
1469  }
1470
1471  /// getUnqualifiedObjCPointerType - Returns version of
1472  /// Objective-C pointer type with lifetime qualifier removed.
1473  QualType getUnqualifiedObjCPointerType(QualType type) const {
1474    if (!type.getTypePtr()->isObjCObjectPointerType() ||
1475        !type.getQualifiers().hasObjCLifetime())
1476      return type;
1477    Qualifiers Qs = type.getQualifiers();
1478    Qs.removeObjCLifetime();
1479    return getQualifiedType(type.getUnqualifiedType(), Qs);
1480  }
1481
1482  DeclarationNameInfo getNameForTemplate(TemplateName Name,
1483                                         SourceLocation NameLoc) const;
1484
1485  TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1486                                         UnresolvedSetIterator End) const;
1487
1488  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1489                                        bool TemplateKeyword,
1490                                        TemplateDecl *Template) const;
1491
1492  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1493                                        const IdentifierInfo *Name) const;
1494  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1495                                        OverloadedOperatorKind Operator) const;
1496  TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1497                                            TemplateName replacement) const;
1498  TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1499                                        const TemplateArgument &ArgPack) const;
1500
1501  enum GetBuiltinTypeError {
1502    GE_None,              ///< No error
1503    GE_Missing_stdio,     ///< Missing a type from <stdio.h>
1504    GE_Missing_setjmp,    ///< Missing a type from <setjmp.h>
1505    GE_Missing_ucontext   ///< Missing a type from <ucontext.h>
1506  };
1507
1508  /// \brief Return the type for the specified builtin.
1509  ///
1510  /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1511  /// arguments to the builtin that are required to be integer constant
1512  /// expressions.
1513  QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1514                          unsigned *IntegerConstantArgs = 0) const;
1515
1516private:
1517  CanQualType getFromTargetType(unsigned Type) const;
1518  std::pair<uint64_t, unsigned> getTypeInfoImpl(const Type *T) const;
1519
1520  //===--------------------------------------------------------------------===//
1521  //                         Type Predicates.
1522  //===--------------------------------------------------------------------===//
1523
1524public:
1525  /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1526  /// collection attributes.
1527  Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1528
1529  /// \brief Return true if the given vector types are of the same unqualified
1530  /// type or if they are equivalent to the same GCC vector type.
1531  ///
1532  /// \note This ignores whether they are target-specific (AltiVec or Neon)
1533  /// types.
1534  bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1535
1536  /// \brief Return true if this is an \c NSObject object with its \c NSObject
1537  /// attribute set.
1538  static bool isObjCNSObjectType(QualType Ty) {
1539    return Ty->isObjCNSObjectType();
1540  }
1541
1542  //===--------------------------------------------------------------------===//
1543  //                         Type Sizing and Analysis
1544  //===--------------------------------------------------------------------===//
1545
1546  /// \brief Return the APFloat 'semantics' for the specified scalar floating
1547  /// point type.
1548  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1549
1550  /// \brief Get the size and alignment of the specified complete type in bits.
1551  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T) const;
1552  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) const {
1553    return getTypeInfo(T.getTypePtr());
1554  }
1555
1556  /// \brief Return the size of the specified (complete) type \p T, in bits.
1557  uint64_t getTypeSize(QualType T) const {
1558    return getTypeInfo(T).first;
1559  }
1560  uint64_t getTypeSize(const Type *T) const {
1561    return getTypeInfo(T).first;
1562  }
1563
1564  /// \brief Return the size of the character type, in bits.
1565  uint64_t getCharWidth() const {
1566    return getTypeSize(CharTy);
1567  }
1568
1569  /// \brief Convert a size in bits to a size in characters.
1570  CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1571
1572  /// \brief Convert a size in characters to a size in bits.
1573  int64_t toBits(CharUnits CharSize) const;
1574
1575  /// \brief Return the size of the specified (complete) type \p T, in
1576  /// characters.
1577  CharUnits getTypeSizeInChars(QualType T) const;
1578  CharUnits getTypeSizeInChars(const Type *T) const;
1579
1580  /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1581  /// bits.
1582  unsigned getTypeAlign(QualType T) const {
1583    return getTypeInfo(T).second;
1584  }
1585  unsigned getTypeAlign(const Type *T) const {
1586    return getTypeInfo(T).second;
1587  }
1588
1589  /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1590  /// characters.
1591  CharUnits getTypeAlignInChars(QualType T) const;
1592  CharUnits getTypeAlignInChars(const Type *T) const;
1593
1594  // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1595  // type is a record, its data size is returned.
1596  std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1597
1598  std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1599  std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1600
1601  /// \brief Return the "preferred" alignment of the specified type \p T for
1602  /// the current target, in bits.
1603  ///
1604  /// This can be different than the ABI alignment in cases where it is
1605  /// beneficial for performance to overalign a data type.
1606  unsigned getPreferredTypeAlign(const Type *T) const;
1607
1608  /// \brief Return the alignment in bits that should be given to a
1609  /// global variable with type \p T.
1610  unsigned getAlignOfGlobalVar(QualType T) const;
1611
1612  /// \brief Return the alignment in characters that should be given to a
1613  /// global variable with type \p T.
1614  CharUnits getAlignOfGlobalVarInChars(QualType T) const;
1615
1616  /// \brief Return a conservative estimate of the alignment of the specified
1617  /// decl \p D.
1618  ///
1619  /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
1620  /// alignment.
1621  ///
1622  /// If \p RefAsPointee, references are treated like their underlying type
1623  /// (for alignof), else they're treated like pointers (for CodeGen).
1624  CharUnits getDeclAlign(const Decl *D, bool RefAsPointee = false) const;
1625
1626  /// \brief Get or compute information about the layout of the specified
1627  /// record (struct/union/class) \p D, which indicates its size and field
1628  /// position information.
1629  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1630
1631  /// \brief Get or compute information about the layout of the specified
1632  /// Objective-C interface.
1633  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1634    const;
1635
1636  void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
1637                        bool Simple = false) const;
1638
1639  /// \brief Get or compute information about the layout of the specified
1640  /// Objective-C implementation.
1641  ///
1642  /// This may differ from the interface if synthesized ivars are present.
1643  const ASTRecordLayout &
1644  getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1645
1646  /// \brief Get our current best idea for the key function of the
1647  /// given record decl, or NULL if there isn't one.
1648  ///
1649  /// The key function is, according to the Itanium C++ ABI section 5.2.3:
1650  ///   ...the first non-pure virtual function that is not inline at the
1651  ///   point of class definition.
1652  ///
1653  /// Other ABIs use the same idea.  However, the ARM C++ ABI ignores
1654  /// virtual functions that are defined 'inline', which means that
1655  /// the result of this computation can change.
1656  const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
1657
1658  /// \brief Observe that the given method cannot be a key function.
1659  /// Checks the key-function cache for the method's class and clears it
1660  /// if matches the given declaration.
1661  ///
1662  /// This is used in ABIs where out-of-line definitions marked
1663  /// inline are not considered to be key functions.
1664  ///
1665  /// \param method should be the declaration from the class definition
1666  void setNonKeyFunction(const CXXMethodDecl *method);
1667
1668  /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1669  uint64_t getFieldOffset(const ValueDecl *FD) const;
1670
1671  bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1672
1673  MangleContext *createMangleContext();
1674
1675  void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1676                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1677
1678  unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1679  void CollectInheritedProtocols(const Decl *CDecl,
1680                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1681
1682  //===--------------------------------------------------------------------===//
1683  //                            Type Operators
1684  //===--------------------------------------------------------------------===//
1685
1686  /// \brief Return the canonical (structural) type corresponding to the
1687  /// specified potentially non-canonical type \p T.
1688  ///
1689  /// The non-canonical version of a type may have many "decorated" versions of
1690  /// types.  Decorators can include typedefs, 'typeof' operators, etc. The
1691  /// returned type is guaranteed to be free of any of these, allowing two
1692  /// canonical types to be compared for exact equality with a simple pointer
1693  /// comparison.
1694  CanQualType getCanonicalType(QualType T) const {
1695    return CanQualType::CreateUnsafe(T.getCanonicalType());
1696  }
1697
1698  const Type *getCanonicalType(const Type *T) const {
1699    return T->getCanonicalTypeInternal().getTypePtr();
1700  }
1701
1702  /// \brief Return the canonical parameter type corresponding to the specific
1703  /// potentially non-canonical one.
1704  ///
1705  /// Qualifiers are stripped off, functions are turned into function
1706  /// pointers, and arrays decay one level into pointers.
1707  CanQualType getCanonicalParamType(QualType T) const;
1708
1709  /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
1710  bool hasSameType(QualType T1, QualType T2) const {
1711    return getCanonicalType(T1) == getCanonicalType(T2);
1712  }
1713
1714  /// \brief Return this type as a completely-unqualified array type,
1715  /// capturing the qualifiers in \p Quals.
1716  ///
1717  /// This will remove the minimal amount of sugaring from the types, similar
1718  /// to the behavior of QualType::getUnqualifiedType().
1719  ///
1720  /// \param T is the qualified type, which may be an ArrayType
1721  ///
1722  /// \param Quals will receive the full set of qualifiers that were
1723  /// applied to the array.
1724  ///
1725  /// \returns if this is an array type, the completely unqualified array type
1726  /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1727  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1728
1729  /// \brief Determine whether the given types are equivalent after
1730  /// cvr-qualifiers have been removed.
1731  bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
1732    return getCanonicalType(T1).getTypePtr() ==
1733           getCanonicalType(T2).getTypePtr();
1734  }
1735
1736  bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1737
1738  /// \brief Retrieves the "canonical" nested name specifier for a
1739  /// given nested name specifier.
1740  ///
1741  /// The canonical nested name specifier is a nested name specifier
1742  /// that uniquely identifies a type or namespace within the type
1743  /// system. For example, given:
1744  ///
1745  /// \code
1746  /// namespace N {
1747  ///   struct S {
1748  ///     template<typename T> struct X { typename T* type; };
1749  ///   };
1750  /// }
1751  ///
1752  /// template<typename T> struct Y {
1753  ///   typename N::S::X<T>::type member;
1754  /// };
1755  /// \endcode
1756  ///
1757  /// Here, the nested-name-specifier for N::S::X<T>:: will be
1758  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1759  /// by declarations in the type system and the canonical type for
1760  /// the template type parameter 'T' is template-param-0-0.
1761  NestedNameSpecifier *
1762  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
1763
1764  /// \brief Retrieves the default calling convention to use for
1765  /// C++ instance methods.
1766  CallingConv getDefaultCXXMethodCallConv(bool isVariadic);
1767
1768  /// \brief Retrieves the canonical representation of the given
1769  /// calling convention.
1770  CallingConv getCanonicalCallConv(CallingConv CC) const;
1771
1772  /// \brief Determines whether two calling conventions name the same
1773  /// calling convention.
1774  bool isSameCallConv(CallingConv lcc, CallingConv rcc) {
1775    return (getCanonicalCallConv(lcc) == getCanonicalCallConv(rcc));
1776  }
1777
1778  /// \brief Retrieves the "canonical" template name that refers to a
1779  /// given template.
1780  ///
1781  /// The canonical template name is the simplest expression that can
1782  /// be used to refer to a given template. For most templates, this
1783  /// expression is just the template declaration itself. For example,
1784  /// the template std::vector can be referred to via a variety of
1785  /// names---std::vector, \::std::vector, vector (if vector is in
1786  /// scope), etc.---but all of these names map down to the same
1787  /// TemplateDecl, which is used to form the canonical template name.
1788  ///
1789  /// Dependent template names are more interesting. Here, the
1790  /// template name could be something like T::template apply or
1791  /// std::allocator<T>::template rebind, where the nested name
1792  /// specifier itself is dependent. In this case, the canonical
1793  /// template name uses the shortest form of the dependent
1794  /// nested-name-specifier, which itself contains all canonical
1795  /// types, values, and templates.
1796  TemplateName getCanonicalTemplateName(TemplateName Name) const;
1797
1798  /// \brief Determine whether the given template names refer to the same
1799  /// template.
1800  bool hasSameTemplateName(TemplateName X, TemplateName Y);
1801
1802  /// \brief Retrieve the "canonical" template argument.
1803  ///
1804  /// The canonical template argument is the simplest template argument
1805  /// (which may be a type, value, expression, or declaration) that
1806  /// expresses the value of the argument.
1807  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
1808    const;
1809
1810  /// Type Query functions.  If the type is an instance of the specified class,
1811  /// return the Type pointer for the underlying maximally pretty type.  This
1812  /// is a member of ASTContext because this may need to do some amount of
1813  /// canonicalization, e.g. to move type qualifiers into the element type.
1814  const ArrayType *getAsArrayType(QualType T) const;
1815  const ConstantArrayType *getAsConstantArrayType(QualType T) const {
1816    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1817  }
1818  const VariableArrayType *getAsVariableArrayType(QualType T) const {
1819    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1820  }
1821  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
1822    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1823  }
1824  const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
1825    const {
1826    return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1827  }
1828
1829  /// \brief Return the innermost element type of an array type.
1830  ///
1831  /// For example, will return "int" for int[m][n]
1832  QualType getBaseElementType(const ArrayType *VAT) const;
1833
1834  /// \brief Return the innermost element type of a type (which needn't
1835  /// actually be an array type).
1836  QualType getBaseElementType(QualType QT) const;
1837
1838  /// \brief Return number of constant array elements.
1839  uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1840
1841  /// \brief Perform adjustment on the parameter type of a function.
1842  ///
1843  /// This routine adjusts the given parameter type @p T to the actual
1844  /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
1845  /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
1846  QualType getAdjustedParameterType(QualType T) const;
1847
1848  /// \brief Retrieve the parameter type as adjusted for use in the signature
1849  /// of a function, decaying array and function types and removing top-level
1850  /// cv-qualifiers.
1851  QualType getSignatureParameterType(QualType T) const;
1852
1853  /// \brief Return the properly qualified result of decaying the specified
1854  /// array type to a pointer.
1855  ///
1856  /// This operation is non-trivial when handling typedefs etc.  The canonical
1857  /// type of \p T must be an array type, this returns a pointer to a properly
1858  /// qualified element of the array.
1859  ///
1860  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1861  QualType getArrayDecayedType(QualType T) const;
1862
1863  /// \brief Return the type that \p PromotableType will promote to: C99
1864  /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
1865  QualType getPromotedIntegerType(QualType PromotableType) const;
1866
1867  /// \brief Recurses in pointer/array types until it finds an Objective-C
1868  /// retainable type and returns its ownership.
1869  Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
1870
1871  /// \brief Whether this is a promotable bitfield reference according
1872  /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1873  ///
1874  /// \returns the type this bit-field will promote to, or NULL if no
1875  /// promotion occurs.
1876  QualType isPromotableBitField(Expr *E) const;
1877
1878  /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
1879  ///
1880  /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
1881  /// \p LHS < \p RHS, return -1.
1882  int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
1883
1884  /// \brief Compare the rank of the two specified floating point types,
1885  /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
1886  ///
1887  /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
1888  /// \p LHS < \p RHS, return -1.
1889  int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
1890
1891  /// \brief Return a real floating point or a complex type (based on
1892  /// \p typeDomain/\p typeSize).
1893  ///
1894  /// \param typeDomain a real floating point or complex type.
1895  /// \param typeSize a real floating point or complex type.
1896  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1897                                             QualType typeDomain) const;
1898
1899  unsigned getTargetAddressSpace(QualType T) const {
1900    return getTargetAddressSpace(T.getQualifiers());
1901  }
1902
1903  unsigned getTargetAddressSpace(Qualifiers Q) const {
1904    return getTargetAddressSpace(Q.getAddressSpace());
1905  }
1906
1907  unsigned getTargetAddressSpace(unsigned AS) const {
1908    if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
1909      return AS;
1910    else
1911      return (*AddrSpaceMap)[AS - LangAS::Offset];
1912  }
1913
1914private:
1915  // Helper for integer ordering
1916  unsigned getIntegerRank(const Type *T) const;
1917
1918public:
1919
1920  //===--------------------------------------------------------------------===//
1921  //                    Type Compatibility Predicates
1922  //===--------------------------------------------------------------------===//
1923
1924  /// Compatibility predicates used to check assignment expressions.
1925  bool typesAreCompatible(QualType T1, QualType T2,
1926                          bool CompareUnqualified = false); // C99 6.2.7p1
1927
1928  bool propertyTypesAreCompatible(QualType, QualType);
1929  bool typesAreBlockPointerCompatible(QualType, QualType);
1930
1931  bool isObjCIdType(QualType T) const {
1932    return T == getObjCIdType();
1933  }
1934  bool isObjCClassType(QualType T) const {
1935    return T == getObjCClassType();
1936  }
1937  bool isObjCSelType(QualType T) const {
1938    return T == getObjCSelType();
1939  }
1940  bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
1941  bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
1942                                         bool ForCompare);
1943
1944  bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
1945
1946  // Check the safety of assignment from LHS to RHS
1947  bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
1948                               const ObjCObjectPointerType *RHSOPT);
1949  bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
1950                               const ObjCObjectType *RHS);
1951  bool canAssignObjCInterfacesInBlockPointer(
1952                                          const ObjCObjectPointerType *LHSOPT,
1953                                          const ObjCObjectPointerType *RHSOPT,
1954                                          bool BlockReturnType);
1955  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
1956  QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
1957                                   const ObjCObjectPointerType *RHSOPT);
1958  bool canBindObjCObjectType(QualType To, QualType From);
1959
1960  // Functions for calculating composite types
1961  QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
1962                      bool Unqualified = false, bool BlockReturnType = false);
1963  QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
1964                              bool Unqualified = false);
1965  QualType mergeFunctionArgumentTypes(QualType, QualType,
1966                                      bool OfBlockPointer=false,
1967                                      bool Unqualified = false);
1968  QualType mergeTransparentUnionType(QualType, QualType,
1969                                     bool OfBlockPointer=false,
1970                                     bool Unqualified = false);
1971
1972  QualType mergeObjCGCQualifiers(QualType, QualType);
1973
1974  bool FunctionTypesMatchOnNSConsumedAttrs(
1975         const FunctionProtoType *FromFunctionType,
1976         const FunctionProtoType *ToFunctionType);
1977
1978  void ResetObjCLayout(const ObjCContainerDecl *CD) {
1979    ObjCLayouts[CD] = 0;
1980  }
1981
1982  //===--------------------------------------------------------------------===//
1983  //                    Integer Predicates
1984  //===--------------------------------------------------------------------===//
1985
1986  // The width of an integer, as defined in C99 6.2.6.2. This is the number
1987  // of bits in an integer type excluding any padding bits.
1988  unsigned getIntWidth(QualType T) const;
1989
1990  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
1991  // unsigned integer type.  This method takes a signed type, and returns the
1992  // corresponding unsigned integer type.
1993  QualType getCorrespondingUnsignedType(QualType T) const;
1994
1995  //===--------------------------------------------------------------------===//
1996  //                    Type Iterators.
1997  //===--------------------------------------------------------------------===//
1998
1999  typedef SmallVectorImpl<Type *>::iterator       type_iterator;
2000  typedef SmallVectorImpl<Type *>::const_iterator const_type_iterator;
2001
2002  type_iterator types_begin() { return Types.begin(); }
2003  type_iterator types_end() { return Types.end(); }
2004  const_type_iterator types_begin() const { return Types.begin(); }
2005  const_type_iterator types_end() const { return Types.end(); }
2006
2007  //===--------------------------------------------------------------------===//
2008  //                    Integer Values
2009  //===--------------------------------------------------------------------===//
2010
2011  /// \brief Make an APSInt of the appropriate width and signedness for the
2012  /// given \p Value and integer \p Type.
2013  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2014    llvm::APSInt Res(getIntWidth(Type),
2015                     !Type->isSignedIntegerOrEnumerationType());
2016    Res = Value;
2017    return Res;
2018  }
2019
2020  bool isSentinelNullExpr(const Expr *E);
2021
2022  /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
2023  /// none exists.
2024  ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2025  /// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
2026  /// none exists.
2027  ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
2028
2029  /// \brief Return true if there is at least one \@implementation in the TU.
2030  bool AnyObjCImplementation() {
2031    return !ObjCImpls.empty();
2032  }
2033
2034  /// \brief Set the implementation of ObjCInterfaceDecl.
2035  void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2036                             ObjCImplementationDecl *ImplD);
2037  /// \brief Set the implementation of ObjCCategoryDecl.
2038  void setObjCImplementation(ObjCCategoryDecl *CatD,
2039                             ObjCCategoryImplDecl *ImplD);
2040
2041  /// \brief Get the duplicate declaration of a ObjCMethod in the same
2042  /// interface, or null if none exists.
2043  const ObjCMethodDecl *getObjCMethodRedeclaration(
2044                                               const ObjCMethodDecl *MD) const {
2045    return ObjCMethodRedecls.lookup(MD);
2046  }
2047
2048  void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2049                                  const ObjCMethodDecl *Redecl) {
2050    assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2051    ObjCMethodRedecls[MD] = Redecl;
2052  }
2053
2054  /// \brief Returns the Objective-C interface that \p ND belongs to if it is
2055  /// an Objective-C method/property/ivar etc. that is part of an interface,
2056  /// otherwise returns null.
2057  const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2058
2059  /// \brief Set the copy inialization expression of a block var decl.
2060  void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2061  /// \brief Get the copy initialization expression of the VarDecl \p VD, or
2062  /// NULL if none exists.
2063  Expr *getBlockVarCopyInits(const VarDecl* VD);
2064
2065  /// \brief Allocate an uninitialized TypeSourceInfo.
2066  ///
2067  /// The caller should initialize the memory held by TypeSourceInfo using
2068  /// the TypeLoc wrappers.
2069  ///
2070  /// \param T the type that will be the basis for type source info. This type
2071  /// should refer to how the declarator was written in source code, not to
2072  /// what type semantic analysis resolved the declarator to.
2073  ///
2074  /// \param Size the size of the type info to create, or 0 if the size
2075  /// should be calculated based on the type.
2076  TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2077
2078  /// \brief Allocate a TypeSourceInfo where all locations have been
2079  /// initialized to a given location, which defaults to the empty
2080  /// location.
2081  TypeSourceInfo *
2082  getTrivialTypeSourceInfo(QualType T,
2083                           SourceLocation Loc = SourceLocation()) const;
2084
2085  TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
2086
2087  /// \brief Add a deallocation callback that will be invoked when the
2088  /// ASTContext is destroyed.
2089  ///
2090  /// \param Callback A callback function that will be invoked on destruction.
2091  ///
2092  /// \param Data Pointer data that will be provided to the callback function
2093  /// when it is called.
2094  void AddDeallocation(void (*Callback)(void*), void *Data);
2095
2096  GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD);
2097  GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2098
2099  /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
2100  /// lazily, only when used; this is only relevant for function or file scoped
2101  /// var definitions.
2102  ///
2103  /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2104  /// it is not used.
2105  bool DeclMustBeEmitted(const Decl *D);
2106
2107  void addUnnamedTag(const TagDecl *Tag);
2108  int getUnnamedTagManglingNumber(const TagDecl *Tag) const;
2109
2110  /// \brief Retrieve the lambda mangling number for a lambda expression.
2111  unsigned getLambdaManglingNumber(CXXMethodDecl *CallOperator);
2112
2113  /// \brief Used by ParmVarDecl to store on the side the
2114  /// index of the parameter when it exceeds the size of the normal bitfield.
2115  void setParameterIndex(const ParmVarDecl *D, unsigned index);
2116
2117  /// \brief Used by ParmVarDecl to retrieve on the side the
2118  /// index of the parameter when it exceeds the size of the normal bitfield.
2119  unsigned getParameterIndex(const ParmVarDecl *D) const;
2120
2121  //===--------------------------------------------------------------------===//
2122  //                    Statistics
2123  //===--------------------------------------------------------------------===//
2124
2125  /// \brief The number of implicitly-declared default constructors.
2126  static unsigned NumImplicitDefaultConstructors;
2127
2128  /// \brief The number of implicitly-declared default constructors for
2129  /// which declarations were built.
2130  static unsigned NumImplicitDefaultConstructorsDeclared;
2131
2132  /// \brief The number of implicitly-declared copy constructors.
2133  static unsigned NumImplicitCopyConstructors;
2134
2135  /// \brief The number of implicitly-declared copy constructors for
2136  /// which declarations were built.
2137  static unsigned NumImplicitCopyConstructorsDeclared;
2138
2139  /// \brief The number of implicitly-declared move constructors.
2140  static unsigned NumImplicitMoveConstructors;
2141
2142  /// \brief The number of implicitly-declared move constructors for
2143  /// which declarations were built.
2144  static unsigned NumImplicitMoveConstructorsDeclared;
2145
2146  /// \brief The number of implicitly-declared copy assignment operators.
2147  static unsigned NumImplicitCopyAssignmentOperators;
2148
2149  /// \brief The number of implicitly-declared copy assignment operators for
2150  /// which declarations were built.
2151  static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2152
2153  /// \brief The number of implicitly-declared move assignment operators.
2154  static unsigned NumImplicitMoveAssignmentOperators;
2155
2156  /// \brief The number of implicitly-declared move assignment operators for
2157  /// which declarations were built.
2158  static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2159
2160  /// \brief The number of implicitly-declared destructors.
2161  static unsigned NumImplicitDestructors;
2162
2163  /// \brief The number of implicitly-declared destructors for which
2164  /// declarations were built.
2165  static unsigned NumImplicitDestructorsDeclared;
2166
2167private:
2168  ASTContext(const ASTContext &) LLVM_DELETED_FUNCTION;
2169  void operator=(const ASTContext &) LLVM_DELETED_FUNCTION;
2170
2171public:
2172  /// \brief Initialize built-in types.
2173  ///
2174  /// This routine may only be invoked once for a given ASTContext object.
2175  /// It is normally invoked by the ASTContext constructor. However, the
2176  /// constructor can be asked to delay initialization, which places the burden
2177  /// of calling this function on the user of that object.
2178  ///
2179  /// \param Target The target
2180  void InitBuiltinTypes(const TargetInfo &Target);
2181
2182private:
2183  void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2184
2185  // Return the Objective-C type encoding for a given type.
2186  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2187                                  bool ExpandPointedToStructures,
2188                                  bool ExpandStructures,
2189                                  const FieldDecl *Field,
2190                                  bool OutermostType = false,
2191                                  bool EncodingProperty = false,
2192                                  bool StructField = false,
2193                                  bool EncodeBlockParameters = false,
2194                                  bool EncodeClassNames = false,
2195                                  bool EncodePointerToObjCTypedef = false) const;
2196
2197  // Adds the encoding of the structure's members.
2198  void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2199                                       const FieldDecl *Field,
2200                                       bool includeVBases = true) const;
2201
2202  // Adds the encoding of a method parameter or return type.
2203  void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2204                                         QualType T, std::string& S,
2205                                         bool Extended) const;
2206
2207  const ASTRecordLayout &
2208  getObjCLayout(const ObjCInterfaceDecl *D,
2209                const ObjCImplementationDecl *Impl) const;
2210
2211private:
2212  /// \brief A set of deallocations that should be performed when the
2213  /// ASTContext is destroyed.
2214  SmallVector<std::pair<void (*)(void*), void *>, 16> Deallocations;
2215
2216  // FIXME: This currently contains the set of StoredDeclMaps used
2217  // by DeclContext objects.  This probably should not be in ASTContext,
2218  // but we include it here so that ASTContext can quickly deallocate them.
2219  llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2220
2221  /// \brief A counter used to uniquely identify "blocks".
2222  mutable unsigned int UniqueBlockByRefTypeID;
2223
2224  friend class DeclContext;
2225  friend class DeclarationNameTable;
2226  void ReleaseDeclContextMaps();
2227
2228  /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
2229  /// parents as defined by the \c RecursiveASTVisitor.
2230  ///
2231  /// Note that the relationship described here is purely in terms of AST
2232  /// traversal - there are other relationships (for example declaration context)
2233  /// in the AST that are better modeled by special matchers.
2234  ///
2235  /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
2236  class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
2237  public:
2238    /// \brief Builds and returns the translation unit's parent map.
2239    ///
2240    ///  The caller takes ownership of the returned \c ParentMap.
2241    static ParentMap *buildMap(TranslationUnitDecl &TU) {
2242      ParentMapASTVisitor Visitor(new ParentMap);
2243      Visitor.TraverseDecl(&TU);
2244      return Visitor.Parents;
2245    }
2246
2247  private:
2248    typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
2249
2250    ParentMapASTVisitor(ParentMap *Parents) : Parents(Parents) {
2251    }
2252
2253    bool shouldVisitTemplateInstantiations() const {
2254      return true;
2255    }
2256    bool shouldVisitImplicitCode() const {
2257      return true;
2258    }
2259    // Disables data recursion. We intercept Traverse* methods in the RAV, which
2260    // are not triggered during data recursion.
2261    bool shouldUseDataRecursionFor(clang::Stmt *S) const {
2262      return false;
2263    }
2264
2265    template <typename T>
2266    bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
2267      if (Node == NULL)
2268        return true;
2269      if (ParentStack.size() > 0)
2270        // FIXME: Currently we add the same parent multiple times, for example
2271        // when we visit all subexpressions of template instantiations; this is
2272        // suboptimal, bug benign: the only way to visit those is with
2273        // hasAncestor / hasParent, and those do not create new matches.
2274        // The plan is to enable DynTypedNode to be storable in a map or hash
2275        // map. The main problem there is to implement hash functions /
2276        // comparison operators for all types that DynTypedNode supports that
2277        // do not have pointer identity.
2278        (*Parents)[Node].push_back(ParentStack.back());
2279      ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
2280      bool Result = (this ->* traverse) (Node);
2281      ParentStack.pop_back();
2282      return Result;
2283    }
2284
2285    bool TraverseDecl(Decl *DeclNode) {
2286      return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
2287    }
2288
2289    bool TraverseStmt(Stmt *StmtNode) {
2290      return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
2291    }
2292
2293    ParentMap *Parents;
2294    llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
2295
2296    friend class RecursiveASTVisitor<ParentMapASTVisitor>;
2297  };
2298
2299  llvm::OwningPtr<ParentMap> AllParents;
2300};
2301
2302/// \brief Utility function for constructing a nullary selector.
2303static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2304  IdentifierInfo* II = &Ctx.Idents.get(name);
2305  return Ctx.Selectors.getSelector(0, &II);
2306}
2307
2308/// \brief Utility function for constructing an unary selector.
2309static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2310  IdentifierInfo* II = &Ctx.Idents.get(name);
2311  return Ctx.Selectors.getSelector(1, &II);
2312}
2313
2314}  // end namespace clang
2315
2316// operator new and delete aren't allowed inside namespaces.
2317
2318/// @brief Placement new for using the ASTContext's allocator.
2319///
2320/// This placement form of operator new uses the ASTContext's allocator for
2321/// obtaining memory.
2322///
2323/// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2324/// here need to also be made there.
2325///
2326/// We intentionally avoid using a nothrow specification here so that the calls
2327/// to this operator will not perform a null check on the result -- the
2328/// underlying allocator never returns null pointers.
2329///
2330/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2331/// @code
2332/// // Default alignment (8)
2333/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2334/// // Specific alignment
2335/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2336/// @endcode
2337/// Please note that you cannot use delete on the pointer; it must be
2338/// deallocated using an explicit destructor call followed by
2339/// @c Context.Deallocate(Ptr).
2340///
2341/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2342/// @param C The ASTContext that provides the allocator.
2343/// @param Alignment The alignment of the allocated memory (if the underlying
2344///                  allocator supports it).
2345/// @return The allocated memory. Could be NULL.
2346inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2347                          size_t Alignment) {
2348  return C.Allocate(Bytes, Alignment);
2349}
2350/// @brief Placement delete companion to the new above.
2351///
2352/// This operator is just a companion to the new above. There is no way of
2353/// invoking it directly; see the new operator for more details. This operator
2354/// is called implicitly by the compiler if a placement new expression using
2355/// the ASTContext throws in the object constructor.
2356inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2357  C.Deallocate(Ptr);
2358}
2359
2360/// This placement form of operator new[] uses the ASTContext's allocator for
2361/// obtaining memory.
2362///
2363/// We intentionally avoid using a nothrow specification here so that the calls
2364/// to this operator will not perform a null check on the result -- the
2365/// underlying allocator never returns null pointers.
2366///
2367/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2368/// @code
2369/// // Default alignment (8)
2370/// char *data = new (Context) char[10];
2371/// // Specific alignment
2372/// char *data = new (Context, 4) char[10];
2373/// @endcode
2374/// Please note that you cannot use delete on the pointer; it must be
2375/// deallocated using an explicit destructor call followed by
2376/// @c Context.Deallocate(Ptr).
2377///
2378/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2379/// @param C The ASTContext that provides the allocator.
2380/// @param Alignment The alignment of the allocated memory (if the underlying
2381///                  allocator supports it).
2382/// @return The allocated memory. Could be NULL.
2383inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2384                            size_t Alignment = 8) {
2385  return C.Allocate(Bytes, Alignment);
2386}
2387
2388/// @brief Placement delete[] companion to the new[] above.
2389///
2390/// This operator is just a companion to the new[] above. There is no way of
2391/// invoking it directly; see the new[] operator for more details. This operator
2392/// is called implicitly by the compiler if a placement new[] expression using
2393/// the ASTContext throws in the object constructor.
2394inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2395  C.Deallocate(Ptr);
2396}
2397
2398#endif
2399