Warning: That file was not part of the compilation database. It may have many parsing errors.

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/// 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/ComparisonCategories.h"
22#include "clang/AST/Decl.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/DeclarationName.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/PrettyPrinter.h"
28#include "clang/AST/RawCommentList.h"
29#include "clang/AST/TemplateBase.h"
30#include "clang/AST/TemplateName.h"
31#include "clang/AST/Type.h"
32#include "clang/Basic/AddressSpaces.h"
33#include "clang/Basic/IdentifierTable.h"
34#include "clang/Basic/LLVM.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/Linkage.h"
37#include "clang/Basic/OperatorKinds.h"
38#include "clang/Basic/PartialDiagnostic.h"
39#include "clang/Basic/SanitizerBlacklist.h"
40#include "clang/Basic/SourceLocation.h"
41#include "clang/Basic/Specifiers.h"
42#include "clang/Basic/TargetInfo.h"
43#include "clang/Basic/XRayLists.h"
44#include "llvm/ADT/APSInt.h"
45#include "llvm/ADT/ArrayRef.h"
46#include "llvm/ADT/DenseMap.h"
47#include "llvm/ADT/FoldingSet.h"
48#include "llvm/ADT/IntrusiveRefCntPtr.h"
49#include "llvm/ADT/MapVector.h"
50#include "llvm/ADT/None.h"
51#include "llvm/ADT/Optional.h"
52#include "llvm/ADT/PointerIntPair.h"
53#include "llvm/ADT/PointerUnion.h"
54#include "llvm/ADT/SmallVector.h"
55#include "llvm/ADT/StringMap.h"
56#include "llvm/ADT/StringRef.h"
57#include "llvm/ADT/TinyPtrVector.h"
58#include "llvm/ADT/Triple.h"
59#include "llvm/ADT/iterator_range.h"
60#include "llvm/Support/AlignOf.h"
61#include "llvm/Support/Allocator.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/Compiler.h"
64#include <cassert>
65#include <cstddef>
66#include <cstdint>
67#include <iterator>
68#include <memory>
69#include <string>
70#include <type_traits>
71#include <utility>
72#include <vector>
73
74namespace llvm {
75
76struct fltSemantics;
77
78} // namespace llvm
79
80namespace clang {
81
82class APValue;
83class ASTMutationListener;
84class ASTRecordLayout;
85class AtomicExpr;
86class BlockExpr;
87class BuiltinTemplateDecl;
88class CharUnits;
89class CXXABI;
90class CXXConstructorDecl;
91class CXXMethodDecl;
92class CXXRecordDecl;
93class DiagnosticsEngine;
94class Expr;
95class MangleContext;
96class MangleNumberingContext;
97class MaterializeTemporaryExpr;
98class MemberSpecializationInfo;
99class Module;
100class ObjCCategoryDecl;
101class ObjCCategoryImplDecl;
102class ObjCContainerDecl;
103class ObjCImplDecl;
104class ObjCImplementationDecl;
105class ObjCInterfaceDecl;
106class ObjCIvarDecl;
107class ObjCMethodDecl;
108class ObjCPropertyDecl;
109class ObjCPropertyImplDecl;
110class ObjCProtocolDecl;
111class ObjCTypeParamDecl;
112class Preprocessor;
113class Stmt;
114class StoredDeclsMap;
115class TemplateDecl;
116class TemplateParameterList;
117class TemplateTemplateParmDecl;
118class TemplateTypeParmDecl;
119class UnresolvedSetIterator;
120class UsingShadowDecl;
121class VarTemplateDecl;
122class VTableContextBase;
123
124namespace Builtin {
125
126class Context;
127
128} // namespace Builtin
129
130enum BuiltinTemplateKind : int;
131
132namespace comments {
133
134class FullComment;
135
136} // namespace comments
137
138struct TypeInfo {
139 uint64_t Width = 0;
140 unsigned Align = 0;
141 bool AlignIsRequired : 1;
142
143 TypeInfo() : AlignIsRequired(false) {}
144 TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
145 : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
146};
147
148/// Holds long-lived AST nodes (such as types and decls) that can be
149/// referred to throughout the semantic analysis of a file.
150class ASTContext : public RefCountedBase<ASTContext> {
151 friend class NestedNameSpecifier;
152
153 mutable SmallVector<Type *, 0> Types;
154 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
155 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
156 mutable llvm::FoldingSet<PointerType> PointerTypes;
157 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
158 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
159 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
160 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
161 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
162 mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
163 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
164 mutable std::vector<VariableArrayType*> VariableArrayTypes;
165 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
166 mutable llvm::FoldingSet<DependentSizedExtVectorType>
167 DependentSizedExtVectorTypes;
168 mutable llvm::FoldingSet<DependentAddressSpaceType>
169 DependentAddressSpaceTypes;
170 mutable llvm::FoldingSet<VectorType> VectorTypes;
171 mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes;
172 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
173 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
174 FunctionProtoTypes;
175 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
176 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
177 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
178 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
179 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
180 SubstTemplateTypeParmTypes;
181 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
182 SubstTemplateTypeParmPackTypes;
183 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
184 TemplateSpecializationTypes;
185 mutable llvm::FoldingSet<ParenType> ParenTypes;
186 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
187 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
188 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
189 ASTContext&>
190 DependentTemplateSpecializationTypes;
191 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
192 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
193 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
194 mutable llvm::FoldingSet<DependentUnaryTransformType>
195 DependentUnaryTransformTypes;
196 mutable llvm::FoldingSet<AutoType> AutoTypes;
197 mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
198 DeducedTemplateSpecializationTypes;
199 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
200 llvm::FoldingSet<AttributedType> AttributedTypes;
201 mutable llvm::FoldingSet<PipeType> PipeTypes;
202
203 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
204 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
205 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
206 SubstTemplateTemplateParms;
207 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
208 ASTContext&>
209 SubstTemplateTemplateParmPacks;
210
211 /// The set of nested name specifiers.
212 ///
213 /// This set is managed by the NestedNameSpecifier class.
214 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
215 mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
216
217 /// A cache mapping from RecordDecls to ASTRecordLayouts.
218 ///
219 /// This is lazily created. This is intentionally not serialized.
220 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
221 ASTRecordLayouts;
222 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
223 ObjCLayouts;
224
225 /// A cache from types to size and alignment information.
226 using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
227 mutable TypeInfoMap MemoizedTypeInfo;
228
229 /// A cache from types to unadjusted alignment information. Only ARM and
230 /// AArch64 targets need this information, keeping it separate prevents
231 /// imposing overhead on TypeInfo size.
232 using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>;
233 mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
234
235 /// A cache mapping from CXXRecordDecls to key functions.
236 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
237
238 /// Mapping from ObjCContainers to their ObjCImplementations.
239 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
240
241 /// Mapping from ObjCMethod to its duplicate declaration in the same
242 /// interface.
243 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
244
245 /// Mapping from __block VarDecls to their copy initialization expr.
246 llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
247
248 /// Mapping from class scope functions specialization to their
249 /// template patterns.
250 llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
251 ClassScopeSpecializationPattern;
252
253 /// Mapping from materialized temporaries with static storage duration
254 /// that appear in constant initializers to their evaluated values. These are
255 /// allocated in a std::map because their address must be stable.
256 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue *>
257 MaterializedTemporaryValues;
258
259 /// Representation of a "canonical" template template parameter that
260 /// is used in canonical template names.
261 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
262 TemplateTemplateParmDecl *Parm;
263
264 public:
265 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
266 : Parm(Parm) {}
267
268 TemplateTemplateParmDecl *getParam() const { return Parm; }
269
270 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
271
272 static void Profile(llvm::FoldingSetNodeID &ID,
273 TemplateTemplateParmDecl *Parm);
274 };
275 mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
276 CanonTemplateTemplateParms;
277
278 TemplateTemplateParmDecl *
279 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
280
281 /// The typedef for the __int128_t type.
282 mutable TypedefDecl *Int128Decl = nullptr;
283
284 /// The typedef for the __uint128_t type.
285 mutable TypedefDecl *UInt128Decl = nullptr;
286
287 /// The typedef for the target specific predefined
288 /// __builtin_va_list type.
289 mutable TypedefDecl *BuiltinVaListDecl = nullptr;
290
291 /// The typedef for the predefined \c __builtin_ms_va_list type.
292 mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
293
294 /// The typedef for the predefined \c id type.
295 mutable TypedefDecl *ObjCIdDecl = nullptr;
296
297 /// The typedef for the predefined \c SEL type.
298 mutable TypedefDecl *ObjCSelDecl = nullptr;
299
300 /// The typedef for the predefined \c Class type.
301 mutable TypedefDecl *ObjCClassDecl = nullptr;
302
303 /// The typedef for the predefined \c Protocol class in Objective-C.
304 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
305
306 /// The typedef for the predefined 'BOOL' type.
307 mutable TypedefDecl *BOOLDecl = nullptr;
308
309 // Typedefs which may be provided defining the structure of Objective-C
310 // pseudo-builtins
311 QualType ObjCIdRedefinitionType;
312 QualType ObjCClassRedefinitionType;
313 QualType ObjCSelRedefinitionType;
314
315 /// The identifier 'bool'.
316 mutable IdentifierInfo *BoolName = nullptr;
317
318 /// The identifier 'NSObject'.
319 IdentifierInfo *NSObjectName = nullptr;
320
321 /// The identifier 'NSCopying'.
322 IdentifierInfo *NSCopyingName = nullptr;
323
324 /// The identifier '__make_integer_seq'.
325 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
326
327 /// The identifier '__type_pack_element'.
328 mutable IdentifierInfo *TypePackElementName = nullptr;
329
330 QualType ObjCConstantStringType;
331 mutable RecordDecl *CFConstantStringTagDecl = nullptr;
332 mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
333
334 mutable QualType ObjCSuperType;
335
336 QualType ObjCNSStringType;
337
338 /// The typedef declaration for the Objective-C "instancetype" type.
339 TypedefDecl *ObjCInstanceTypeDecl = nullptr;
340
341 /// The type for the C FILE type.
342 TypeDecl *FILEDecl = nullptr;
343
344 /// The type for the C jmp_buf type.
345 TypeDecl *jmp_bufDecl = nullptr;
346
347 /// The type for the C sigjmp_buf type.
348 TypeDecl *sigjmp_bufDecl = nullptr;
349
350 /// The type for the C ucontext_t type.
351 TypeDecl *ucontext_tDecl = nullptr;
352
353 /// Type for the Block descriptor for Blocks CodeGen.
354 ///
355 /// Since this is only used for generation of debug info, it is not
356 /// serialized.
357 mutable RecordDecl *BlockDescriptorType = nullptr;
358
359 /// Type for the Block descriptor for Blocks CodeGen.
360 ///
361 /// Since this is only used for generation of debug info, it is not
362 /// serialized.
363 mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
364
365 /// Declaration for the CUDA cudaConfigureCall function.
366 FunctionDecl *cudaConfigureCallDecl = nullptr;
367
368 /// Keeps track of all declaration attributes.
369 ///
370 /// Since so few decls have attrs, we keep them in a hash map instead of
371 /// wasting space in the Decl class.
372 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
373
374 /// A mapping from non-redeclarable declarations in modules that were
375 /// merged with other declarations to the canonical declaration that they were
376 /// merged into.
377 llvm::DenseMap<Decl*, Decl*> MergedDecls;
378
379 /// A mapping from a defining declaration to a list of modules (other
380 /// than the owning module of the declaration) that contain merged
381 /// definitions of that entity.
382 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
383
384 /// Initializers for a module, in order. Each Decl will be either
385 /// something that has a semantic effect on startup (such as a variable with
386 /// a non-constant initializer), or an ImportDecl (which recursively triggers
387 /// initialization of another module).
388 struct PerModuleInitializers {
389 llvm::SmallVector<Decl*, 4> Initializers;
390 llvm::SmallVector<uint32_t, 4> LazyInitializers;
391
392 void resolve(ASTContext &Ctx);
393 };
394 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
395
396 ASTContext &this_() { return *this; }
397
398public:
399 /// A type synonym for the TemplateOrInstantiation mapping.
400 using TemplateOrSpecializationInfo =
401 llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
402
403private:
404 friend class ASTDeclReader;
405 friend class ASTReader;
406 friend class ASTWriter;
407 friend class CXXRecordDecl;
408
409 /// A mapping to contain the template or declaration that
410 /// a variable declaration describes or was instantiated from,
411 /// respectively.
412 ///
413 /// For non-templates, this value will be NULL. For variable
414 /// declarations that describe a variable template, this will be a
415 /// pointer to a VarTemplateDecl. For static data members
416 /// of class template specializations, this will be the
417 /// MemberSpecializationInfo referring to the member variable that was
418 /// instantiated or specialized. Thus, the mapping will keep track of
419 /// the static data member templates from which static data members of
420 /// class template specializations were instantiated.
421 ///
422 /// Given the following example:
423 ///
424 /// \code
425 /// template<typename T>
426 /// struct X {
427 /// static T value;
428 /// };
429 ///
430 /// template<typename T>
431 /// T X<T>::value = T(17);
432 ///
433 /// int *x = &X<int>::value;
434 /// \endcode
435 ///
436 /// This mapping will contain an entry that maps from the VarDecl for
437 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
438 /// class template X) and will be marked TSK_ImplicitInstantiation.
439 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
440 TemplateOrInstantiation;
441
442 /// Keeps track of the declaration from which a using declaration was
443 /// created during instantiation.
444 ///
445 /// The source and target declarations are always a UsingDecl, an
446 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
447 ///
448 /// For example:
449 /// \code
450 /// template<typename T>
451 /// struct A {
452 /// void f();
453 /// };
454 ///
455 /// template<typename T>
456 /// struct B : A<T> {
457 /// using A<T>::f;
458 /// };
459 ///
460 /// template struct B<int>;
461 /// \endcode
462 ///
463 /// This mapping will contain an entry that maps from the UsingDecl in
464 /// B<int> to the UnresolvedUsingDecl in B<T>.
465 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
466
467 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
468 InstantiatedFromUsingShadowDecl;
469
470 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
471
472 /// Mapping that stores the methods overridden by a given C++
473 /// member function.
474 ///
475 /// Since most C++ member functions aren't virtual and therefore
476 /// don't override anything, we store the overridden functions in
477 /// this map on the side rather than within the CXXMethodDecl structure.
478 using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
479 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
480
481 /// Mapping from each declaration context to its corresponding
482 /// mangling numbering context (used for constructs like lambdas which
483 /// need to be consistently numbered for the mangler).
484 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
485 MangleNumberingContexts;
486
487 /// Side-table of mangling numbers for declarations which rarely
488 /// need them (like static local vars).
489 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
490 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
491
492 /// Mapping that stores parameterIndex values for ParmVarDecls when
493 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
494 using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
495 ParameterIndexTable ParamIndices;
496
497 ImportDecl *FirstLocalImport = nullptr;
498 ImportDecl *LastLocalImport = nullptr;
499
500 TranslationUnitDecl *TUDecl;
501 mutable ExternCContextDecl *ExternCContext = nullptr;
502 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
503 mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
504
505 /// The associated SourceManager object.
506 SourceManager &SourceMgr;
507
508 /// The language options used to create the AST associated with
509 /// this ASTContext object.
510 LangOptions &LangOpts;
511
512 /// Blacklist object that is used by sanitizers to decide which
513 /// entities should not be instrumented.
514 std::unique_ptr<SanitizerBlacklist> SanitizerBL;
515
516 /// Function filtering mechanism to determine whether a given function
517 /// should be imbued with the XRay "always" or "never" attributes.
518 std::unique_ptr<XRayFunctionFilter> XRayFilter;
519
520 /// The allocator used to create AST objects.
521 ///
522 /// AST objects are never destructed; rather, all memory associated with the
523 /// AST objects will be released when the ASTContext itself is destroyed.
524 mutable llvm::BumpPtrAllocator BumpAlloc;
525
526 /// Allocator for partial diagnostics.
527 PartialDiagnostic::StorageAllocator DiagAllocator;
528
529 /// The current C++ ABI.
530 std::unique_ptr<CXXABI> ABI;
531 CXXABI *createCXXABI(const TargetInfo &T);
532
533 /// The logical -> physical address space map.
534 const LangASMap *AddrSpaceMap = nullptr;
535
536 /// Address space map mangling must be used with language specific
537 /// address spaces (e.g. OpenCL/CUDA)
538 bool AddrSpaceMapMangling;
539
540 const TargetInfo *Target = nullptr;
541 const TargetInfo *AuxTarget = nullptr;
542 clang::PrintingPolicy PrintingPolicy;
543
544public:
545 IdentifierTable &Idents;
546 SelectorTable &Selectors;
547 Builtin::Context &BuiltinInfo;
548 mutable DeclarationNameTable DeclarationNames;
549 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
550 ASTMutationListener *Listener = nullptr;
551
552 /// Contains parents of a node.
553 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
554
555 /// Maps from a node to its parents. This is used for nodes that have
556 /// pointer identity only, which are more common and we can save space by
557 /// only storing a unique pointer to them.
558 using ParentMapPointers =
559 llvm::DenseMap<const void *,
560 llvm::PointerUnion4<const Decl *, const Stmt *,
561 ast_type_traits::DynTypedNode *,
562 ParentVector *>>;
563
564 /// Parent map for nodes without pointer identity. We store a full
565 /// DynTypedNode for all keys.
566 using ParentMapOtherNodes =
567 llvm::DenseMap<ast_type_traits::DynTypedNode,
568 llvm::PointerUnion4<const Decl *, const Stmt *,
569 ast_type_traits::DynTypedNode *,
570 ParentVector *>>;
571
572 /// Container for either a single DynTypedNode or for an ArrayRef to
573 /// DynTypedNode. For use with ParentMap.
574 class DynTypedNodeList {
575 using DynTypedNode = ast_type_traits::DynTypedNode;
576
577 llvm::AlignedCharArrayUnion<ast_type_traits::DynTypedNode,
578 ArrayRef<DynTypedNode>> Storage;
579 bool IsSingleNode;
580
581 public:
582 DynTypedNodeList(const DynTypedNode &N) : IsSingleNode(true) {
583 new (Storage.buffer) DynTypedNode(N);
584 }
585
586 DynTypedNodeList(ArrayRef<DynTypedNode> A) : IsSingleNode(false) {
587 new (Storage.buffer) ArrayRef<DynTypedNode>(A);
588 }
589
590 const ast_type_traits::DynTypedNode *begin() const {
591 if (!IsSingleNode)
592 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
593 ->begin();
594 return reinterpret_cast<const DynTypedNode *>(Storage.buffer);
595 }
596
597 const ast_type_traits::DynTypedNode *end() const {
598 if (!IsSingleNode)
599 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
600 ->end();
601 return reinterpret_cast<const DynTypedNode *>(Storage.buffer) + 1;
602 }
603
604 size_t size() const { return end() - begin(); }
605 bool empty() const { return begin() == end(); }
606
607 const DynTypedNode &operator[](size_t N) const {
608 assert(N < size() && "Out of bounds!");
609 return *(begin() + N);
610 }
611 };
612
613 /// Returns the parents of the given node.
614 ///
615 /// Note that this will lazily compute the parents of all nodes
616 /// and store them for later retrieval. Thus, the first call is O(n)
617 /// in the number of AST nodes.
618 ///
619 /// Caveats and FIXMEs:
620 /// Calculating the parent map over all AST nodes will need to load the
621 /// full AST. This can be undesirable in the case where the full AST is
622 /// expensive to create (for example, when using precompiled header
623 /// preambles). Thus, there are good opportunities for optimization here.
624 /// One idea is to walk the given node downwards, looking for references
625 /// to declaration contexts - once a declaration context is found, compute
626 /// the parent map for the declaration context; if that can satisfy the
627 /// request, loading the whole AST can be avoided. Note that this is made
628 /// more complex by statements in templates having multiple parents - those
629 /// problems can be solved by building closure over the templated parts of
630 /// the AST, which also avoids touching large parts of the AST.
631 /// Additionally, we will want to add an interface to already give a hint
632 /// where to search for the parents, for example when looking at a statement
633 /// inside a certain function.
634 ///
635 /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
636 /// NestedNameSpecifier or NestedNameSpecifierLoc.
637 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node) {
638 return getParents(ast_type_traits::DynTypedNode::create(Node));
639 }
640
641 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node);
642
643 const clang::PrintingPolicy &getPrintingPolicy() const {
644 return PrintingPolicy;
645 }
646
647 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
648 PrintingPolicy = Policy;
649 }
650
651 SourceManager& getSourceManager() { return SourceMgr; }
652 const SourceManager& getSourceManager() const { return SourceMgr; }
653
654 llvm::BumpPtrAllocator &getAllocator() const {
655 return BumpAlloc;
656 }
657
658 void *Allocate(size_t Size, unsigned Align = 8) const {
659 return BumpAlloc.Allocate(Size, Align);
660 }
661 template <typename T> T *Allocate(size_t Num = 1) const {
662 return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
663 }
664 void Deallocate(void *Ptr) const {}
665
666 /// Return the total amount of physical memory allocated for representing
667 /// AST nodes and type information.
668 size_t getASTAllocatedMemory() const {
669 return BumpAlloc.getTotalMemory();
670 }
671
672 /// Return the total memory used for various side tables.
673 size_t getSideTableAllocatedMemory() const;
674
675 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
676 return DiagAllocator;
677 }
678
679 const TargetInfo &getTargetInfo() const { return *Target; }
680 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
681
682 /// getIntTypeForBitwidth -
683 /// sets integer QualTy according to specified details:
684 /// bitwidth, signed/unsigned.
685 /// Returns empty type if there is no appropriate target types.
686 QualType getIntTypeForBitwidth(unsigned DestWidth,
687 unsigned Signed) const;
688
689 /// getRealTypeForBitwidth -
690 /// sets floating point QualTy according to specified bitwidth.
691 /// Returns empty type if there is no appropriate target types.
692 QualType getRealTypeForBitwidth(unsigned DestWidth) const;
693
694 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
695
696 const LangOptions& getLangOpts() const { return LangOpts; }
697
698 const SanitizerBlacklist &getSanitizerBlacklist() const {
699 return *SanitizerBL;
700 }
701
702 const XRayFunctionFilter &getXRayFilter() const {
703 return *XRayFilter;
704 }
705
706 DiagnosticsEngine &getDiagnostics() const;
707
708 FullSourceLoc getFullLoc(SourceLocation Loc) const {
709 return FullSourceLoc(Loc,SourceMgr);
710 }
711
712 /// All comments in this translation unit.
713 RawCommentList Comments;
714
715 /// True if comments are already loaded from ExternalASTSource.
716 mutable bool CommentsLoaded = false;
717
718 class RawCommentAndCacheFlags {
719 public:
720 enum Kind {
721 /// We searched for a comment attached to the particular declaration, but
722 /// didn't find any.
723 ///
724 /// getRaw() == 0.
725 NoCommentInDecl = 0,
726
727 /// We have found a comment attached to this particular declaration.
728 ///
729 /// getRaw() != 0.
730 FromDecl,
731
732 /// This declaration does not have an attached comment, and we have
733 /// searched the redeclaration chain.
734 ///
735 /// If getRaw() == 0, the whole redeclaration chain does not have any
736 /// comments.
737 ///
738 /// If getRaw() != 0, it is a comment propagated from other
739 /// redeclaration.
740 FromRedecl
741 };
742
743 Kind getKind() const LLVM_READONLY {
744 return Data.getInt();
745 }
746
747 void setKind(Kind K) {
748 Data.setInt(K);
749 }
750
751 const RawComment *getRaw() const LLVM_READONLY {
752 return Data.getPointer();
753 }
754
755 void setRaw(const RawComment *RC) {
756 Data.setPointer(RC);
757 }
758
759 const Decl *getOriginalDecl() const LLVM_READONLY {
760 return OriginalDecl;
761 }
762
763 void setOriginalDecl(const Decl *Orig) {
764 OriginalDecl = Orig;
765 }
766
767 private:
768 llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
769 const Decl *OriginalDecl;
770 };
771
772 /// Mapping from declarations to comments attached to any
773 /// redeclaration.
774 ///
775 /// Raw comments are owned by Comments list. This mapping is populated
776 /// lazily.
777 mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
778
779 /// Mapping from declarations to parsed comments attached to any
780 /// redeclaration.
781 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
782
783 /// Return the documentation comment attached to a given declaration,
784 /// without looking into cache.
785 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
786
787public:
788 RawCommentList &getRawCommentList() {
789 return Comments;
790 }
791
792 void addComment(const RawComment &RC) {
793 assert(LangOpts.RetainCommentsFromSystemHeaders ||
794 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
795 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
796 }
797
798 /// Return the documentation comment attached to a given declaration.
799 /// Returns nullptr if no comment is attached.
800 ///
801 /// \param OriginalDecl if not nullptr, is set to declaration AST node that
802 /// had the comment, if the comment we found comes from a redeclaration.
803 const RawComment *
804 getRawCommentForAnyRedecl(const Decl *D,
805 const Decl **OriginalDecl = nullptr) const;
806
807 /// Return parsed documentation comment attached to a given declaration.
808 /// Returns nullptr if no comment is attached.
809 ///
810 /// \param PP the Preprocessor used with this TU. Could be nullptr if
811 /// preprocessor is not available.
812 comments::FullComment *getCommentForDecl(const Decl *D,
813 const Preprocessor *PP) const;
814
815 /// Return parsed documentation comment attached to a given declaration.
816 /// Returns nullptr if no comment is attached. Does not look at any
817 /// redeclarations of the declaration.
818 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
819
820 comments::FullComment *cloneFullComment(comments::FullComment *FC,
821 const Decl *D) const;
822
823private:
824 mutable comments::CommandTraits CommentCommandTraits;
825
826 /// Iterator that visits import declarations.
827 class import_iterator {
828 ImportDecl *Import = nullptr;
829
830 public:
831 using value_type = ImportDecl *;
832 using reference = ImportDecl *;
833 using pointer = ImportDecl *;
834 using difference_type = int;
835 using iterator_category = std::forward_iterator_tag;
836
837 import_iterator() = default;
838 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
839
840 reference operator*() const { return Import; }
841 pointer operator->() const { return Import; }
842
843 import_iterator &operator++() {
844 Import = ASTContext::getNextLocalImport(Import);
845 return *this;
846 }
847
848 import_iterator operator++(int) {
849 import_iterator Other(*this);
850 ++(*this);
851 return Other;
852 }
853
854 friend bool operator==(import_iterator X, import_iterator Y) {
855 return X.Import == Y.Import;
856 }
857
858 friend bool operator!=(import_iterator X, import_iterator Y) {
859 return X.Import != Y.Import;
860 }
861 };
862
863public:
864 comments::CommandTraits &getCommentCommandTraits() const {
865 return CommentCommandTraits;
866 }
867
868 /// Retrieve the attributes for the given declaration.
869 AttrVec& getDeclAttrs(const Decl *D);
870
871 /// Erase the attributes corresponding to the given declaration.
872 void eraseDeclAttrs(const Decl *D);
873
874 /// If this variable is an instantiated static data member of a
875 /// class template specialization, returns the templated static data member
876 /// from which it was instantiated.
877 // FIXME: Remove ?
878 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
879 const VarDecl *Var);
880
881 TemplateOrSpecializationInfo
882 getTemplateOrSpecializationInfo(const VarDecl *Var);
883
884 FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
885
886 void setClassScopeSpecializationPattern(FunctionDecl *FD,
887 FunctionDecl *Pattern);
888
889 /// Note that the static data member \p Inst is an instantiation of
890 /// the static data member template \p Tmpl of a class template.
891 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
892 TemplateSpecializationKind TSK,
893 SourceLocation PointOfInstantiation = SourceLocation());
894
895 void setTemplateOrSpecializationInfo(VarDecl *Inst,
896 TemplateOrSpecializationInfo TSI);
897
898 /// If the given using decl \p Inst is an instantiation of a
899 /// (possibly unresolved) using decl from a template instantiation,
900 /// return it.
901 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
902
903 /// Remember that the using decl \p Inst is an instantiation
904 /// of the using decl \p Pattern of a class template.
905 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
906
907 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
908 UsingShadowDecl *Pattern);
909 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
910
911 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
912
913 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
914
915 // Access to the set of methods overridden by the given C++ method.
916 using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
917 overridden_cxx_method_iterator
918 overridden_methods_begin(const CXXMethodDecl *Method) const;
919
920 overridden_cxx_method_iterator
921 overridden_methods_end(const CXXMethodDecl *Method) const;
922
923 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
924
925 using overridden_method_range =
926 llvm::iterator_range<overridden_cxx_method_iterator>;
927
928 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
929
930 /// Note that the given C++ \p Method overrides the given \p
931 /// Overridden method.
932 void addOverriddenMethod(const CXXMethodDecl *Method,
933 const CXXMethodDecl *Overridden);
934
935 /// Return C++ or ObjC overridden methods for the given \p Method.
936 ///
937 /// An ObjC method is considered to override any method in the class's
938 /// base classes, its protocols, or its categories' protocols, that has
939 /// the same selector and is of the same kind (class or instance).
940 /// A method in an implementation is not considered as overriding the same
941 /// method in the interface or its categories.
942 void getOverriddenMethods(
943 const NamedDecl *Method,
944 SmallVectorImpl<const NamedDecl *> &Overridden) const;
945
946 /// Notify the AST context that a new import declaration has been
947 /// parsed or implicitly created within this translation unit.
948 void addedLocalImportDecl(ImportDecl *Import);
949
950 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
951 return Import->NextLocalImport;
952 }
953
954 using import_range = llvm::iterator_range<import_iterator>;
955
956 import_range local_imports() const {
957 return import_range(import_iterator(FirstLocalImport), import_iterator());
958 }
959
960 Decl *getPrimaryMergedDecl(Decl *D) {
961 Decl *Result = MergedDecls.lookup(D);
962 return Result ? Result : D;
963 }
964 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
965 MergedDecls[D] = Primary;
966 }
967
968 /// Note that the definition \p ND has been merged into module \p M,
969 /// and should be visible whenever \p M is visible.
970 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
971 bool NotifyListeners = true);
972
973 /// Clean up the merged definition list. Call this if you might have
974 /// added duplicates into the list.
975 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
976
977 /// Get the additional modules in which the definition \p Def has
978 /// been merged.
979 ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def) {
980 auto MergedIt = MergedDefModules.find(Def);
981 if (MergedIt == MergedDefModules.end())
982 return None;
983 return MergedIt->second;
984 }
985
986 /// Add a declaration to the list of declarations that are initialized
987 /// for a module. This will typically be a global variable (with internal
988 /// linkage) that runs module initializers, such as the iostream initializer,
989 /// or an ImportDecl nominating another module that has initializers.
990 void addModuleInitializer(Module *M, Decl *Init);
991
992 void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs);
993
994 /// Get the initializations to perform when importing a module, if any.
995 ArrayRef<Decl*> getModuleInitializers(Module *M);
996
997 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
998
999 ExternCContextDecl *getExternCContextDecl() const;
1000 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
1001 BuiltinTemplateDecl *getTypePackElementDecl() const;
1002
1003 // Builtin Types.
1004 CanQualType VoidTy;
1005 CanQualType BoolTy;
1006 CanQualType CharTy;
1007 CanQualType WCharTy; // [C++ 3.9.1p5].
1008 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
1009 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
1010 CanQualType Char8Ty; // [C++20 proposal]
1011 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
1012 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
1013 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
1014 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
1015 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
1016 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty;
1017 CanQualType ShortAccumTy, AccumTy,
1018 LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1019 CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
1020 CanQualType ShortFractTy, FractTy, LongFractTy;
1021 CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
1022 CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy;
1023 CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy,
1024 SatUnsignedLongAccumTy;
1025 CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
1026 CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
1027 SatUnsignedLongFractTy;
1028 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
1029 CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
1030 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
1031 CanQualType Float128ComplexTy;
1032 CanQualType VoidPtrTy, NullPtrTy;
1033 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
1034 CanQualType BuiltinFnTy;
1035 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
1036 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
1037 CanQualType ObjCBuiltinBoolTy;
1038#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1039 CanQualType SingletonId;
1040#include "clang/Basic/OpenCLImageTypes.def"
1041 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
1042 CanQualType OCLQueueTy, OCLReserveIDTy;
1043 CanQualType OMPArraySectionTy;
1044
1045 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
1046 mutable QualType AutoDeductTy; // Deduction against 'auto'.
1047 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
1048
1049 // Decl used to help define __builtin_va_list for some targets.
1050 // The decl is built when constructing 'BuiltinVaListDecl'.
1051 mutable Decl *VaListTagDecl;
1052
1053 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1054 SelectorTable &sels, Builtin::Context &builtins);
1055 ASTContext(const ASTContext &) = delete;
1056 ASTContext &operator=(const ASTContext &) = delete;
1057 ~ASTContext();
1058
1059 /// Attach an external AST source to the AST context.
1060 ///
1061 /// The external AST source provides the ability to load parts of
1062 /// the abstract syntax tree as needed from some external storage,
1063 /// e.g., a precompiled header.
1064 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1065
1066 /// Retrieve a pointer to the external AST source associated
1067 /// with this AST context, if any.
1068 ExternalASTSource *getExternalSource() const {
1069 return ExternalSource.get();
1070 }
1071
1072 /// Attach an AST mutation listener to the AST context.
1073 ///
1074 /// The AST mutation listener provides the ability to track modifications to
1075 /// the abstract syntax tree entities committed after they were initially
1076 /// created.
1077 void setASTMutationListener(ASTMutationListener *Listener) {
1078 this->Listener = Listener;
1079 }
1080
1081 /// Retrieve a pointer to the AST mutation listener associated
1082 /// with this AST context, if any.
1083 ASTMutationListener *getASTMutationListener() const { return Listener; }
1084
1085 void PrintStats() const;
1086 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1087
1088 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1089 const IdentifierInfo *II) const;
1090
1091 /// Create a new implicit TU-level CXXRecordDecl or RecordDecl
1092 /// declaration.
1093 RecordDecl *buildImplicitRecord(StringRef Name,
1094 RecordDecl::TagKind TK = TTK_Struct) const;
1095
1096 /// Create a new implicit TU-level typedef declaration.
1097 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1098
1099 /// Retrieve the declaration for the 128-bit signed integer type.
1100 TypedefDecl *getInt128Decl() const;
1101
1102 /// Retrieve the declaration for the 128-bit unsigned integer type.
1103 TypedefDecl *getUInt128Decl() const;
1104
1105 //===--------------------------------------------------------------------===//
1106 // Type Constructors
1107 //===--------------------------------------------------------------------===//
1108
1109private:
1110 /// Return a type with extended qualifiers.
1111 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1112
1113 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1114
1115 QualType getPipeType(QualType T, bool ReadOnly) const;
1116
1117public:
1118 /// Return the uniqued reference to the type for an address space
1119 /// qualified type with the specified type and address space.
1120 ///
1121 /// The resulting type has a union of the qualifiers from T and the address
1122 /// space. If T already has an address space specifier, it is silently
1123 /// replaced.
1124 QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
1125
1126 /// Remove any existing address space on the type and returns the type
1127 /// with qualifiers intact (or that's the idea anyway)
1128 ///
1129 /// The return type should be T with all prior qualifiers minus the address
1130 /// space.
1131 QualType removeAddrSpaceQualType(QualType T) const;
1132
1133 /// Apply Objective-C protocol qualifiers to the given type.
1134 /// \param allowOnPointerType specifies if we can apply protocol
1135 /// qualifiers on ObjCObjectPointerType. It can be set to true when
1136 /// constructing the canonical type of a Objective-C type parameter.
1137 QualType applyObjCProtocolQualifiers(QualType type,
1138 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1139 bool allowOnPointerType = false) const;
1140
1141 /// Return the uniqued reference to the type for an Objective-C
1142 /// gc-qualified type.
1143 ///
1144 /// The resulting type has a union of the qualifiers from T and the gc
1145 /// attribute.
1146 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1147
1148 /// Return the uniqued reference to the type for a \c restrict
1149 /// qualified type.
1150 ///
1151 /// The resulting type has a union of the qualifiers from \p T and
1152 /// \c restrict.
1153 QualType getRestrictType(QualType T) const {
1154 return T.withFastQualifiers(Qualifiers::Restrict);
1155 }
1156
1157 /// Return the uniqued reference to the type for a \c volatile
1158 /// qualified type.
1159 ///
1160 /// The resulting type has a union of the qualifiers from \p T and
1161 /// \c volatile.
1162 QualType getVolatileType(QualType T) const {
1163 return T.withFastQualifiers(Qualifiers::Volatile);
1164 }
1165
1166 /// Return the uniqued reference to the type for a \c const
1167 /// qualified type.
1168 ///
1169 /// The resulting type has a union of the qualifiers from \p T and \c const.
1170 ///
1171 /// It can be reasonably expected that this will always be equivalent to
1172 /// calling T.withConst().
1173 QualType getConstType(QualType T) const { return T.withConst(); }
1174
1175 /// Change the ExtInfo on a function type.
1176 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1177 FunctionType::ExtInfo EInfo);
1178
1179 /// Adjust the given function result type.
1180 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1181
1182 /// Change the result type of a function type once it is deduced.
1183 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1184
1185 /// Get a function type and produce the equivalent function type with the
1186 /// specified exception specification. Type sugar that can be present on a
1187 /// declaration of a function with an exception specification is permitted
1188 /// and preserved. Other type sugar (for instance, typedefs) is not.
1189 QualType getFunctionTypeWithExceptionSpec(
1190 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI);
1191
1192 /// Determine whether two function types are the same, ignoring
1193 /// exception specifications in cases where they're part of the type.
1194 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U);
1195
1196 /// Change the exception specification on a function once it is
1197 /// delay-parsed, instantiated, or computed.
1198 void adjustExceptionSpec(FunctionDecl *FD,
1199 const FunctionProtoType::ExceptionSpecInfo &ESI,
1200 bool AsWritten = false);
1201
1202 /// Return the uniqued reference to the type for a complex
1203 /// number with the specified element type.
1204 QualType getComplexType(QualType T) const;
1205 CanQualType getComplexType(CanQualType T) const {
1206 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1207 }
1208
1209 /// Return the uniqued reference to the type for a pointer to
1210 /// the specified type.
1211 QualType getPointerType(QualType T) const;
1212 CanQualType getPointerType(CanQualType T) const {
1213 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1214 }
1215
1216 /// Return the uniqued reference to a type adjusted from the original
1217 /// type to a new type.
1218 QualType getAdjustedType(QualType Orig, QualType New) const;
1219 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1220 return CanQualType::CreateUnsafe(
1221 getAdjustedType((QualType)Orig, (QualType)New));
1222 }
1223
1224 /// Return the uniqued reference to the decayed version of the given
1225 /// type. Can only be called on array and function types which decay to
1226 /// pointer types.
1227 QualType getDecayedType(QualType T) const;
1228 CanQualType getDecayedType(CanQualType T) const {
1229 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1230 }
1231
1232 /// Return the uniqued reference to the atomic type for the specified
1233 /// type.
1234 QualType getAtomicType(QualType T) const;
1235
1236 /// Return the uniqued reference to the type for a block of the
1237 /// specified type.
1238 QualType getBlockPointerType(QualType T) const;
1239
1240 /// Gets the struct used to keep track of the descriptor for pointer to
1241 /// blocks.
1242 QualType getBlockDescriptorType() const;
1243
1244 /// Return a read_only pipe type for the specified type.
1245 QualType getReadPipeType(QualType T) const;
1246
1247 /// Return a write_only pipe type for the specified type.
1248 QualType getWritePipeType(QualType T) const;
1249
1250 /// Gets the struct used to keep track of the extended descriptor for
1251 /// pointer to blocks.
1252 QualType getBlockDescriptorExtendedType() const;
1253
1254 /// Map an AST Type to an OpenCLTypeKind enum value.
1255 TargetInfo::OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
1256
1257 /// Get address space for OpenCL type.
1258 LangAS getOpenCLTypeAddrSpace(const Type *T) const;
1259
1260 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1261 cudaConfigureCallDecl = FD;
1262 }
1263
1264 FunctionDecl *getcudaConfigureCallDecl() {
1265 return cudaConfigureCallDecl;
1266 }
1267
1268 /// Returns true iff we need copy/dispose helpers for the given type.
1269 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1270
1271 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
1272 /// is set to false in this case. If HasByrefExtendedLayout returns true,
1273 /// byref variable has extended lifetime.
1274 bool getByrefLifetime(QualType Ty,
1275 Qualifiers::ObjCLifetime &Lifetime,
1276 bool &HasByrefExtendedLayout) const;
1277
1278 /// Return the uniqued reference to the type for an lvalue reference
1279 /// to the specified type.
1280 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1281 const;
1282
1283 /// Return the uniqued reference to the type for an rvalue reference
1284 /// to the specified type.
1285 QualType getRValueReferenceType(QualType T) const;
1286
1287 /// Return the uniqued reference to the type for a member pointer to
1288 /// the specified type in the specified class.
1289 ///
1290 /// The class \p Cls is a \c Type because it could be a dependent name.
1291 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1292
1293 /// Return a non-unique reference to the type for a variable array of
1294 /// the specified element type.
1295 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1296 ArrayType::ArraySizeModifier ASM,
1297 unsigned IndexTypeQuals,
1298 SourceRange Brackets) const;
1299
1300 /// Return a non-unique reference to the type for a dependently-sized
1301 /// array of the specified element type.
1302 ///
1303 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1304 /// point.
1305 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1306 ArrayType::ArraySizeModifier ASM,
1307 unsigned IndexTypeQuals,
1308 SourceRange Brackets) const;
1309
1310 /// Return a unique reference to the type for an incomplete array of
1311 /// the specified element type.
1312 QualType getIncompleteArrayType(QualType EltTy,
1313 ArrayType::ArraySizeModifier ASM,
1314 unsigned IndexTypeQuals) const;
1315
1316 /// Return the unique reference to the type for a constant array of
1317 /// the specified element type.
1318 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1319 ArrayType::ArraySizeModifier ASM,
1320 unsigned IndexTypeQuals) const;
1321
1322 /// Returns a vla type where known sizes are replaced with [*].
1323 QualType getVariableArrayDecayedType(QualType Ty) const;
1324
1325 /// Return the unique reference to a vector type of the specified
1326 /// element type and size.
1327 ///
1328 /// \pre \p VectorType must be a built-in type.
1329 QualType getVectorType(QualType VectorType, unsigned NumElts,
1330 VectorType::VectorKind VecKind) const;
1331 /// Return the unique reference to the type for a dependently sized vector of
1332 /// the specified element type.
1333 QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr,
1334 SourceLocation AttrLoc,
1335 VectorType::VectorKind VecKind) const;
1336
1337 /// Return the unique reference to an extended vector type
1338 /// of the specified element type and size.
1339 ///
1340 /// \pre \p VectorType must be a built-in type.
1341 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1342
1343 /// \pre Return a non-unique reference to the type for a dependently-sized
1344 /// vector of the specified element type.
1345 ///
1346 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1347 /// point.
1348 QualType getDependentSizedExtVectorType(QualType VectorType,
1349 Expr *SizeExpr,
1350 SourceLocation AttrLoc) const;
1351
1352 QualType getDependentAddressSpaceType(QualType PointeeType,
1353 Expr *AddrSpaceExpr,
1354 SourceLocation AttrLoc) const;
1355
1356 /// Return a K&R style C function type like 'int()'.
1357 QualType getFunctionNoProtoType(QualType ResultTy,
1358 const FunctionType::ExtInfo &Info) const;
1359
1360 QualType getFunctionNoProtoType(QualType ResultTy) const {
1361 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1362 }
1363
1364 /// Return a normal function type with a typed argument list.
1365 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1366 const FunctionProtoType::ExtProtoInfo &EPI) const {
1367 return getFunctionTypeInternal(ResultTy, Args, EPI, false);
1368 }
1369
1370 QualType adjustStringLiteralBaseType(QualType StrLTy) const;
1371
1372private:
1373 /// Return a normal function type with a typed argument list.
1374 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1375 const FunctionProtoType::ExtProtoInfo &EPI,
1376 bool OnlyWantCanonical) const;
1377
1378public:
1379 /// Return the unique reference to the type for the specified type
1380 /// declaration.
1381 QualType getTypeDeclType(const TypeDecl *Decl,
1382 const TypeDecl *PrevDecl = nullptr) const {
1383 assert(Decl && "Passed null for Decl param");
1384 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1385
1386 if (PrevDecl) {
1387 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1388 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1389 return QualType(PrevDecl->TypeForDecl, 0);
1390 }
1391
1392 return getTypeDeclTypeSlow(Decl);
1393 }
1394
1395 /// Return the unique reference to the type for the specified
1396 /// typedef-name decl.
1397 QualType getTypedefType(const TypedefNameDecl *Decl,
1398 QualType Canon = QualType()) const;
1399
1400 QualType getRecordType(const RecordDecl *Decl) const;
1401
1402 QualType getEnumType(const EnumDecl *Decl) const;
1403
1404 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1405
1406 QualType getAttributedType(AttributedType::Kind attrKind,
1407 QualType modifiedType,
1408 QualType equivalentType);
1409
1410 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1411 QualType Replacement) const;
1412 QualType getSubstTemplateTypeParmPackType(
1413 const TemplateTypeParmType *Replaced,
1414 const TemplateArgument &ArgPack);
1415
1416 QualType
1417 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1418 bool ParameterPack,
1419 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1420
1421 QualType getTemplateSpecializationType(TemplateName T,
1422 ArrayRef<TemplateArgument> Args,
1423 QualType Canon = QualType()) const;
1424
1425 QualType
1426 getCanonicalTemplateSpecializationType(TemplateName T,
1427 ArrayRef<TemplateArgument> Args) const;
1428
1429 QualType getTemplateSpecializationType(TemplateName T,
1430 const TemplateArgumentListInfo &Args,
1431 QualType Canon = QualType()) const;
1432
1433 TypeSourceInfo *
1434 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1435 const TemplateArgumentListInfo &Args,
1436 QualType Canon = QualType()) const;
1437
1438 QualType getParenType(QualType NamedType) const;
1439
1440 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1441 NestedNameSpecifier *NNS, QualType NamedType,
1442 TagDecl *OwnedTagDecl = nullptr) const;
1443 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1444 NestedNameSpecifier *NNS,
1445 const IdentifierInfo *Name,
1446 QualType Canon = QualType()) const;
1447
1448 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1449 NestedNameSpecifier *NNS,
1450 const IdentifierInfo *Name,
1451 const TemplateArgumentListInfo &Args) const;
1452 QualType getDependentTemplateSpecializationType(
1453 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1454 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1455
1456 TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
1457
1458 /// Get a template argument list with one argument per template parameter
1459 /// in a template parameter list, such as for the injected class name of
1460 /// a class template.
1461 void getInjectedTemplateArgs(const TemplateParameterList *Params,
1462 SmallVectorImpl<TemplateArgument> &Args);
1463
1464 QualType getPackExpansionType(QualType Pattern,
1465 Optional<unsigned> NumExpansions);
1466
1467 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1468 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1469
1470 /// Legacy interface: cannot provide type arguments or __kindof.
1471 QualType getObjCObjectType(QualType Base,
1472 ObjCProtocolDecl * const *Protocols,
1473 unsigned NumProtocols) const;
1474
1475 QualType getObjCObjectType(QualType Base,
1476 ArrayRef<QualType> typeArgs,
1477 ArrayRef<ObjCProtocolDecl *> protocols,
1478 bool isKindOf) const;
1479
1480 QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1481 ArrayRef<ObjCProtocolDecl *> protocols,
1482 QualType Canonical = QualType()) const;
1483
1484 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1485
1486 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1487 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1488 /// of protocols.
1489 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1490 ObjCInterfaceDecl *IDecl);
1491
1492 /// Return a ObjCObjectPointerType type for the given ObjCObjectType.
1493 QualType getObjCObjectPointerType(QualType OIT) const;
1494
1495 /// GCC extension.
1496 QualType getTypeOfExprType(Expr *e) const;
1497 QualType getTypeOfType(QualType t) const;
1498
1499 /// C++11 decltype.
1500 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1501
1502 /// Unary type transforms
1503 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1504 UnaryTransformType::UTTKind UKind) const;
1505
1506 /// C++11 deduced auto type.
1507 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1508 bool IsDependent) const;
1509
1510 /// C++11 deduction pattern for 'auto' type.
1511 QualType getAutoDeductType() const;
1512
1513 /// C++11 deduction pattern for 'auto &&' type.
1514 QualType getAutoRRefDeductType() const;
1515
1516 /// C++17 deduced class template specialization type.
1517 QualType getDeducedTemplateSpecializationType(TemplateName Template,
1518 QualType DeducedType,
1519 bool IsDependent) const;
1520
1521 /// Return the unique reference to the type for the specified TagDecl
1522 /// (struct/union/class/enum) decl.
1523 QualType getTagDeclType(const TagDecl *Decl) const;
1524
1525 /// Return the unique type for "size_t" (C99 7.17), defined in
1526 /// <stddef.h>.
1527 ///
1528 /// The sizeof operator requires this (C99 6.5.3.4p4).
1529 CanQualType getSizeType() const;
1530
1531 /// Return the unique signed counterpart of
1532 /// the integer type corresponding to size_t.
1533 CanQualType getSignedSizeType() const;
1534
1535 /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1536 /// <stdint.h>.
1537 CanQualType getIntMaxType() const;
1538
1539 /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1540 /// <stdint.h>.
1541 CanQualType getUIntMaxType() const;
1542
1543 /// Return the unique wchar_t type available in C++ (and available as
1544 /// __wchar_t as a Microsoft extension).
1545 QualType getWCharType() const { return WCharTy; }
1546
1547 /// Return the type of wide characters. In C++, this returns the
1548 /// unique wchar_t type. In C99, this returns a type compatible with the type
1549 /// defined in <stddef.h> as defined by the target.
1550 QualType getWideCharType() const { return WideCharTy; }
1551
1552 /// Return the type of "signed wchar_t".
1553 ///
1554 /// Used when in C++, as a GCC extension.
1555 QualType getSignedWCharType() const;
1556
1557 /// Return the type of "unsigned wchar_t".
1558 ///
1559 /// Used when in C++, as a GCC extension.
1560 QualType getUnsignedWCharType() const;
1561
1562 /// In C99, this returns a type compatible with the type
1563 /// defined in <stddef.h> as defined by the target.
1564 QualType getWIntType() const { return WIntTy; }
1565
1566 /// Return a type compatible with "intptr_t" (C99 7.18.1.4),
1567 /// as defined by the target.
1568 QualType getIntPtrType() const;
1569
1570 /// Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1571 /// as defined by the target.
1572 QualType getUIntPtrType() const;
1573
1574 /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1575 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1576 QualType getPointerDiffType() const;
1577
1578 /// Return the unique unsigned counterpart of "ptrdiff_t"
1579 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
1580 /// in the definition of %tu format specifier.
1581 QualType getUnsignedPointerDiffType() const;
1582
1583 /// Return the unique type for "pid_t" defined in
1584 /// <sys/types.h>. We need this to compute the correct type for vfork().
1585 QualType getProcessIDType() const;
1586
1587 /// Return the C structure type used to represent constant CFStrings.
1588 QualType getCFConstantStringType() const;
1589
1590 /// Returns the C struct type for objc_super
1591 QualType getObjCSuperType() const;
1592 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1593
1594 /// Get the structure type used to representation CFStrings, or NULL
1595 /// if it hasn't yet been built.
1596 QualType getRawCFConstantStringType() const {
1597 if (CFConstantStringTypeDecl)
1598 return getTypedefType(CFConstantStringTypeDecl);
1599 return QualType();
1600 }
1601 void setCFConstantStringType(QualType T);
1602 TypedefDecl *getCFConstantStringDecl() const;
1603 RecordDecl *getCFConstantStringTagDecl() const;
1604
1605 // This setter/getter represents the ObjC type for an NSConstantString.
1606 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1607 QualType getObjCConstantStringInterface() const {
1608 return ObjCConstantStringType;
1609 }
1610
1611 QualType getObjCNSStringType() const {
1612 return ObjCNSStringType;
1613 }
1614
1615 void setObjCNSStringType(QualType T) {
1616 ObjCNSStringType = T;
1617 }
1618
1619 /// Retrieve the type that \c id has been defined to, which may be
1620 /// different from the built-in \c id if \c id has been typedef'd.
1621 QualType getObjCIdRedefinitionType() const {
1622 if (ObjCIdRedefinitionType.isNull())
1623 return getObjCIdType();
1624 return ObjCIdRedefinitionType;
1625 }
1626
1627 /// Set the user-written type that redefines \c id.
1628 void setObjCIdRedefinitionType(QualType RedefType) {
1629 ObjCIdRedefinitionType = RedefType;
1630 }
1631
1632 /// Retrieve the type that \c Class has been defined to, which may be
1633 /// different from the built-in \c Class if \c Class has been typedef'd.
1634 QualType getObjCClassRedefinitionType() const {
1635 if (ObjCClassRedefinitionType.isNull())
1636 return getObjCClassType();
1637 return ObjCClassRedefinitionType;
1638 }
1639
1640 /// Set the user-written type that redefines 'SEL'.
1641 void setObjCClassRedefinitionType(QualType RedefType) {
1642 ObjCClassRedefinitionType = RedefType;
1643 }
1644
1645 /// Retrieve the type that 'SEL' has been defined to, which may be
1646 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1647 QualType getObjCSelRedefinitionType() const {
1648 if (ObjCSelRedefinitionType.isNull())
1649 return getObjCSelType();
1650 return ObjCSelRedefinitionType;
1651 }
1652
1653 /// Set the user-written type that redefines 'SEL'.
1654 void setObjCSelRedefinitionType(QualType RedefType) {
1655 ObjCSelRedefinitionType = RedefType;
1656 }
1657
1658 /// Retrieve the identifier 'NSObject'.
1659 IdentifierInfo *getNSObjectName() {
1660 if (!NSObjectName) {
1661 NSObjectName = &Idents.get("NSObject");
1662 }
1663
1664 return NSObjectName;
1665 }
1666
1667 /// Retrieve the identifier 'NSCopying'.
1668 IdentifierInfo *getNSCopyingName() {
1669 if (!NSCopyingName) {
1670 NSCopyingName = &Idents.get("NSCopying");
1671 }
1672
1673 return NSCopyingName;
1674 }
1675
1676 CanQualType getNSUIntegerType() const {
1677 assert(Target && "Expected target to be initialized");
1678 const llvm::Triple &T = Target->getTriple();
1679 // Windows is LLP64 rather than LP64
1680 if (T.isOSWindows() && T.isArch64Bit())
1681 return UnsignedLongLongTy;
1682 return UnsignedLongTy;
1683 }
1684
1685 CanQualType getNSIntegerType() const {
1686 assert(Target && "Expected target to be initialized");
1687 const llvm::Triple &T = Target->getTriple();
1688 // Windows is LLP64 rather than LP64
1689 if (T.isOSWindows() && T.isArch64Bit())
1690 return LongLongTy;
1691 return LongTy;
1692 }
1693
1694 /// Retrieve the identifier 'bool'.
1695 IdentifierInfo *getBoolName() const {
1696 if (!BoolName)
1697 BoolName = &Idents.get("bool");
1698 return BoolName;
1699 }
1700
1701 IdentifierInfo *getMakeIntegerSeqName() const {
1702 if (!MakeIntegerSeqName)
1703 MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1704 return MakeIntegerSeqName;
1705 }
1706
1707 IdentifierInfo *getTypePackElementName() const {
1708 if (!TypePackElementName)
1709 TypePackElementName = &Idents.get("__type_pack_element");
1710 return TypePackElementName;
1711 }
1712
1713 /// Retrieve the Objective-C "instancetype" type, if already known;
1714 /// otherwise, returns a NULL type;
1715 QualType getObjCInstanceType() {
1716 return getTypeDeclType(getObjCInstanceTypeDecl());
1717 }
1718
1719 /// Retrieve the typedef declaration corresponding to the Objective-C
1720 /// "instancetype" type.
1721 TypedefDecl *getObjCInstanceTypeDecl();
1722
1723 /// Set the type for the C FILE type.
1724 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1725
1726 /// Retrieve the C FILE type.
1727 QualType getFILEType() const {
1728 if (FILEDecl)
1729 return getTypeDeclType(FILEDecl);
1730 return QualType();
1731 }
1732
1733 /// Set the type for the C jmp_buf type.
1734 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1735 this->jmp_bufDecl = jmp_bufDecl;
1736 }
1737
1738 /// Retrieve the C jmp_buf type.
1739 QualType getjmp_bufType() const {
1740 if (jmp_bufDecl)
1741 return getTypeDeclType(jmp_bufDecl);
1742 return QualType();
1743 }
1744
1745 /// Set the type for the C sigjmp_buf type.
1746 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1747 this->sigjmp_bufDecl = sigjmp_bufDecl;
1748 }
1749
1750 /// Retrieve the C sigjmp_buf type.
1751 QualType getsigjmp_bufType() const {
1752 if (sigjmp_bufDecl)
1753 return getTypeDeclType(sigjmp_bufDecl);
1754 return QualType();
1755 }
1756
1757 /// Set the type for the C ucontext_t type.
1758 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1759 this->ucontext_tDecl = ucontext_tDecl;
1760 }
1761
1762 /// Retrieve the C ucontext_t type.
1763 QualType getucontext_tType() const {
1764 if (ucontext_tDecl)
1765 return getTypeDeclType(ucontext_tDecl);
1766 return QualType();
1767 }
1768
1769 /// The result type of logical operations, '<', '>', '!=', etc.
1770 QualType getLogicalOperationType() const {
1771 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1772 }
1773
1774 /// Emit the Objective-CC type encoding for the given type \p T into
1775 /// \p S.
1776 ///
1777 /// If \p Field is specified then record field names are also encoded.
1778 void getObjCEncodingForType(QualType T, std::string &S,
1779 const FieldDecl *Field=nullptr,
1780 QualType *NotEncodedT=nullptr) const;
1781
1782 /// Emit the Objective-C property type encoding for the given
1783 /// type \p T into \p S.
1784 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1785
1786 void getLegacyIntegralTypeEncoding(QualType &t) const;
1787
1788 /// Put the string version of the type qualifiers \p QT into \p S.
1789 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1790 std::string &S) const;
1791
1792 /// Emit the encoded type for the function \p Decl into \p S.
1793 ///
1794 /// This is in the same format as Objective-C method encodings.
1795 ///
1796 /// \returns true if an error occurred (e.g., because one of the parameter
1797 /// types is incomplete), false otherwise.
1798 std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
1799
1800 /// Emit the encoded type for the method declaration \p Decl into
1801 /// \p S.
1802 std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1803 bool Extended = false) const;
1804
1805 /// Return the encoded type for this block declaration.
1806 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1807
1808 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1809 /// this method declaration. If non-NULL, Container must be either
1810 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1811 /// only be NULL when getting encodings for protocol properties.
1812 std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1813 const Decl *Container) const;
1814
1815 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1816 ObjCProtocolDecl *rProto) const;
1817
1818 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1819 const ObjCPropertyDecl *PD,
1820 const Decl *Container) const;
1821
1822 /// Return the size of type \p T for Objective-C encoding purpose,
1823 /// in characters.
1824 CharUnits getObjCEncodingTypeSize(QualType T) const;
1825
1826 /// Retrieve the typedef corresponding to the predefined \c id type
1827 /// in Objective-C.
1828 TypedefDecl *getObjCIdDecl() const;
1829
1830 /// Represents the Objective-CC \c id type.
1831 ///
1832 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1833 /// pointer type, a pointer to a struct.
1834 QualType getObjCIdType() const {
1835 return getTypeDeclType(getObjCIdDecl());
1836 }
1837
1838 /// Retrieve the typedef corresponding to the predefined 'SEL' type
1839 /// in Objective-C.
1840 TypedefDecl *getObjCSelDecl() const;
1841
1842 /// Retrieve the type that corresponds to the predefined Objective-C
1843 /// 'SEL' type.
1844 QualType getObjCSelType() const {
1845 return getTypeDeclType(getObjCSelDecl());
1846 }
1847
1848 /// Retrieve the typedef declaration corresponding to the predefined
1849 /// Objective-C 'Class' type.
1850 TypedefDecl *getObjCClassDecl() const;
1851
1852 /// Represents the Objective-C \c Class type.
1853 ///
1854 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1855 /// pointer type, a pointer to a struct.
1856 QualType getObjCClassType() const {
1857 return getTypeDeclType(getObjCClassDecl());
1858 }
1859
1860 /// Retrieve the Objective-C class declaration corresponding to
1861 /// the predefined \c Protocol class.
1862 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1863
1864 /// Retrieve declaration of 'BOOL' typedef
1865 TypedefDecl *getBOOLDecl() const {
1866 return BOOLDecl;
1867 }
1868
1869 /// Save declaration of 'BOOL' typedef
1870 void setBOOLDecl(TypedefDecl *TD) {
1871 BOOLDecl = TD;
1872 }
1873
1874 /// type of 'BOOL' type.
1875 QualType getBOOLType() const {
1876 return getTypeDeclType(getBOOLDecl());
1877 }
1878
1879 /// Retrieve the type of the Objective-C \c Protocol class.
1880 QualType getObjCProtoType() const {
1881 return getObjCInterfaceType(getObjCProtocolDecl());
1882 }
1883
1884 /// Retrieve the C type declaration corresponding to the predefined
1885 /// \c __builtin_va_list type.
1886 TypedefDecl *getBuiltinVaListDecl() const;
1887
1888 /// Retrieve the type of the \c __builtin_va_list type.
1889 QualType getBuiltinVaListType() const {
1890 return getTypeDeclType(getBuiltinVaListDecl());
1891 }
1892
1893 /// Retrieve the C type declaration corresponding to the predefined
1894 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1895 /// for some targets.
1896 Decl *getVaListTagDecl() const;
1897
1898 /// Retrieve the C type declaration corresponding to the predefined
1899 /// \c __builtin_ms_va_list type.
1900 TypedefDecl *getBuiltinMSVaListDecl() const;
1901
1902 /// Retrieve the type of the \c __builtin_ms_va_list type.
1903 QualType getBuiltinMSVaListType() const {
1904 return getTypeDeclType(getBuiltinMSVaListDecl());
1905 }
1906
1907 /// Return whether a declaration to a builtin is allowed to be
1908 /// overloaded/redeclared.
1909 bool canBuiltinBeRedeclared(const FunctionDecl *) const;
1910
1911 /// Return a type with additional \c const, \c volatile, or
1912 /// \c restrict qualifiers.
1913 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1914 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1915 }
1916
1917 /// Un-split a SplitQualType.
1918 QualType getQualifiedType(SplitQualType split) const {
1919 return getQualifiedType(split.Ty, split.Quals);
1920 }
1921
1922 /// Return a type with additional qualifiers.
1923 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1924 if (!Qs.hasNonFastQualifiers())
1925 return T.withFastQualifiers(Qs.getFastQualifiers());
1926 QualifierCollector Qc(Qs);
1927 const Type *Ptr = Qc.strip(T);
1928 return getExtQualType(Ptr, Qc);
1929 }
1930
1931 /// Return a type with additional qualifiers.
1932 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1933 if (!Qs.hasNonFastQualifiers())
1934 return QualType(T, Qs.getFastQualifiers());
1935 return getExtQualType(T, Qs);
1936 }
1937
1938 /// Return a type with the given lifetime qualifier.
1939 ///
1940 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1941 QualType getLifetimeQualifiedType(QualType type,
1942 Qualifiers::ObjCLifetime lifetime) {
1943 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1944 assert(lifetime != Qualifiers::OCL_None);
1945
1946 Qualifiers qs;
1947 qs.addObjCLifetime(lifetime);
1948 return getQualifiedType(type, qs);
1949 }
1950
1951 /// getUnqualifiedObjCPointerType - Returns version of
1952 /// Objective-C pointer type with lifetime qualifier removed.
1953 QualType getUnqualifiedObjCPointerType(QualType type) const {
1954 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1955 !type.getQualifiers().hasObjCLifetime())
1956 return type;
1957 Qualifiers Qs = type.getQualifiers();
1958 Qs.removeObjCLifetime();
1959 return getQualifiedType(type.getUnqualifiedType(), Qs);
1960 }
1961
1962 unsigned char getFixedPointScale(QualType Ty) const;
1963 unsigned char getFixedPointIBits(QualType Ty) const;
1964
1965 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1966 SourceLocation NameLoc) const;
1967
1968 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1969 UnresolvedSetIterator End) const;
1970
1971 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1972 bool TemplateKeyword,
1973 TemplateDecl *Template) const;
1974
1975 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1976 const IdentifierInfo *Name) const;
1977 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1978 OverloadedOperatorKind Operator) const;
1979 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1980 TemplateName replacement) const;
1981 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1982 const TemplateArgument &ArgPack) const;
1983
1984 enum GetBuiltinTypeError {
1985 /// No error
1986 GE_None,
1987
1988 /// Missing a type from <stdio.h>
1989 GE_Missing_stdio,
1990
1991 /// Missing a type from <setjmp.h>
1992 GE_Missing_setjmp,
1993
1994 /// Missing a type from <ucontext.h>
1995 GE_Missing_ucontext
1996 };
1997
1998 /// Return the type for the specified builtin.
1999 ///
2000 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
2001 /// arguments to the builtin that are required to be integer constant
2002 /// expressions.
2003 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
2004 unsigned *IntegerConstantArgs = nullptr) const;
2005
2006 /// Types and expressions required to build C++2a three-way comparisons
2007 /// using operator<=>, including the values return by builtin <=> operators.
2008 ComparisonCategories CompCategories;
2009
2010private:
2011 CanQualType getFromTargetType(unsigned Type) const;
2012 TypeInfo getTypeInfoImpl(const Type *T) const;
2013
2014 //===--------------------------------------------------------------------===//
2015 // Type Predicates.
2016 //===--------------------------------------------------------------------===//
2017
2018public:
2019 /// Return one of the GCNone, Weak or Strong Objective-C garbage
2020 /// collection attributes.
2021 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
2022
2023 /// Return true if the given vector types are of the same unqualified
2024 /// type or if they are equivalent to the same GCC vector type.
2025 ///
2026 /// \note This ignores whether they are target-specific (AltiVec or Neon)
2027 /// types.
2028 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
2029
2030 /// Return true if this is an \c NSObject object with its \c NSObject
2031 /// attribute set.
2032 static bool isObjCNSObjectType(QualType Ty) {
2033 return Ty->isObjCNSObjectType();
2034 }
2035
2036 //===--------------------------------------------------------------------===//
2037 // Type Sizing and Analysis
2038 //===--------------------------------------------------------------------===//
2039
2040 /// Return the APFloat 'semantics' for the specified scalar floating
2041 /// point type.
2042 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
2043
2044 /// Get the size and alignment of the specified complete type in bits.
2045 TypeInfo getTypeInfo(const Type *T) const;
2046 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
2047
2048 /// Get default simd alignment of the specified complete type in bits.
2049 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
2050
2051 /// Return the size of the specified (complete) type \p T, in bits.
2052 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
2053 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
2054
2055 /// Return the size of the character type, in bits.
2056 uint64_t getCharWidth() const {
2057 return getTypeSize(CharTy);
2058 }
2059
2060 /// Convert a size in bits to a size in characters.
2061 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
2062
2063 /// Convert a size in characters to a size in bits.
2064 int64_t toBits(CharUnits CharSize) const;
2065
2066 /// Return the size of the specified (complete) type \p T, in
2067 /// characters.
2068 CharUnits getTypeSizeInChars(QualType T) const;
2069 CharUnits getTypeSizeInChars(const Type *T) const;
2070
2071 /// Return the ABI-specified alignment of a (complete) type \p T, in
2072 /// bits.
2073 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
2074 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
2075
2076 /// Return the ABI-specified natural alignment of a (complete) type \p T,
2077 /// before alignment adjustments, in bits.
2078 ///
2079 /// This alignment is curently used only by ARM and AArch64 when passing
2080 /// arguments of a composite type.
2081 unsigned getTypeUnadjustedAlign(QualType T) const {
2082 return getTypeUnadjustedAlign(T.getTypePtr());
2083 }
2084 unsigned getTypeUnadjustedAlign(const Type *T) const;
2085
2086 /// Return the ABI-specified alignment of a type, in bits, or 0 if
2087 /// the type is incomplete and we cannot determine the alignment (for
2088 /// example, from alignment attributes).
2089 unsigned getTypeAlignIfKnown(QualType T) const;
2090
2091 /// Return the ABI-specified alignment of a (complete) type \p T, in
2092 /// characters.
2093 CharUnits getTypeAlignInChars(QualType T) const;
2094 CharUnits getTypeAlignInChars(const Type *T) const;
2095
2096 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
2097 /// in characters, before alignment adjustments. This method does not work on
2098 /// incomplete types.
2099 CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
2100 CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
2101
2102 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
2103 // type is a record, its data size is returned.
2104 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
2105
2106 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
2107 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
2108
2109 /// Determine if the alignment the type has was required using an
2110 /// alignment attribute.
2111 bool isAlignmentRequired(const Type *T) const;
2112 bool isAlignmentRequired(QualType T) const;
2113
2114 /// Return the "preferred" alignment of the specified type \p T for
2115 /// the current target, in bits.
2116 ///
2117 /// This can be different than the ABI alignment in cases where it is
2118 /// beneficial for performance to overalign a data type.
2119 unsigned getPreferredTypeAlign(const Type *T) const;
2120
2121 /// Return the default alignment for __attribute__((aligned)) on
2122 /// this target, to be used if no alignment value is specified.
2123 unsigned getTargetDefaultAlignForAttributeAligned() const;
2124
2125 /// Return the alignment in bits that should be given to a
2126 /// global variable with type \p T.
2127 unsigned getAlignOfGlobalVar(QualType T) const;
2128
2129 /// Return the alignment in characters that should be given to a
2130 /// global variable with type \p T.
2131 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
2132
2133 /// Return a conservative estimate of the alignment of the specified
2134 /// decl \p D.
2135 ///
2136 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
2137 /// alignment.
2138 ///
2139 /// If \p ForAlignof, references are treated like their underlying type
2140 /// and large arrays don't get any special treatment. If not \p ForAlignof
2141 /// it computes the value expected by CodeGen: references are treated like
2142 /// pointers and large arrays get extra alignment.
2143 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2144
2145 /// Get or compute information about the layout of the specified
2146 /// record (struct/union/class) \p D, which indicates its size and field
2147 /// position information.
2148 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2149
2150 /// Get or compute information about the layout of the specified
2151 /// Objective-C interface.
2152 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2153 const;
2154
2155 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2156 bool Simple = false) const;
2157
2158 /// Get or compute information about the layout of the specified
2159 /// Objective-C implementation.
2160 ///
2161 /// This may differ from the interface if synthesized ivars are present.
2162 const ASTRecordLayout &
2163 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2164
2165 /// Get our current best idea for the key function of the
2166 /// given record decl, or nullptr if there isn't one.
2167 ///
2168 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2169 /// ...the first non-pure virtual function that is not inline at the
2170 /// point of class definition.
2171 ///
2172 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
2173 /// virtual functions that are defined 'inline', which means that
2174 /// the result of this computation can change.
2175 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2176
2177 /// Observe that the given method cannot be a key function.
2178 /// Checks the key-function cache for the method's class and clears it
2179 /// if matches the given declaration.
2180 ///
2181 /// This is used in ABIs where out-of-line definitions marked
2182 /// inline are not considered to be key functions.
2183 ///
2184 /// \param method should be the declaration from the class definition
2185 void setNonKeyFunction(const CXXMethodDecl *method);
2186
2187 /// Loading virtual member pointers using the virtual inheritance model
2188 /// always results in an adjustment using the vbtable even if the index is
2189 /// zero.
2190 ///
2191 /// This is usually OK because the first slot in the vbtable points
2192 /// backwards to the top of the MDC. However, the MDC might be reusing a
2193 /// vbptr from an nv-base. In this case, the first slot in the vbtable
2194 /// points to the start of the nv-base which introduced the vbptr and *not*
2195 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
2196 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2197
2198 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2199 uint64_t getFieldOffset(const ValueDecl *FD) const;
2200
2201 /// Get the offset of an ObjCIvarDecl in bits.
2202 uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2203 const ObjCImplementationDecl *ID,
2204 const ObjCIvarDecl *Ivar) const;
2205
2206 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2207
2208 VTableContextBase *getVTableContext();
2209
2210 MangleContext *createMangleContext();
2211
2212 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2213 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2214
2215 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2216 void CollectInheritedProtocols(const Decl *CDecl,
2217 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2218
2219 /// Return true if the specified type has unique object representations
2220 /// according to (C++17 [meta.unary.prop]p9)
2221 bool hasUniqueObjectRepresentations(QualType Ty) const;
2222
2223 //===--------------------------------------------------------------------===//
2224 // Type Operators
2225 //===--------------------------------------------------------------------===//
2226
2227 /// Return the canonical (structural) type corresponding to the
2228 /// specified potentially non-canonical type \p T.
2229 ///
2230 /// The non-canonical version of a type may have many "decorated" versions of
2231 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
2232 /// returned type is guaranteed to be free of any of these, allowing two
2233 /// canonical types to be compared for exact equality with a simple pointer
2234 /// comparison.
2235 CanQualType getCanonicalType(QualType T) const {
2236 return CanQualType::CreateUnsafe(T.getCanonicalType());
2237 }
2238
2239 const Type *getCanonicalType(const Type *T) const {
2240 return T->getCanonicalTypeInternal().getTypePtr();
2241 }
2242
2243 /// Return the canonical parameter type corresponding to the specific
2244 /// potentially non-canonical one.
2245 ///
2246 /// Qualifiers are stripped off, functions are turned into function
2247 /// pointers, and arrays decay one level into pointers.
2248 CanQualType getCanonicalParamType(QualType T) const;
2249
2250 /// Determine whether the given types \p T1 and \p T2 are equivalent.
2251 bool hasSameType(QualType T1, QualType T2) const {
2252 return getCanonicalType(T1) == getCanonicalType(T2);
2253 }
2254 bool hasSameType(const Type *T1, const Type *T2) const {
2255 return getCanonicalType(T1) == getCanonicalType(T2);
2256 }
2257
2258 /// Return this type as a completely-unqualified array type,
2259 /// capturing the qualifiers in \p Quals.
2260 ///
2261 /// This will remove the minimal amount of sugaring from the types, similar
2262 /// to the behavior of QualType::getUnqualifiedType().
2263 ///
2264 /// \param T is the qualified type, which may be an ArrayType
2265 ///
2266 /// \param Quals will receive the full set of qualifiers that were
2267 /// applied to the array.
2268 ///
2269 /// \returns if this is an array type, the completely unqualified array type
2270 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2271 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2272
2273 /// Determine whether the given types are equivalent after
2274 /// cvr-qualifiers have been removed.
2275 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2276 return getCanonicalType(T1).getTypePtr() ==
2277 getCanonicalType(T2).getTypePtr();
2278 }
2279
2280 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2281 bool IsParam) const {
2282 auto SubTnullability = SubT->getNullability(*this);
2283 auto SuperTnullability = SuperT->getNullability(*this);
2284 if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
2285 // Neither has nullability; return true
2286 if (!SubTnullability)
2287 return true;
2288 // Both have nullability qualifier.
2289 if (*SubTnullability == *SuperTnullability ||
2290 *SubTnullability == NullabilityKind::Unspecified ||
2291 *SuperTnullability == NullabilityKind::Unspecified)
2292 return true;
2293
2294 if (IsParam) {
2295 // Ok for the superclass method parameter to be "nonnull" and the subclass
2296 // method parameter to be "nullable"
2297 return (*SuperTnullability == NullabilityKind::NonNull &&
2298 *SubTnullability == NullabilityKind::Nullable);
2299 }
2300 else {
2301 // For the return type, it's okay for the superclass method to specify
2302 // "nullable" and the subclass method specify "nonnull"
2303 return (*SuperTnullability == NullabilityKind::Nullable &&
2304 *SubTnullability == NullabilityKind::NonNull);
2305 }
2306 }
2307 return true;
2308 }
2309
2310 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2311 const ObjCMethodDecl *MethodImp);
2312
2313 bool UnwrapSimilarTypes(QualType &T1, QualType &T2);
2314 bool UnwrapSimilarArrayTypes(QualType &T1, QualType &T2);
2315
2316 /// Determine if two types are similar, according to the C++ rules. That is,
2317 /// determine if they are the same other than qualifiers on the initial
2318 /// sequence of pointer / pointer-to-member / array (and in Clang, object
2319 /// pointer) types and their element types.
2320 ///
2321 /// Clang offers a number of qualifiers in addition to the C++ qualifiers;
2322 /// those qualifiers are also ignored in the 'similarity' check.
2323 bool hasSimilarType(QualType T1, QualType T2);
2324
2325 /// Determine if two types are similar, ignoring only CVR qualifiers.
2326 bool hasCvrSimilarType(QualType T1, QualType T2);
2327
2328 /// Retrieves the "canonical" nested name specifier for a
2329 /// given nested name specifier.
2330 ///
2331 /// The canonical nested name specifier is a nested name specifier
2332 /// that uniquely identifies a type or namespace within the type
2333 /// system. For example, given:
2334 ///
2335 /// \code
2336 /// namespace N {
2337 /// struct S {
2338 /// template<typename T> struct X { typename T* type; };
2339 /// };
2340 /// }
2341 ///
2342 /// template<typename T> struct Y {
2343 /// typename N::S::X<T>::type member;
2344 /// };
2345 /// \endcode
2346 ///
2347 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2348 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2349 /// by declarations in the type system and the canonical type for
2350 /// the template type parameter 'T' is template-param-0-0.
2351 NestedNameSpecifier *
2352 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2353
2354 /// Retrieves the default calling convention for the current target.
2355 CallingConv getDefaultCallingConvention(bool IsVariadic,
2356 bool IsCXXMethod) const;
2357
2358 /// Retrieves the "canonical" template name that refers to a
2359 /// given template.
2360 ///
2361 /// The canonical template name is the simplest expression that can
2362 /// be used to refer to a given template. For most templates, this
2363 /// expression is just the template declaration itself. For example,
2364 /// the template std::vector can be referred to via a variety of
2365 /// names---std::vector, \::std::vector, vector (if vector is in
2366 /// scope), etc.---but all of these names map down to the same
2367 /// TemplateDecl, which is used to form the canonical template name.
2368 ///
2369 /// Dependent template names are more interesting. Here, the
2370 /// template name could be something like T::template apply or
2371 /// std::allocator<T>::template rebind, where the nested name
2372 /// specifier itself is dependent. In this case, the canonical
2373 /// template name uses the shortest form of the dependent
2374 /// nested-name-specifier, which itself contains all canonical
2375 /// types, values, and templates.
2376 TemplateName getCanonicalTemplateName(TemplateName Name) const;
2377
2378 /// Determine whether the given template names refer to the same
2379 /// template.
2380 bool hasSameTemplateName(TemplateName X, TemplateName Y);
2381
2382 /// Retrieve the "canonical" template argument.
2383 ///
2384 /// The canonical template argument is the simplest template argument
2385 /// (which may be a type, value, expression, or declaration) that
2386 /// expresses the value of the argument.
2387 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2388 const;
2389
2390 /// Type Query functions. If the type is an instance of the specified class,
2391 /// return the Type pointer for the underlying maximally pretty type. This
2392 /// is a member of ASTContext because this may need to do some amount of
2393 /// canonicalization, e.g. to move type qualifiers into the element type.
2394 const ArrayType *getAsArrayType(QualType T) const;
2395 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2396 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2397 }
2398 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2399 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2400 }
2401 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2402 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2403 }
2404 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2405 const {
2406 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2407 }
2408
2409 /// Return the innermost element type of an array type.
2410 ///
2411 /// For example, will return "int" for int[m][n]
2412 QualType getBaseElementType(const ArrayType *VAT) const;
2413
2414 /// Return the innermost element type of a type (which needn't
2415 /// actually be an array type).
2416 QualType getBaseElementType(QualType QT) const;
2417
2418 /// Return number of constant array elements.
2419 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2420
2421 /// Perform adjustment on the parameter type of a function.
2422 ///
2423 /// This routine adjusts the given parameter type @p T to the actual
2424 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2425 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2426 QualType getAdjustedParameterType(QualType T) const;
2427
2428 /// Retrieve the parameter type as adjusted for use in the signature
2429 /// of a function, decaying array and function types and removing top-level
2430 /// cv-qualifiers.
2431 QualType getSignatureParameterType(QualType T) const;
2432
2433 QualType getExceptionObjectType(QualType T) const;
2434
2435 /// Return the properly qualified result of decaying the specified
2436 /// array type to a pointer.
2437 ///
2438 /// This operation is non-trivial when handling typedefs etc. The canonical
2439 /// type of \p T must be an array type, this returns a pointer to a properly
2440 /// qualified element of the array.
2441 ///
2442 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2443 QualType getArrayDecayedType(QualType T) const;
2444
2445 /// Return the type that \p PromotableType will promote to: C99
2446 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2447 QualType getPromotedIntegerType(QualType PromotableType) const;
2448
2449 /// Recurses in pointer/array types until it finds an Objective-C
2450 /// retainable type and returns its ownership.
2451 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2452
2453 /// Whether this is a promotable bitfield reference according
2454 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2455 ///
2456 /// \returns the type this bit-field will promote to, or NULL if no
2457 /// promotion occurs.
2458 QualType isPromotableBitField(Expr *E) const;
2459
2460 /// Return the highest ranked integer type, see C99 6.3.1.8p1.
2461 ///
2462 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2463 /// \p LHS < \p RHS, return -1.
2464 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2465
2466 /// Compare the rank of the two specified floating point types,
2467 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2468 ///
2469 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2470 /// \p LHS < \p RHS, return -1.
2471 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2472
2473 /// Return a real floating point or a complex type (based on
2474 /// \p typeDomain/\p typeSize).
2475 ///
2476 /// \param typeDomain a real floating point or complex type.
2477 /// \param typeSize a real floating point or complex type.
2478 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2479 QualType typeDomain) const;
2480
2481 unsigned getTargetAddressSpace(QualType T) const {
2482 return getTargetAddressSpace(T.getQualifiers());
2483 }
2484
2485 unsigned getTargetAddressSpace(Qualifiers Q) const {
2486 return getTargetAddressSpace(Q.getAddressSpace());
2487 }
2488
2489 unsigned getTargetAddressSpace(LangAS AS) const;
2490
2491 /// Get target-dependent integer value for null pointer which is used for
2492 /// constant folding.
2493 uint64_t getTargetNullPointerValue(QualType QT) const;
2494
2495 bool addressSpaceMapManglingFor(LangAS AS) const {
2496 return AddrSpaceMapMangling || isTargetAddressSpace(AS);
2497 }
2498
2499private:
2500 // Helper for integer ordering
2501 unsigned getIntegerRank(const Type *T) const;
2502
2503public:
2504 //===--------------------------------------------------------------------===//
2505 // Type Compatibility Predicates
2506 //===--------------------------------------------------------------------===//
2507
2508 /// Compatibility predicates used to check assignment expressions.
2509 bool typesAreCompatible(QualType T1, QualType T2,
2510 bool CompareUnqualified = false); // C99 6.2.7p1
2511
2512 bool propertyTypesAreCompatible(QualType, QualType);
2513 bool typesAreBlockPointerCompatible(QualType, QualType);
2514
2515 bool isObjCIdType(QualType T) const {
2516 return T == getObjCIdType();
2517 }
2518
2519 bool isObjCClassType(QualType T) const {
2520 return T == getObjCClassType();
2521 }
2522
2523 bool isObjCSelType(QualType T) const {
2524 return T == getObjCSelType();
2525 }
2526
2527 bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
2528 bool ForCompare);
2529
2530 bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
2531
2532 // Check the safety of assignment from LHS to RHS
2533 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2534 const ObjCObjectPointerType *RHSOPT);
2535 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2536 const ObjCObjectType *RHS);
2537 bool canAssignObjCInterfacesInBlockPointer(
2538 const ObjCObjectPointerType *LHSOPT,
2539 const ObjCObjectPointerType *RHSOPT,
2540 bool BlockReturnType);
2541 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2542 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2543 const ObjCObjectPointerType *RHSOPT);
2544 bool canBindObjCObjectType(QualType To, QualType From);
2545
2546 // Functions for calculating composite types
2547 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2548 bool Unqualified = false, bool BlockReturnType = false);
2549 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2550 bool Unqualified = false);
2551 QualType mergeFunctionParameterTypes(QualType, QualType,
2552 bool OfBlockPointer = false,
2553 bool Unqualified = false);
2554 QualType mergeTransparentUnionType(QualType, QualType,
2555 bool OfBlockPointer=false,
2556 bool Unqualified = false);
2557
2558 QualType mergeObjCGCQualifiers(QualType, QualType);
2559
2560 /// This function merges the ExtParameterInfo lists of two functions. It
2561 /// returns true if the lists are compatible. The merged list is returned in
2562 /// NewParamInfos.
2563 ///
2564 /// \param FirstFnType The type of the first function.
2565 ///
2566 /// \param SecondFnType The type of the second function.
2567 ///
2568 /// \param CanUseFirst This flag is set to true if the first function's
2569 /// ExtParameterInfo list can be used as the composite list of
2570 /// ExtParameterInfo.
2571 ///
2572 /// \param CanUseSecond This flag is set to true if the second function's
2573 /// ExtParameterInfo list can be used as the composite list of
2574 /// ExtParameterInfo.
2575 ///
2576 /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
2577 /// empty if none of the flags are set.
2578 ///
2579 bool mergeExtParameterInfo(
2580 const FunctionProtoType *FirstFnType,
2581 const FunctionProtoType *SecondFnType,
2582 bool &CanUseFirst, bool &CanUseSecond,
2583 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
2584
2585 void ResetObjCLayout(const ObjCContainerDecl *CD);
2586
2587 //===--------------------------------------------------------------------===//
2588 // Integer Predicates
2589 //===--------------------------------------------------------------------===//
2590
2591 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2592 // of bits in an integer type excluding any padding bits.
2593 unsigned getIntWidth(QualType T) const;
2594
2595 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2596 // unsigned integer type. This method takes a signed type, and returns the
2597 // corresponding unsigned integer type.
2598 // With the introduction of fixed point types in ISO N1169, this method also
2599 // accepts fixed point types and returns the corresponding unsigned type for
2600 // a given fixed point type.
2601 QualType getCorrespondingUnsignedType(QualType T) const;
2602
2603 // Per ISO N1169, this method accepts fixed point types and returns the
2604 // corresponding saturated type for a given fixed point type.
2605 QualType getCorrespondingSaturatedType(QualType Ty) const;
2606
2607 //===--------------------------------------------------------------------===//
2608 // Integer Values
2609 //===--------------------------------------------------------------------===//
2610
2611 /// Make an APSInt of the appropriate width and signedness for the
2612 /// given \p Value and integer \p Type.
2613 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2614 // If Type is a signed integer type larger than 64 bits, we need to be sure
2615 // to sign extend Res appropriately.
2616 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2617 Res = Value;
2618 unsigned Width = getIntWidth(Type);
2619 if (Width != Res.getBitWidth())
2620 return Res.extOrTrunc(Width);
2621 return Res;
2622 }
2623
2624 bool isSentinelNullExpr(const Expr *E);
2625
2626 /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
2627 /// none exists.
2628 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2629
2630 /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
2631 /// none exists.
2632 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2633
2634 /// Return true if there is at least one \@implementation in the TU.
2635 bool AnyObjCImplementation() {
2636 return !ObjCImpls.empty();
2637 }
2638
2639 /// Set the implementation of ObjCInterfaceDecl.
2640 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2641 ObjCImplementationDecl *ImplD);
2642
2643 /// Set the implementation of ObjCCategoryDecl.
2644 void setObjCImplementation(ObjCCategoryDecl *CatD,
2645 ObjCCategoryImplDecl *ImplD);
2646
2647 /// Get the duplicate declaration of a ObjCMethod in the same
2648 /// interface, or null if none exists.
2649 const ObjCMethodDecl *
2650 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2651
2652 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2653 const ObjCMethodDecl *Redecl);
2654
2655 /// Returns the Objective-C interface that \p ND belongs to if it is
2656 /// an Objective-C method/property/ivar etc. that is part of an interface,
2657 /// otherwise returns null.
2658 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2659
2660 /// Set the copy inialization expression of a block var decl.
2661 void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2662
2663 /// Get the copy initialization expression of the VarDecl \p VD, or
2664 /// nullptr if none exists.
2665 Expr *getBlockVarCopyInits(const VarDecl* VD);
2666
2667 /// Allocate an uninitialized TypeSourceInfo.
2668 ///
2669 /// The caller should initialize the memory held by TypeSourceInfo using
2670 /// the TypeLoc wrappers.
2671 ///
2672 /// \param T the type that will be the basis for type source info. This type
2673 /// should refer to how the declarator was written in source code, not to
2674 /// what type semantic analysis resolved the declarator to.
2675 ///
2676 /// \param Size the size of the type info to create, or 0 if the size
2677 /// should be calculated based on the type.
2678 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2679
2680 /// Allocate a TypeSourceInfo where all locations have been
2681 /// initialized to a given location, which defaults to the empty
2682 /// location.
2683 TypeSourceInfo *
2684 getTrivialTypeSourceInfo(QualType T,
2685 SourceLocation Loc = SourceLocation()) const;
2686
2687 /// Add a deallocation callback that will be invoked when the
2688 /// ASTContext is destroyed.
2689 ///
2690 /// \param Callback A callback function that will be invoked on destruction.
2691 ///
2692 /// \param Data Pointer data that will be provided to the callback function
2693 /// when it is called.
2694 void AddDeallocation(void (*Callback)(void*), void *Data);
2695
2696 /// If T isn't trivially destructible, calls AddDeallocation to register it
2697 /// for destruction.
2698 template <typename T>
2699 void addDestruction(T *Ptr) {
2700 if (!std::is_trivially_destructible<T>::value) {
2701 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
2702 AddDeallocation(DestroyPtr, Ptr);
2703 }
2704 }
2705
2706 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2707 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2708
2709 /// Determines if the decl can be CodeGen'ed or deserialized from PCH
2710 /// lazily, only when used; this is only relevant for function or file scoped
2711 /// var definitions.
2712 ///
2713 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2714 /// it is not used.
2715 bool DeclMustBeEmitted(const Decl *D);
2716
2717 /// Visits all versions of a multiversioned function with the passed
2718 /// predicate.
2719 void forEachMultiversionedFunctionVersion(
2720 const FunctionDecl *FD,
2721 llvm::function_ref<void(FunctionDecl *)> Pred) const;
2722
2723 const CXXConstructorDecl *
2724 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2725
2726 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2727 CXXConstructorDecl *CD);
2728
2729 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2730
2731 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2732
2733 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2734
2735 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2736
2737 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2738 unsigned getManglingNumber(const NamedDecl *ND) const;
2739
2740 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2741 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2742
2743 /// Retrieve the context for computing mangling numbers in the given
2744 /// DeclContext.
2745 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2746
2747 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
2748
2749 /// Used by ParmVarDecl to store on the side the
2750 /// index of the parameter when it exceeds the size of the normal bitfield.
2751 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2752
2753 /// Used by ParmVarDecl to retrieve on the side the
2754 /// index of the parameter when it exceeds the size of the normal bitfield.
2755 unsigned getParameterIndex(const ParmVarDecl *D) const;
2756
2757 /// Get the storage for the constant value of a materialized temporary
2758 /// of static storage duration.
2759 APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
2760 bool MayCreate);
2761
2762 //===--------------------------------------------------------------------===//
2763 // Statistics
2764 //===--------------------------------------------------------------------===//
2765
2766 /// The number of implicitly-declared default constructors.
2767 static unsigned NumImplicitDefaultConstructors;
2768
2769 /// The number of implicitly-declared default constructors for
2770 /// which declarations were built.
2771 static unsigned NumImplicitDefaultConstructorsDeclared;
2772
2773 /// The number of implicitly-declared copy constructors.
2774 static unsigned NumImplicitCopyConstructors;
2775
2776 /// The number of implicitly-declared copy constructors for
2777 /// which declarations were built.
2778 static unsigned NumImplicitCopyConstructorsDeclared;
2779
2780 /// The number of implicitly-declared move constructors.
2781 static unsigned NumImplicitMoveConstructors;
2782
2783 /// The number of implicitly-declared move constructors for
2784 /// which declarations were built.
2785 static unsigned NumImplicitMoveConstructorsDeclared;
2786
2787 /// The number of implicitly-declared copy assignment operators.
2788 static unsigned NumImplicitCopyAssignmentOperators;
2789
2790 /// The number of implicitly-declared copy assignment operators for
2791 /// which declarations were built.
2792 static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2793
2794 /// The number of implicitly-declared move assignment operators.
2795 static unsigned NumImplicitMoveAssignmentOperators;
2796
2797 /// The number of implicitly-declared move assignment operators for
2798 /// which declarations were built.
2799 static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2800
2801 /// The number of implicitly-declared destructors.
2802 static unsigned NumImplicitDestructors;
2803
2804 /// The number of implicitly-declared destructors for which
2805 /// declarations were built.
2806 static unsigned NumImplicitDestructorsDeclared;
2807
2808public:
2809 /// Initialize built-in types.
2810 ///
2811 /// This routine may only be invoked once for a given ASTContext object.
2812 /// It is normally invoked after ASTContext construction.
2813 ///
2814 /// \param Target The target
2815 void InitBuiltinTypes(const TargetInfo &Target,
2816 const TargetInfo *AuxTarget = nullptr);
2817
2818private:
2819 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2820
2821 // Return the Objective-C type encoding for a given type.
2822 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2823 bool ExpandPointedToStructures,
2824 bool ExpandStructures,
2825 const FieldDecl *Field,
2826 bool OutermostType = false,
2827 bool EncodingProperty = false,
2828 bool StructField = false,
2829 bool EncodeBlockParameters = false,
2830 bool EncodeClassNames = false,
2831 bool EncodePointerToObjCTypedef = false,
2832 QualType *NotEncodedT=nullptr) const;
2833
2834 // Adds the encoding of the structure's members.
2835 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2836 const FieldDecl *Field,
2837 bool includeVBases = true,
2838 QualType *NotEncodedT=nullptr) const;
2839
2840public:
2841 // Adds the encoding of a method parameter or return type.
2842 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2843 QualType T, std::string& S,
2844 bool Extended) const;
2845
2846 /// Returns true if this is an inline-initialized static data member
2847 /// which is treated as a definition for MSVC compatibility.
2848 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2849
2850 enum class InlineVariableDefinitionKind {
2851 /// Not an inline variable.
2852 None,
2853
2854 /// Weak definition of inline variable.
2855 Weak,
2856
2857 /// Weak for now, might become strong later in this TU.
2858 WeakUnknown,
2859
2860 /// Strong definition.
2861 Strong
2862 };
2863
2864 /// Determine whether a definition of this inline variable should
2865 /// be treated as a weak or strong definition. For compatibility with
2866 /// C++14 and before, for a constexpr static data member, if there is an
2867 /// out-of-line declaration of the member, we may promote it from weak to
2868 /// strong.
2869 InlineVariableDefinitionKind
2870 getInlineVariableDefinitionKind(const VarDecl *VD) const;
2871
2872private:
2873 friend class DeclarationNameTable;
2874 friend class DeclContext;
2875
2876 const ASTRecordLayout &
2877 getObjCLayout(const ObjCInterfaceDecl *D,
2878 const ObjCImplementationDecl *Impl) const;
2879
2880 /// A set of deallocations that should be performed when the
2881 /// ASTContext is destroyed.
2882 // FIXME: We really should have a better mechanism in the ASTContext to
2883 // manage running destructors for types which do variable sized allocation
2884 // within the AST. In some places we thread the AST bump pointer allocator
2885 // into the datastructures which avoids this mess during deallocation but is
2886 // wasteful of memory, and here we require a lot of error prone book keeping
2887 // in order to track and run destructors while we're tearing things down.
2888 using DeallocationFunctionsAndArguments =
2889 llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
2890 DeallocationFunctionsAndArguments Deallocations;
2891
2892 // FIXME: This currently contains the set of StoredDeclMaps used
2893 // by DeclContext objects. This probably should not be in ASTContext,
2894 // but we include it here so that ASTContext can quickly deallocate them.
2895 llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
2896
2897 std::unique_ptr<ParentMapPointers> PointerParents;
2898 std::unique_ptr<ParentMapOtherNodes> OtherParents;
2899
2900 std::unique_ptr<VTableContextBase> VTContext;
2901
2902 void ReleaseDeclContextMaps();
2903 void ReleaseParentMapEntries();
2904
2905public:
2906 enum PragmaSectionFlag : unsigned {
2907 PSF_None = 0,
2908 PSF_Read = 0x1,
2909 PSF_Write = 0x2,
2910 PSF_Execute = 0x4,
2911 PSF_Implicit = 0x8,
2912 PSF_Invalid = 0x80000000U,
2913 };
2914
2915 struct SectionInfo {
2916 DeclaratorDecl *Decl;
2917 SourceLocation PragmaSectionLocation;
2918 int SectionFlags;
2919
2920 SectionInfo() = default;
2921 SectionInfo(DeclaratorDecl *Decl,
2922 SourceLocation PragmaSectionLocation,
2923 int SectionFlags)
2924 : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
2925 SectionFlags(SectionFlags) {}
2926 };
2927
2928 llvm::StringMap<SectionInfo> SectionInfos;
2929};
2930
2931/// Utility function for constructing a nullary selector.
2932inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
2933 IdentifierInfo* II = &Ctx.Idents.get(name);
2934 return Ctx.Selectors.getSelector(0, &II);
2935}
2936
2937/// Utility function for constructing an unary selector.
2938inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
2939 IdentifierInfo* II = &Ctx.Idents.get(name);
2940 return Ctx.Selectors.getSelector(1, &II);
2941}
2942
2943} // namespace clang
2944
2945// operator new and delete aren't allowed inside namespaces.
2946
2947/// Placement new for using the ASTContext's allocator.
2948///
2949/// This placement form of operator new uses the ASTContext's allocator for
2950/// obtaining memory.
2951///
2952/// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2953/// here need to also be made there.
2954///
2955/// We intentionally avoid using a nothrow specification here so that the calls
2956/// to this operator will not perform a null check on the result -- the
2957/// underlying allocator never returns null pointers.
2958///
2959/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2960/// @code
2961/// // Default alignment (8)
2962/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2963/// // Specific alignment
2964/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2965/// @endcode
2966/// Memory allocated through this placement new operator does not need to be
2967/// explicitly freed, as ASTContext will free all of this memory when it gets
2968/// destroyed. Please note that you cannot use delete on the pointer.
2969///
2970/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2971/// @param C The ASTContext that provides the allocator.
2972/// @param Alignment The alignment of the allocated memory (if the underlying
2973/// allocator supports it).
2974/// @return The allocated memory. Could be nullptr.
2975inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2976 size_t Alignment) {
2977 return C.Allocate(Bytes, Alignment);
2978}
2979
2980/// Placement delete companion to the new above.
2981///
2982/// This operator is just a companion to the new above. There is no way of
2983/// invoking it directly; see the new operator for more details. This operator
2984/// is called implicitly by the compiler if a placement new expression using
2985/// the ASTContext throws in the object constructor.
2986inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2987 C.Deallocate(Ptr);
2988}
2989
2990/// This placement form of operator new[] uses the ASTContext's allocator for
2991/// obtaining memory.
2992///
2993/// We intentionally avoid using a nothrow specification here so that the calls
2994/// to this operator will not perform a null check on the result -- the
2995/// underlying allocator never returns null pointers.
2996///
2997/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2998/// @code
2999/// // Default alignment (8)
3000/// char *data = new (Context) char[10];
3001/// // Specific alignment
3002/// char *data = new (Context, 4) char[10];
3003/// @endcode
3004/// Memory allocated through this placement new[] operator does not need to be
3005/// explicitly freed, as ASTContext will free all of this memory when it gets
3006/// destroyed. Please note that you cannot use delete on the pointer.
3007///
3008/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3009/// @param C The ASTContext that provides the allocator.
3010/// @param Alignment The alignment of the allocated memory (if the underlying
3011/// allocator supports it).
3012/// @return The allocated memory. Could be nullptr.
3013inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
3014 size_t Alignment = 8) {
3015 return C.Allocate(Bytes, Alignment);
3016}
3017
3018/// Placement delete[] companion to the new[] above.
3019///
3020/// This operator is just a companion to the new[] above. There is no way of
3021/// invoking it directly; see the new[] operator for more details. This operator
3022/// is called implicitly by the compiler if a placement new[] expression using
3023/// the ASTContext throws in the object constructor.
3024inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
3025 C.Deallocate(Ptr);
3026}
3027
3028/// Create the representation of a LazyGenerationalUpdatePtr.
3029template <typename Owner, typename T,
3030 void (clang::ExternalASTSource::*Update)(Owner)>
3031typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
3032 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
3033 const clang::ASTContext &Ctx, T Value) {
3034 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
3035 // include ASTContext.h. We explicitly instantiate it for all relevant types
3036 // in ASTContext.cpp.
3037 if (auto *Source = Ctx.getExternalSource())
3038 return new (Ctx) LazyData(Source, Value);
3039 return Value;
3040}
3041
3042#endif // LLVM_CLANG_AST_ASTCONTEXT_H
3043

Warning: That file was not part of the compilation database. It may have many parsing errors.