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