1 //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the ASTContext interface.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/APValue.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/ASTTypeTraits.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/AttrIterator.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/Comment.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclContextInternals.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclOpenMP.h"
28 #include "clang/AST/DeclTemplate.h"
29 #include "clang/AST/DeclarationName.h"
30 #include "clang/AST/Expr.h"
31 #include "clang/AST/ExprCXX.h"
32 #include "clang/AST/ExternalASTSource.h"
33 #include "clang/AST/Mangle.h"
34 #include "clang/AST/MangleNumberingContext.h"
35 #include "clang/AST/NestedNameSpecifier.h"
36 #include "clang/AST/RawCommentList.h"
37 #include "clang/AST/RecordLayout.h"
38 #include "clang/AST/RecursiveASTVisitor.h"
39 #include "clang/AST/Stmt.h"
40 #include "clang/AST/TemplateBase.h"
41 #include "clang/AST/TemplateName.h"
42 #include "clang/AST/Type.h"
43 #include "clang/AST/TypeLoc.h"
44 #include "clang/AST/UnresolvedSet.h"
45 #include "clang/AST/VTableBuilder.h"
46 #include "clang/Basic/AddressSpaces.h"
47 #include "clang/Basic/Builtins.h"
48 #include "clang/Basic/CommentOptions.h"
49 #include "clang/Basic/ExceptionSpecificationType.h"
50 #include "clang/Basic/FixedPoint.h"
51 #include "clang/Basic/IdentifierTable.h"
52 #include "clang/Basic/LLVM.h"
53 #include "clang/Basic/LangOptions.h"
54 #include "clang/Basic/Linkage.h"
55 #include "clang/Basic/ObjCRuntime.h"
56 #include "clang/Basic/SanitizerBlacklist.h"
57 #include "clang/Basic/SourceLocation.h"
58 #include "clang/Basic/SourceManager.h"
59 #include "clang/Basic/Specifiers.h"
60 #include "clang/Basic/TargetCXXABI.h"
61 #include "clang/Basic/TargetInfo.h"
62 #include "clang/Basic/XRayLists.h"
63 #include "llvm/ADT/APInt.h"
64 #include "llvm/ADT/APSInt.h"
65 #include "llvm/ADT/ArrayRef.h"
66 #include "llvm/ADT/DenseMap.h"
67 #include "llvm/ADT/DenseSet.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/PointerUnion.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallVector.h"
75 #include "llvm/ADT/StringExtras.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/Triple.h"
78 #include "llvm/Support/Capacity.h"
79 #include "llvm/Support/Casting.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Support/MathExtras.h"
83 #include "llvm/Support/raw_ostream.h"
95 using namespace clang;
98 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
101 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
104 // If we already tried to load comments but there are none,
105 // we won't find anything.
106 if (CommentsLoaded && Comments.getComments().empty())
109 // User can not attach documentation to implicit declarations.
113 // User can not attach documentation to implicit instantiations.
114 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
115 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
119 if (const auto *VD = dyn_cast<VarDecl>(D)) {
120 if (VD->isStaticDataMember() &&
121 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
125 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
126 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
130 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
131 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
132 if (TSK == TSK_ImplicitInstantiation ||
133 TSK == TSK_Undeclared)
137 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
138 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
141 if (const auto *TD = dyn_cast<TagDecl>(D)) {
142 // When tag declaration (but not definition!) is part of the
143 // decl-specifier-seq of some other declaration, it doesn't get comment
144 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
147 // TODO: handle comments for function parameters properly.
148 if (isa<ParmVarDecl>(D))
151 // TODO: we could look up template parameter documentation in the template
153 if (isa<TemplateTypeParmDecl>(D) ||
154 isa<NonTypeTemplateParmDecl>(D) ||
155 isa<TemplateTemplateParmDecl>(D))
158 // Find declaration location.
159 // For Objective-C declarations we generally don't expect to have multiple
160 // declarators, thus use declaration starting location as the "declaration
162 // For all other declarations multiple declarators are used quite frequently,
163 // so we use the location of the identifier as the "declaration location".
164 SourceLocation DeclLoc;
165 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
166 isa<ObjCPropertyDecl>(D) ||
167 isa<RedeclarableTemplateDecl>(D) ||
168 isa<ClassTemplateSpecializationDecl>(D))
169 DeclLoc = D->getBeginLoc();
171 DeclLoc = D->getLocation();
172 if (DeclLoc.isMacroID()) {
173 if (isa<TypedefDecl>(D)) {
174 // If location of the typedef name is in a macro, it is because being
175 // declared via a macro. Try using declaration's starting location as
176 // the "declaration location".
177 DeclLoc = D->getBeginLoc();
178 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
179 // If location of the tag decl is inside a macro, but the spelling of
180 // the tag name comes from a macro argument, it looks like a special
181 // macro like NS_ENUM is being used to define the tag decl. In that
182 // case, adjust the source location to the expansion loc so that we can
183 // attach the comment to the tag decl.
184 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
185 TD->isCompleteDefinition())
186 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
191 // If the declaration doesn't map directly to a location in a file, we
192 // can't find the comment.
193 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
196 if (!CommentsLoaded && ExternalSource) {
197 ExternalSource->ReadComments();
200 ArrayRef<RawComment *> RawComments = Comments.getComments();
201 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
202 BeforeThanCompare<RawComment>(SourceMgr)));
205 CommentsLoaded = true;
208 ArrayRef<RawComment *> RawComments = Comments.getComments();
209 // If there are no comments anywhere, we won't find anything.
210 if (RawComments.empty())
213 // Find the comment that occurs just after this declaration.
214 ArrayRef<RawComment *>::iterator Comment;
216 // When searching for comments during parsing, the comment we are looking
217 // for is usually among the last two comments we parsed -- check them
219 RawComment CommentAtDeclLoc(
220 SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
221 BeforeThanCompare<RawComment> Compare(SourceMgr);
222 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
223 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
224 if (!Found && RawComments.size() >= 2) {
226 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
230 Comment = MaybeBeforeDecl + 1;
232 llvm::lower_bound(RawComments, &CommentAtDeclLoc, Compare));
235 Comment = llvm::lower_bound(RawComments, &CommentAtDeclLoc, Compare);
239 // Decompose the location for the declaration and find the beginning of the
241 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
243 // First check whether we have a trailing comment.
244 if (Comment != RawComments.end() &&
245 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
246 && (*Comment)->isTrailingComment() &&
247 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
248 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
249 std::pair<FileID, unsigned> CommentBeginDecomp
250 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
251 // Check that Doxygen trailing comment comes after the declaration, starts
252 // on the same line and in the same file as the declaration.
253 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
254 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
255 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
256 CommentBeginDecomp.second)) {
257 (**Comment).setAttached();
262 // The comment just after the declaration was not a trailing comment.
263 // Let's look at the previous comment.
264 if (Comment == RawComments.begin())
268 // Check that we actually have a non-member Doxygen comment.
269 if (!((*Comment)->isDocumentation() ||
270 LangOpts.CommentOpts.ParseAllComments) ||
271 (*Comment)->isTrailingComment())
274 // Decompose the end of the comment.
275 std::pair<FileID, unsigned> CommentEndDecomp
276 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
278 // If the comment and the declaration aren't in the same file, then they
280 if (DeclLocDecomp.first != CommentEndDecomp.first)
283 // Get the corresponding buffer.
284 bool Invalid = false;
285 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
290 // Extract text between the comment and declaration.
291 StringRef Text(Buffer + CommentEndDecomp.second,
292 DeclLocDecomp.second - CommentEndDecomp.second);
294 // There should be no other declarations or preprocessor directives between
295 // comment and declaration.
296 if (Text.find_first_of(";{}#@") != StringRef::npos)
299 (**Comment).setAttached();
303 /// If we have a 'templated' declaration for a template, adjust 'D' to
304 /// refer to the actual template.
305 /// If we have an implicit instantiation, adjust 'D' to refer to template.
306 static const Decl *adjustDeclToTemplate(const Decl *D) {
307 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
308 // Is this function declaration part of a function template?
309 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
312 // Nothing to do if function is not an implicit instantiation.
313 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
316 // Function is an implicit instantiation of a function template?
317 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
320 // Function is instantiated from a member definition of a class template?
321 if (const FunctionDecl *MemberDecl =
322 FD->getInstantiatedFromMemberFunction())
327 if (const auto *VD = dyn_cast<VarDecl>(D)) {
328 // Static data member is instantiated from a member definition of a class
330 if (VD->isStaticDataMember())
331 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
336 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
337 // Is this class declaration part of a class template?
338 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
341 // Class is an implicit instantiation of a class template or partial
343 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
344 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
346 llvm::PointerUnion<ClassTemplateDecl *,
347 ClassTemplatePartialSpecializationDecl *>
348 PU = CTSD->getSpecializedTemplateOrPartial();
349 return PU.is<ClassTemplateDecl*>() ?
350 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
351 static_cast<const Decl*>(
352 PU.get<ClassTemplatePartialSpecializationDecl *>());
355 // Class is instantiated from a member definition of a class template?
356 if (const MemberSpecializationInfo *Info =
357 CRD->getMemberSpecializationInfo())
358 return Info->getInstantiatedFrom();
362 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
363 // Enum is instantiated from a member definition of a class template?
364 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
369 // FIXME: Adjust alias templates?
373 const RawComment *ASTContext::getRawCommentForAnyRedecl(
375 const Decl **OriginalDecl) const {
376 D = adjustDeclToTemplate(D);
378 // Check whether we have cached a comment for this declaration already.
380 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
381 RedeclComments.find(D);
382 if (Pos != RedeclComments.end()) {
383 const RawCommentAndCacheFlags &Raw = Pos->second;
384 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
386 *OriginalDecl = Raw.getOriginalDecl();
392 // Search for comments attached to declarations in the redeclaration chain.
393 const RawComment *RC = nullptr;
394 const Decl *OriginalDeclForRC = nullptr;
395 for (auto I : D->redecls()) {
396 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
397 RedeclComments.find(I);
398 if (Pos != RedeclComments.end()) {
399 const RawCommentAndCacheFlags &Raw = Pos->second;
400 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
402 OriginalDeclForRC = Raw.getOriginalDecl();
406 RC = getRawCommentForDeclNoCache(I);
407 OriginalDeclForRC = I;
408 RawCommentAndCacheFlags Raw;
410 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
411 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
412 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
415 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
416 Raw.setOriginalDecl(I);
417 RedeclComments[I] = Raw;
423 // If we found a comment, it should be a documentation comment.
424 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
427 *OriginalDecl = OriginalDeclForRC;
429 // Update cache for every declaration in the redeclaration chain.
430 RawCommentAndCacheFlags Raw;
432 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
433 Raw.setOriginalDecl(OriginalDeclForRC);
435 for (auto I : D->redecls()) {
436 RawCommentAndCacheFlags &R = RedeclComments[I];
437 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
444 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
445 SmallVectorImpl<const NamedDecl *> &Redeclared) {
446 const DeclContext *DC = ObjCMethod->getDeclContext();
447 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
448 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
451 // Add redeclared method here.
452 for (const auto *Ext : ID->known_extensions()) {
453 if (ObjCMethodDecl *RedeclaredMethod =
454 Ext->getMethod(ObjCMethod->getSelector(),
455 ObjCMethod->isInstanceMethod()))
456 Redeclared.push_back(RedeclaredMethod);
461 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
462 const Decl *D) const {
463 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
464 ThisDeclInfo->CommentDecl = D;
465 ThisDeclInfo->IsFilled = false;
466 ThisDeclInfo->fill();
467 ThisDeclInfo->CommentDecl = FC->getDecl();
468 if (!ThisDeclInfo->TemplateParameters)
469 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
470 comments::FullComment *CFC =
471 new (*this) comments::FullComment(FC->getBlocks(),
476 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
477 const RawComment *RC = getRawCommentForDeclNoCache(D);
478 return RC ? RC->parse(*this, nullptr, D) : nullptr;
481 comments::FullComment *ASTContext::getCommentForDecl(
483 const Preprocessor *PP) const {
484 if (D->isInvalidDecl())
486 D = adjustDeclToTemplate(D);
488 const Decl *Canonical = D->getCanonicalDecl();
489 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
490 ParsedComments.find(Canonical);
492 if (Pos != ParsedComments.end()) {
493 if (Canonical != D) {
494 comments::FullComment *FC = Pos->second;
495 comments::FullComment *CFC = cloneFullComment(FC, D);
501 const Decl *OriginalDecl;
503 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
505 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
506 SmallVector<const NamedDecl*, 8> Overridden;
507 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
508 if (OMD && OMD->isPropertyAccessor())
509 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
510 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
511 return cloneFullComment(FC, D);
513 addRedeclaredMethods(OMD, Overridden);
514 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
515 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
516 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
517 return cloneFullComment(FC, D);
519 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
520 // Attach any tag type's documentation to its typedef if latter
521 // does not have one of its own.
522 QualType QT = TD->getUnderlyingType();
523 if (const auto *TT = QT->getAs<TagType>())
524 if (const Decl *TD = TT->getDecl())
525 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
526 return cloneFullComment(FC, D);
528 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
529 while (IC->getSuperClass()) {
530 IC = IC->getSuperClass();
531 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
532 return cloneFullComment(FC, D);
535 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
536 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
537 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
538 return cloneFullComment(FC, D);
540 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
541 if (!(RD = RD->getDefinition()))
543 // Check non-virtual bases.
544 for (const auto &I : RD->bases()) {
545 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
547 QualType Ty = I.getType();
550 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
551 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
554 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
555 return cloneFullComment(FC, D);
558 // Check virtual bases.
559 for (const auto &I : RD->vbases()) {
560 if (I.getAccessSpecifier() != AS_public)
562 QualType Ty = I.getType();
565 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
566 if (!(VirtualBase= VirtualBase->getDefinition()))
568 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
569 return cloneFullComment(FC, D);
576 // If the RawComment was attached to other redeclaration of this Decl, we
577 // should parse the comment in context of that other Decl. This is important
578 // because comments can contain references to parameter names which can be
579 // different across redeclarations.
580 if (D != OriginalDecl)
581 return getCommentForDecl(OriginalDecl, PP);
583 comments::FullComment *FC = RC->parse(*this, PP, D);
584 ParsedComments[Canonical] = FC;
589 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
590 TemplateTemplateParmDecl *Parm) {
591 ID.AddInteger(Parm->getDepth());
592 ID.AddInteger(Parm->getPosition());
593 ID.AddBoolean(Parm->isParameterPack());
595 TemplateParameterList *Params = Parm->getTemplateParameters();
596 ID.AddInteger(Params->size());
597 for (TemplateParameterList::const_iterator P = Params->begin(),
598 PEnd = Params->end();
600 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
602 ID.AddBoolean(TTP->isParameterPack());
606 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
608 ID.AddBoolean(NTTP->isParameterPack());
609 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
610 if (NTTP->isExpandedParameterPack()) {
612 ID.AddInteger(NTTP->getNumExpansionTypes());
613 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
614 QualType T = NTTP->getExpansionType(I);
615 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
618 ID.AddBoolean(false);
622 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
628 TemplateTemplateParmDecl *
629 ASTContext::getCanonicalTemplateTemplateParmDecl(
630 TemplateTemplateParmDecl *TTP) const {
631 // Check if we already have a canonical template template parameter.
632 llvm::FoldingSetNodeID ID;
633 CanonicalTemplateTemplateParm::Profile(ID, TTP);
634 void *InsertPos = nullptr;
635 CanonicalTemplateTemplateParm *Canonical
636 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
638 return Canonical->getParam();
640 // Build a canonical template parameter list.
641 TemplateParameterList *Params = TTP->getTemplateParameters();
642 SmallVector<NamedDecl *, 4> CanonParams;
643 CanonParams.reserve(Params->size());
644 for (TemplateParameterList::const_iterator P = Params->begin(),
645 PEnd = Params->end();
647 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
648 CanonParams.push_back(
649 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
653 TTP->getIndex(), nullptr, false,
654 TTP->isParameterPack()));
655 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
656 QualType T = getCanonicalType(NTTP->getType());
657 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
658 NonTypeTemplateParmDecl *Param;
659 if (NTTP->isExpandedParameterPack()) {
660 SmallVector<QualType, 2> ExpandedTypes;
661 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
662 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
663 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
664 ExpandedTInfos.push_back(
665 getTrivialTypeSourceInfo(ExpandedTypes.back()));
668 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
672 NTTP->getPosition(), nullptr,
678 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
682 NTTP->getPosition(), nullptr,
684 NTTP->isParameterPack(),
687 CanonParams.push_back(Param);
690 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
691 cast<TemplateTemplateParmDecl>(*P)));
694 assert(!TTP->getRequiresClause() &&
695 "Unexpected requires-clause on template template-parameter");
696 Expr *const CanonRequiresClause = nullptr;
698 TemplateTemplateParmDecl *CanonTTP
699 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
700 SourceLocation(), TTP->getDepth(),
702 TTP->isParameterPack(),
704 TemplateParameterList::Create(*this, SourceLocation(),
708 CanonRequiresClause));
710 // Get the new insert position for the node we care about.
711 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
712 assert(!Canonical && "Shouldn't be in the map!");
715 // Create the canonical template template parameter entry.
716 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
717 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
721 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
722 if (!LangOpts.CPlusPlus) return nullptr;
724 switch (T.getCXXABI().getKind()) {
725 case TargetCXXABI::GenericARM: // Same as Itanium at this level
726 case TargetCXXABI::iOS:
727 case TargetCXXABI::iOS64:
728 case TargetCXXABI::WatchOS:
729 case TargetCXXABI::GenericAArch64:
730 case TargetCXXABI::GenericMIPS:
731 case TargetCXXABI::GenericItanium:
732 case TargetCXXABI::WebAssembly:
733 return CreateItaniumCXXABI(*this);
734 case TargetCXXABI::Microsoft:
735 return CreateMicrosoftCXXABI(*this);
737 llvm_unreachable("Invalid CXXABI type!");
740 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
741 const LangOptions &LOpts) {
742 if (LOpts.FakeAddressSpaceMap) {
743 // The fake address space map must have a distinct entry for each
744 // language-specific address space.
745 static const unsigned FakeAddrSpaceMap[] = {
749 2, // opencl_constant
756 return &FakeAddrSpaceMap;
758 return &T.getAddressSpaceMap();
762 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
763 const LangOptions &LangOpts) {
764 switch (LangOpts.getAddressSpaceMapMangling()) {
765 case LangOptions::ASMM_Target:
766 return TI.useAddressSpaceMapMangling();
767 case LangOptions::ASMM_On:
769 case LangOptions::ASMM_Off:
772 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
775 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
776 IdentifierTable &idents, SelectorTable &sels,
777 Builtin::Context &builtins)
778 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
779 DependentTemplateSpecializationTypes(this_()),
780 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
781 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
782 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
783 LangOpts.XRayNeverInstrumentFiles,
784 LangOpts.XRayAttrListFiles, SM)),
785 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
786 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
787 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
788 CompCategories(this_()), LastSDM(nullptr, 0) {
789 TUDecl = TranslationUnitDecl::Create(*this);
790 TraversalScope = {TUDecl};
793 ASTContext::~ASTContext() {
794 // Release the DenseMaps associated with DeclContext objects.
795 // FIXME: Is this the ideal solution?
796 ReleaseDeclContextMaps();
798 // Call all of the deallocation functions on all of their targets.
799 for (auto &Pair : Deallocations)
800 (Pair.first)(Pair.second);
802 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
803 // because they can contain DenseMaps.
804 for (llvm::DenseMap<const ObjCContainerDecl*,
805 const ASTRecordLayout*>::iterator
806 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
807 // Increment in loop to prevent using deallocated memory.
808 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
811 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
812 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
813 // Increment in loop to prevent using deallocated memory.
814 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
818 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
819 AEnd = DeclAttrs.end();
821 A->second->~AttrVec();
823 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
824 MaterializedTemporaryValues)
825 MTVPair.second->~APValue();
827 for (const auto &Value : ModuleInitializers)
828 Value.second->~PerModuleInitializers();
830 for (APValue *Value : APValueCleanups)
834 class ASTContext::ParentMap {
835 /// Contains parents of a node.
836 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
838 /// Maps from a node to its parents. This is used for nodes that have
839 /// pointer identity only, which are more common and we can save space by
840 /// only storing a unique pointer to them.
841 using ParentMapPointers = llvm::DenseMap<
843 llvm::PointerUnion4<const Decl *, const Stmt *,
844 ast_type_traits::DynTypedNode *, ParentVector *>>;
846 /// Parent map for nodes without pointer identity. We store a full
847 /// DynTypedNode for all keys.
848 using ParentMapOtherNodes = llvm::DenseMap<
849 ast_type_traits::DynTypedNode,
850 llvm::PointerUnion4<const Decl *, const Stmt *,
851 ast_type_traits::DynTypedNode *, ParentVector *>>;
853 ParentMapPointers PointerParents;
854 ParentMapOtherNodes OtherParents;
857 static ast_type_traits::DynTypedNode
858 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
859 if (const auto *D = U.dyn_cast<const Decl *>())
860 return ast_type_traits::DynTypedNode::create(*D);
861 if (const auto *S = U.dyn_cast<const Stmt *>())
862 return ast_type_traits::DynTypedNode::create(*S);
863 return *U.get<ast_type_traits::DynTypedNode *>();
866 template <typename NodeTy, typename MapTy>
867 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
869 auto I = Map.find(Node);
870 if (I == Map.end()) {
871 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
873 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
874 return llvm::makeArrayRef(*V);
876 return getSingleDynTypedNodeFromParentMap(I->second);
880 ParentMap(ASTContext &Ctx);
882 for (const auto &Entry : PointerParents) {
883 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
884 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
885 } else if (Entry.second.is<ParentVector *>()) {
886 delete Entry.second.get<ParentVector *>();
889 for (const auto &Entry : OtherParents) {
890 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
891 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
892 } else if (Entry.second.is<ParentVector *>()) {
893 delete Entry.second.get<ParentVector *>();
898 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
899 if (Node.getNodeKind().hasPointerIdentity())
900 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
901 return getDynNodeFromMap(Node, OtherParents);
905 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
906 TraversalScope = TopLevelDecls;
910 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
911 Deallocations.push_back({Callback, Data});
915 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
916 ExternalSource = std::move(Source);
919 void ASTContext::PrintStats() const {
920 llvm::errs() << "\n*** AST Context Stats:\n";
921 llvm::errs() << " " << Types.size() << " types total.\n";
923 unsigned counts[] = {
924 #define TYPE(Name, Parent) 0,
925 #define ABSTRACT_TYPE(Name, Parent)
926 #include "clang/AST/TypeNodes.def"
930 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
932 counts[(unsigned)T->getTypeClass()]++;
936 unsigned TotalBytes = 0;
937 #define TYPE(Name, Parent) \
939 llvm::errs() << " " << counts[Idx] << " " << #Name \
940 << " types, " << sizeof(Name##Type) << " each " \
941 << "(" << counts[Idx] * sizeof(Name##Type) \
943 TotalBytes += counts[Idx] * sizeof(Name##Type); \
945 #define ABSTRACT_TYPE(Name, Parent)
946 #include "clang/AST/TypeNodes.def"
948 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
950 // Implicit special member functions.
951 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
952 << NumImplicitDefaultConstructors
953 << " implicit default constructors created\n";
954 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
955 << NumImplicitCopyConstructors
956 << " implicit copy constructors created\n";
957 if (getLangOpts().CPlusPlus)
958 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
959 << NumImplicitMoveConstructors
960 << " implicit move constructors created\n";
961 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
962 << NumImplicitCopyAssignmentOperators
963 << " implicit copy assignment operators created\n";
964 if (getLangOpts().CPlusPlus)
965 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
966 << NumImplicitMoveAssignmentOperators
967 << " implicit move assignment operators created\n";
968 llvm::errs() << NumImplicitDestructorsDeclared << "/"
969 << NumImplicitDestructors
970 << " implicit destructors created\n";
972 if (ExternalSource) {
973 llvm::errs() << "\n";
974 ExternalSource->PrintStats();
977 BumpAlloc.PrintStats();
980 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
981 bool NotifyListeners) {
983 if (auto *Listener = getASTMutationListener())
984 Listener->RedefinedHiddenDefinition(ND, M);
986 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
989 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
990 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
991 if (It == MergedDefModules.end())
994 auto &Merged = It->second;
995 llvm::DenseSet<Module*> Found;
996 for (Module *&M : Merged)
997 if (!Found.insert(M).second)
999 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1002 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1003 if (LazyInitializers.empty())
1006 auto *Source = Ctx.getExternalSource();
1007 assert(Source && "lazy initializers but no external source");
1009 auto LazyInits = std::move(LazyInitializers);
1010 LazyInitializers.clear();
1012 for (auto ID : LazyInits)
1013 Initializers.push_back(Source->GetExternalDecl(ID));
1015 assert(LazyInitializers.empty() &&
1016 "GetExternalDecl for lazy module initializer added more inits");
1019 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1020 // One special case: if we add a module initializer that imports another
1021 // module, and that module's only initializer is an ImportDecl, simplify.
1022 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1023 auto It = ModuleInitializers.find(ID->getImportedModule());
1025 // Maybe the ImportDecl does nothing at all. (Common case.)
1026 if (It == ModuleInitializers.end())
1029 // Maybe the ImportDecl only imports another ImportDecl.
1030 auto &Imported = *It->second;
1031 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1032 Imported.resolve(*this);
1033 auto *OnlyDecl = Imported.Initializers.front();
1034 if (isa<ImportDecl>(OnlyDecl))
1039 auto *&Inits = ModuleInitializers[M];
1041 Inits = new (*this) PerModuleInitializers;
1042 Inits->Initializers.push_back(D);
1045 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1046 auto *&Inits = ModuleInitializers[M];
1048 Inits = new (*this) PerModuleInitializers;
1049 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1050 IDs.begin(), IDs.end());
1053 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1054 auto It = ModuleInitializers.find(M);
1055 if (It == ModuleInitializers.end())
1058 auto *Inits = It->second;
1059 Inits->resolve(*this);
1060 return Inits->Initializers;
1063 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1064 if (!ExternCContext)
1065 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1067 return ExternCContext;
1070 BuiltinTemplateDecl *
1071 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1072 const IdentifierInfo *II) const {
1073 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1074 BuiltinTemplate->setImplicit();
1075 TUDecl->addDecl(BuiltinTemplate);
1077 return BuiltinTemplate;
1080 BuiltinTemplateDecl *
1081 ASTContext::getMakeIntegerSeqDecl() const {
1082 if (!MakeIntegerSeqDecl)
1083 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1084 getMakeIntegerSeqName());
1085 return MakeIntegerSeqDecl;
1088 BuiltinTemplateDecl *
1089 ASTContext::getTypePackElementDecl() const {
1090 if (!TypePackElementDecl)
1091 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1092 getTypePackElementName());
1093 return TypePackElementDecl;
1096 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1097 RecordDecl::TagKind TK) const {
1099 RecordDecl *NewDecl;
1100 if (getLangOpts().CPlusPlus)
1101 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1102 Loc, &Idents.get(Name));
1104 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1106 NewDecl->setImplicit();
1107 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1108 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1112 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1113 StringRef Name) const {
1114 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1115 TypedefDecl *NewDecl = TypedefDecl::Create(
1116 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1117 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1118 NewDecl->setImplicit();
1122 TypedefDecl *ASTContext::getInt128Decl() const {
1124 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1128 TypedefDecl *ASTContext::getUInt128Decl() const {
1130 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1134 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1135 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1136 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1137 Types.push_back(Ty);
1140 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1141 const TargetInfo *AuxTarget) {
1142 assert((!this->Target || this->Target == &Target) &&
1143 "Incorrect target reinitialization");
1144 assert(VoidTy.isNull() && "Context reinitialized?");
1146 this->Target = &Target;
1147 this->AuxTarget = AuxTarget;
1149 ABI.reset(createCXXABI(Target));
1150 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1151 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1154 InitBuiltinType(VoidTy, BuiltinType::Void);
1157 InitBuiltinType(BoolTy, BuiltinType::Bool);
1159 if (LangOpts.CharIsSigned)
1160 InitBuiltinType(CharTy, BuiltinType::Char_S);
1162 InitBuiltinType(CharTy, BuiltinType::Char_U);
1164 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1165 InitBuiltinType(ShortTy, BuiltinType::Short);
1166 InitBuiltinType(IntTy, BuiltinType::Int);
1167 InitBuiltinType(LongTy, BuiltinType::Long);
1168 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1171 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1172 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1173 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1174 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1175 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1178 InitBuiltinType(FloatTy, BuiltinType::Float);
1179 InitBuiltinType(DoubleTy, BuiltinType::Double);
1180 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1182 // GNU extension, __float128 for IEEE quadruple precision
1183 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1185 // C11 extension ISO/IEC TS 18661-3
1186 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1188 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1189 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1190 InitBuiltinType(AccumTy, BuiltinType::Accum);
1191 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1192 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1193 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1194 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1195 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1196 InitBuiltinType(FractTy, BuiltinType::Fract);
1197 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1198 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1199 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1200 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1201 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1202 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1203 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1204 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1205 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1206 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1207 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1208 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1209 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1210 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1211 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1212 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1214 // GNU extension, 128-bit integers.
1215 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1216 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1219 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1220 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1221 else // -fshort-wchar makes wchar_t be unsigned.
1222 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1223 if (LangOpts.CPlusPlus && LangOpts.WChar)
1224 WideCharTy = WCharTy;
1226 // C99 (or C++ using -fno-wchar).
1227 WideCharTy = getFromTargetType(Target.getWCharType());
1230 WIntTy = getFromTargetType(Target.getWIntType());
1233 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1235 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1236 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1238 Char16Ty = getFromTargetType(Target.getChar16Type());
1240 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1241 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1243 Char32Ty = getFromTargetType(Target.getChar32Type());
1245 // Placeholder type for type-dependent expressions whose type is
1246 // completely unknown. No code should ever check a type against
1247 // DependentTy and users should never see it; however, it is here to
1248 // help diagnose failures to properly check for type-dependent
1250 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1252 // Placeholder type for functions.
1253 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1255 // Placeholder type for bound members.
1256 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1258 // Placeholder type for pseudo-objects.
1259 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1261 // "any" type; useful for debugger-like clients.
1262 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1264 // Placeholder type for unbridged ARC casts.
1265 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1267 // Placeholder type for builtin functions.
1268 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1270 // Placeholder type for OMP array sections.
1271 if (LangOpts.OpenMP)
1272 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1275 FloatComplexTy = getComplexType(FloatTy);
1276 DoubleComplexTy = getComplexType(DoubleTy);
1277 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1278 Float128ComplexTy = getComplexType(Float128Ty);
1280 // Builtin types for 'id', 'Class', and 'SEL'.
1281 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1282 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1283 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1285 if (LangOpts.OpenCL) {
1286 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1287 InitBuiltinType(SingletonId, BuiltinType::Id);
1288 #include "clang/Basic/OpenCLImageTypes.def"
1290 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1291 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1292 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1293 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1294 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1296 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1297 InitBuiltinType(Id##Ty, BuiltinType::Id);
1298 #include "clang/Basic/OpenCLExtensionTypes.def"
1301 // Builtin type for __objc_yes and __objc_no
1302 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1303 SignedCharTy : BoolTy);
1305 ObjCConstantStringType = QualType();
1307 ObjCSuperType = QualType();
1310 if (LangOpts.OpenCLVersion >= 200) {
1311 auto Q = VoidTy.getQualifiers();
1312 Q.setAddressSpace(LangAS::opencl_generic);
1313 VoidPtrTy = getPointerType(getCanonicalType(
1314 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1316 VoidPtrTy = getPointerType(VoidTy);
1319 // nullptr type (C++0x 2.14.7)
1320 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1322 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1323 InitBuiltinType(HalfTy, BuiltinType::Half);
1325 // Builtin type used to help define __builtin_va_list.
1326 VaListTagDecl = nullptr;
1329 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1330 return SourceMgr.getDiagnostics();
1333 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1334 AttrVec *&Result = DeclAttrs[D];
1336 void *Mem = Allocate(sizeof(AttrVec));
1337 Result = new (Mem) AttrVec;
1343 /// Erase the attributes corresponding to the given declaration.
1344 void ASTContext::eraseDeclAttrs(const Decl *D) {
1345 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1346 if (Pos != DeclAttrs.end()) {
1347 Pos->second->~AttrVec();
1348 DeclAttrs.erase(Pos);
1353 MemberSpecializationInfo *
1354 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1355 assert(Var->isStaticDataMember() && "Not a static data member");
1356 return getTemplateOrSpecializationInfo(Var)
1357 .dyn_cast<MemberSpecializationInfo *>();
1360 ASTContext::TemplateOrSpecializationInfo
1361 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1362 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1363 TemplateOrInstantiation.find(Var);
1364 if (Pos == TemplateOrInstantiation.end())
1371 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1372 TemplateSpecializationKind TSK,
1373 SourceLocation PointOfInstantiation) {
1374 assert(Inst->isStaticDataMember() && "Not a static data member");
1375 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1376 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1377 Tmpl, TSK, PointOfInstantiation));
1381 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1382 TemplateOrSpecializationInfo TSI) {
1383 assert(!TemplateOrInstantiation[Inst] &&
1384 "Already noted what the variable was instantiated from");
1385 TemplateOrInstantiation[Inst] = TSI;
1389 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1390 auto Pos = InstantiatedFromUsingDecl.find(UUD);
1391 if (Pos == InstantiatedFromUsingDecl.end())
1398 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1399 assert((isa<UsingDecl>(Pattern) ||
1400 isa<UnresolvedUsingValueDecl>(Pattern) ||
1401 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1402 "pattern decl is not a using decl");
1403 assert((isa<UsingDecl>(Inst) ||
1404 isa<UnresolvedUsingValueDecl>(Inst) ||
1405 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1406 "instantiation did not produce a using decl");
1407 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1408 InstantiatedFromUsingDecl[Inst] = Pattern;
1412 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1413 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1414 = InstantiatedFromUsingShadowDecl.find(Inst);
1415 if (Pos == InstantiatedFromUsingShadowDecl.end())
1422 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1423 UsingShadowDecl *Pattern) {
1424 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1425 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1428 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1429 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1430 = InstantiatedFromUnnamedFieldDecl.find(Field);
1431 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1437 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1439 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1440 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1441 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1442 "Already noted what unnamed field was instantiated from");
1444 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1447 ASTContext::overridden_cxx_method_iterator
1448 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1449 return overridden_methods(Method).begin();
1452 ASTContext::overridden_cxx_method_iterator
1453 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1454 return overridden_methods(Method).end();
1458 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1459 auto Range = overridden_methods(Method);
1460 return Range.end() - Range.begin();
1463 ASTContext::overridden_method_range
1464 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1465 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1466 OverriddenMethods.find(Method->getCanonicalDecl());
1467 if (Pos == OverriddenMethods.end())
1468 return overridden_method_range(nullptr, nullptr);
1469 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1472 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1473 const CXXMethodDecl *Overridden) {
1474 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1475 OverriddenMethods[Method].push_back(Overridden);
1478 void ASTContext::getOverriddenMethods(
1480 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1483 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1484 Overridden.append(overridden_methods_begin(CXXMethod),
1485 overridden_methods_end(CXXMethod));
1489 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1493 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1494 Method->getOverriddenMethods(OverDecls);
1495 Overridden.append(OverDecls.begin(), OverDecls.end());
1498 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1499 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1500 assert(!Import->isFromASTFile() && "Non-local import declaration");
1501 if (!FirstLocalImport) {
1502 FirstLocalImport = Import;
1503 LastLocalImport = Import;
1507 LastLocalImport->NextLocalImport = Import;
1508 LastLocalImport = Import;
1511 //===----------------------------------------------------------------------===//
1512 // Type Sizing and Analysis
1513 //===----------------------------------------------------------------------===//
1515 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1516 /// scalar floating point type.
1517 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1518 const auto *BT = T->getAs<BuiltinType>();
1519 assert(BT && "Not a floating point type!");
1520 switch (BT->getKind()) {
1521 default: llvm_unreachable("Not a floating point type!");
1522 case BuiltinType::Float16:
1523 case BuiltinType::Half:
1524 return Target->getHalfFormat();
1525 case BuiltinType::Float: return Target->getFloatFormat();
1526 case BuiltinType::Double: return Target->getDoubleFormat();
1527 case BuiltinType::LongDouble:
1528 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1529 return AuxTarget->getLongDoubleFormat();
1530 return Target->getLongDoubleFormat();
1531 case BuiltinType::Float128:
1532 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1533 return AuxTarget->getFloat128Format();
1534 return Target->getFloat128Format();
1538 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1539 unsigned Align = Target->getCharWidth();
1541 bool UseAlignAttrOnly = false;
1542 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1543 Align = AlignFromAttr;
1545 // __attribute__((aligned)) can increase or decrease alignment
1546 // *except* on a struct or struct member, where it only increases
1547 // alignment unless 'packed' is also specified.
1549 // It is an error for alignas to decrease alignment, so we can
1550 // ignore that possibility; Sema should diagnose it.
1551 if (isa<FieldDecl>(D)) {
1552 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1553 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1555 UseAlignAttrOnly = true;
1558 else if (isa<FieldDecl>(D))
1560 D->hasAttr<PackedAttr>() ||
1561 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1563 // If we're using the align attribute only, just ignore everything
1564 // else about the declaration and its type.
1565 if (UseAlignAttrOnly) {
1567 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1568 QualType T = VD->getType();
1569 if (const auto *RT = T->getAs<ReferenceType>()) {
1571 T = RT->getPointeeType();
1573 T = getPointerType(RT->getPointeeType());
1575 QualType BaseT = getBaseElementType(T);
1576 if (T->isFunctionType())
1577 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1578 else if (!BaseT->isIncompleteType()) {
1579 // Adjust alignments of declarations with array type by the
1580 // large-array alignment on the target.
1581 if (const ArrayType *arrayType = getAsArrayType(T)) {
1582 unsigned MinWidth = Target->getLargeArrayMinWidth();
1583 if (!ForAlignof && MinWidth) {
1584 if (isa<VariableArrayType>(arrayType))
1585 Align = std::max(Align, Target->getLargeArrayAlign());
1586 else if (isa<ConstantArrayType>(arrayType) &&
1587 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1588 Align = std::max(Align, Target->getLargeArrayAlign());
1591 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1592 if (BaseT.getQualifiers().hasUnaligned())
1593 Align = Target->getCharWidth();
1594 if (const auto *VD = dyn_cast<VarDecl>(D)) {
1595 if (VD->hasGlobalStorage() && !ForAlignof) {
1596 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1597 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1602 // Fields can be subject to extra alignment constraints, like if
1603 // the field is packed, the struct is packed, or the struct has a
1604 // a max-field-alignment constraint (#pragma pack). So calculate
1605 // the actual alignment of the field within the struct, and then
1606 // (as we're expected to) constrain that by the alignment of the type.
1607 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1608 const RecordDecl *Parent = Field->getParent();
1609 // We can only produce a sensible answer if the record is valid.
1610 if (!Parent->isInvalidDecl()) {
1611 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1613 // Start with the record's overall alignment.
1614 unsigned FieldAlign = toBits(Layout.getAlignment());
1616 // Use the GCD of that and the offset within the record.
1617 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1619 // Alignment is always a power of 2, so the GCD will be a power of 2,
1620 // which means we get to do this crazy thing instead of Euclid's.
1621 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1622 if (LowBitOfOffset < FieldAlign)
1623 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1626 Align = std::min(Align, FieldAlign);
1631 return toCharUnitsFromBits(Align);
1634 // getTypeInfoDataSizeInChars - Return the size of a type, in
1635 // chars. If the type is a record, its data size is returned. This is
1636 // the size of the memcpy that's performed when assigning this type
1637 // using a trivial copy/move assignment operator.
1638 std::pair<CharUnits, CharUnits>
1639 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1640 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1642 // In C++, objects can sometimes be allocated into the tail padding
1643 // of a base-class subobject. We decide whether that's possible
1644 // during class layout, so here we can just trust the layout results.
1645 if (getLangOpts().CPlusPlus) {
1646 if (const auto *RT = T->getAs<RecordType>()) {
1647 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1648 sizeAndAlign.first = layout.getDataSize();
1652 return sizeAndAlign;
1655 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1656 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1657 std::pair<CharUnits, CharUnits>
1658 static getConstantArrayInfoInChars(const ASTContext &Context,
1659 const ConstantArrayType *CAT) {
1660 std::pair<CharUnits, CharUnits> EltInfo =
1661 Context.getTypeInfoInChars(CAT->getElementType());
1662 uint64_t Size = CAT->getSize().getZExtValue();
1663 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1664 (uint64_t)(-1)/Size) &&
1665 "Overflow in array type char size evaluation");
1666 uint64_t Width = EltInfo.first.getQuantity() * Size;
1667 unsigned Align = EltInfo.second.getQuantity();
1668 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1669 Context.getTargetInfo().getPointerWidth(0) == 64)
1670 Width = llvm::alignTo(Width, Align);
1671 return std::make_pair(CharUnits::fromQuantity(Width),
1672 CharUnits::fromQuantity(Align));
1675 std::pair<CharUnits, CharUnits>
1676 ASTContext::getTypeInfoInChars(const Type *T) const {
1677 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1678 return getConstantArrayInfoInChars(*this, CAT);
1679 TypeInfo Info = getTypeInfo(T);
1680 return std::make_pair(toCharUnitsFromBits(Info.Width),
1681 toCharUnitsFromBits(Info.Align));
1684 std::pair<CharUnits, CharUnits>
1685 ASTContext::getTypeInfoInChars(QualType T) const {
1686 return getTypeInfoInChars(T.getTypePtr());
1689 bool ASTContext::isAlignmentRequired(const Type *T) const {
1690 return getTypeInfo(T).AlignIsRequired;
1693 bool ASTContext::isAlignmentRequired(QualType T) const {
1694 return isAlignmentRequired(T.getTypePtr());
1697 unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1698 // An alignment on a typedef overrides anything else.
1699 if (const auto *TT = T->getAs<TypedefType>())
1700 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1703 // If we have an (array of) complete type, we're done.
1704 T = getBaseElementType(T);
1705 if (!T->isIncompleteType())
1706 return getTypeAlign(T);
1708 // If we had an array type, its element type might be a typedef
1709 // type with an alignment attribute.
1710 if (const auto *TT = T->getAs<TypedefType>())
1711 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1714 // Otherwise, see if the declaration of the type had an attribute.
1715 if (const auto *TT = T->getAs<TagType>())
1716 return TT->getDecl()->getMaxAlignment();
1721 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1722 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1723 if (I != MemoizedTypeInfo.end())
1726 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1727 TypeInfo TI = getTypeInfoImpl(T);
1728 MemoizedTypeInfo[T] = TI;
1732 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1733 /// method does not work on incomplete types.
1735 /// FIXME: Pointers into different addr spaces could have different sizes and
1736 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1737 /// should take a QualType, &c.
1738 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1741 bool AlignIsRequired = false;
1743 switch (T->getTypeClass()) {
1744 #define TYPE(Class, Base)
1745 #define ABSTRACT_TYPE(Class, Base)
1746 #define NON_CANONICAL_TYPE(Class, Base)
1747 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1748 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1750 assert(!T->isDependentType() && "should not see dependent types here"); \
1751 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1752 #include "clang/AST/TypeNodes.def"
1753 llvm_unreachable("Should not see dependent types");
1755 case Type::FunctionNoProto:
1756 case Type::FunctionProto:
1757 // GCC extension: alignof(function) = 32 bits
1762 case Type::IncompleteArray:
1763 case Type::VariableArray:
1765 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1768 case Type::ConstantArray: {
1769 const auto *CAT = cast<ConstantArrayType>(T);
1771 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1772 uint64_t Size = CAT->getSize().getZExtValue();
1773 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1774 "Overflow in array type bit size evaluation");
1775 Width = EltInfo.Width * Size;
1776 Align = EltInfo.Align;
1777 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1778 getTargetInfo().getPointerWidth(0) == 64)
1779 Width = llvm::alignTo(Width, Align);
1782 case Type::ExtVector:
1783 case Type::Vector: {
1784 const auto *VT = cast<VectorType>(T);
1785 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1786 Width = EltInfo.Width * VT->getNumElements();
1788 // If the alignment is not a power of 2, round up to the next power of 2.
1789 // This happens for non-power-of-2 length vectors.
1790 if (Align & (Align-1)) {
1791 Align = llvm::NextPowerOf2(Align);
1792 Width = llvm::alignTo(Width, Align);
1794 // Adjust the alignment based on the target max.
1795 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1796 if (TargetVectorAlign && TargetVectorAlign < Align)
1797 Align = TargetVectorAlign;
1802 switch (cast<BuiltinType>(T)->getKind()) {
1803 default: llvm_unreachable("Unknown builtin type!");
1804 case BuiltinType::Void:
1805 // GCC extension: alignof(void) = 8 bits.
1809 case BuiltinType::Bool:
1810 Width = Target->getBoolWidth();
1811 Align = Target->getBoolAlign();
1813 case BuiltinType::Char_S:
1814 case BuiltinType::Char_U:
1815 case BuiltinType::UChar:
1816 case BuiltinType::SChar:
1817 case BuiltinType::Char8:
1818 Width = Target->getCharWidth();
1819 Align = Target->getCharAlign();
1821 case BuiltinType::WChar_S:
1822 case BuiltinType::WChar_U:
1823 Width = Target->getWCharWidth();
1824 Align = Target->getWCharAlign();
1826 case BuiltinType::Char16:
1827 Width = Target->getChar16Width();
1828 Align = Target->getChar16Align();
1830 case BuiltinType::Char32:
1831 Width = Target->getChar32Width();
1832 Align = Target->getChar32Align();
1834 case BuiltinType::UShort:
1835 case BuiltinType::Short:
1836 Width = Target->getShortWidth();
1837 Align = Target->getShortAlign();
1839 case BuiltinType::UInt:
1840 case BuiltinType::Int:
1841 Width = Target->getIntWidth();
1842 Align = Target->getIntAlign();
1844 case BuiltinType::ULong:
1845 case BuiltinType::Long:
1846 Width = Target->getLongWidth();
1847 Align = Target->getLongAlign();
1849 case BuiltinType::ULongLong:
1850 case BuiltinType::LongLong:
1851 Width = Target->getLongLongWidth();
1852 Align = Target->getLongLongAlign();
1854 case BuiltinType::Int128:
1855 case BuiltinType::UInt128:
1857 Align = 128; // int128_t is 128-bit aligned on all targets.
1859 case BuiltinType::ShortAccum:
1860 case BuiltinType::UShortAccum:
1861 case BuiltinType::SatShortAccum:
1862 case BuiltinType::SatUShortAccum:
1863 Width = Target->getShortAccumWidth();
1864 Align = Target->getShortAccumAlign();
1866 case BuiltinType::Accum:
1867 case BuiltinType::UAccum:
1868 case BuiltinType::SatAccum:
1869 case BuiltinType::SatUAccum:
1870 Width = Target->getAccumWidth();
1871 Align = Target->getAccumAlign();
1873 case BuiltinType::LongAccum:
1874 case BuiltinType::ULongAccum:
1875 case BuiltinType::SatLongAccum:
1876 case BuiltinType::SatULongAccum:
1877 Width = Target->getLongAccumWidth();
1878 Align = Target->getLongAccumAlign();
1880 case BuiltinType::ShortFract:
1881 case BuiltinType::UShortFract:
1882 case BuiltinType::SatShortFract:
1883 case BuiltinType::SatUShortFract:
1884 Width = Target->getShortFractWidth();
1885 Align = Target->getShortFractAlign();
1887 case BuiltinType::Fract:
1888 case BuiltinType::UFract:
1889 case BuiltinType::SatFract:
1890 case BuiltinType::SatUFract:
1891 Width = Target->getFractWidth();
1892 Align = Target->getFractAlign();
1894 case BuiltinType::LongFract:
1895 case BuiltinType::ULongFract:
1896 case BuiltinType::SatLongFract:
1897 case BuiltinType::SatULongFract:
1898 Width = Target->getLongFractWidth();
1899 Align = Target->getLongFractAlign();
1901 case BuiltinType::Float16:
1902 case BuiltinType::Half:
1903 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
1904 !getLangOpts().OpenMPIsDevice) {
1905 Width = Target->getHalfWidth();
1906 Align = Target->getHalfAlign();
1908 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1909 "Expected OpenMP device compilation.");
1910 Width = AuxTarget->getHalfWidth();
1911 Align = AuxTarget->getHalfAlign();
1914 case BuiltinType::Float:
1915 Width = Target->getFloatWidth();
1916 Align = Target->getFloatAlign();
1918 case BuiltinType::Double:
1919 Width = Target->getDoubleWidth();
1920 Align = Target->getDoubleAlign();
1922 case BuiltinType::LongDouble:
1923 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1924 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
1925 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
1926 Width = AuxTarget->getLongDoubleWidth();
1927 Align = AuxTarget->getLongDoubleAlign();
1929 Width = Target->getLongDoubleWidth();
1930 Align = Target->getLongDoubleAlign();
1933 case BuiltinType::Float128:
1934 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
1935 !getLangOpts().OpenMPIsDevice) {
1936 Width = Target->getFloat128Width();
1937 Align = Target->getFloat128Align();
1939 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1940 "Expected OpenMP device compilation.");
1941 Width = AuxTarget->getFloat128Width();
1942 Align = AuxTarget->getFloat128Align();
1945 case BuiltinType::NullPtr:
1946 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1947 Align = Target->getPointerAlign(0); // == sizeof(void*)
1949 case BuiltinType::ObjCId:
1950 case BuiltinType::ObjCClass:
1951 case BuiltinType::ObjCSel:
1952 Width = Target->getPointerWidth(0);
1953 Align = Target->getPointerAlign(0);
1955 case BuiltinType::OCLSampler:
1956 case BuiltinType::OCLEvent:
1957 case BuiltinType::OCLClkEvent:
1958 case BuiltinType::OCLQueue:
1959 case BuiltinType::OCLReserveID:
1960 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1961 case BuiltinType::Id:
1962 #include "clang/Basic/OpenCLImageTypes.def"
1963 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1964 case BuiltinType::Id:
1965 #include "clang/Basic/OpenCLExtensionTypes.def"
1966 AS = getTargetAddressSpace(
1967 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
1968 Width = Target->getPointerWidth(AS);
1969 Align = Target->getPointerAlign(AS);
1973 case Type::ObjCObjectPointer:
1974 Width = Target->getPointerWidth(0);
1975 Align = Target->getPointerAlign(0);
1977 case Type::BlockPointer:
1978 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
1979 Width = Target->getPointerWidth(AS);
1980 Align = Target->getPointerAlign(AS);
1982 case Type::LValueReference:
1983 case Type::RValueReference:
1984 // alignof and sizeof should never enter this code path here, so we go
1985 // the pointer route.
1986 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
1987 Width = Target->getPointerWidth(AS);
1988 Align = Target->getPointerAlign(AS);
1991 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1992 Width = Target->getPointerWidth(AS);
1993 Align = Target->getPointerAlign(AS);
1995 case Type::MemberPointer: {
1996 const auto *MPT = cast<MemberPointerType>(T);
1997 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2002 case Type::Complex: {
2003 // Complex types have the same alignment as their elements, but twice the
2005 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2006 Width = EltInfo.Width * 2;
2007 Align = EltInfo.Align;
2010 case Type::ObjCObject:
2011 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2012 case Type::Adjusted:
2014 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2015 case Type::ObjCInterface: {
2016 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2017 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2018 Width = toBits(Layout.getSize());
2019 Align = toBits(Layout.getAlignment());
2024 const auto *TT = cast<TagType>(T);
2026 if (TT->getDecl()->isInvalidDecl()) {
2032 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2033 const EnumDecl *ED = ET->getDecl();
2035 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2036 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2037 Info.Align = AttrAlign;
2038 Info.AlignIsRequired = true;
2043 const auto *RT = cast<RecordType>(TT);
2044 const RecordDecl *RD = RT->getDecl();
2045 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2046 Width = toBits(Layout.getSize());
2047 Align = toBits(Layout.getAlignment());
2048 AlignIsRequired = RD->hasAttr<AlignedAttr>();
2052 case Type::SubstTemplateTypeParm:
2053 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2054 getReplacementType().getTypePtr());
2057 case Type::DeducedTemplateSpecialization: {
2058 const auto *A = cast<DeducedType>(T);
2059 assert(!A->getDeducedType().isNull() &&
2060 "cannot request the size of an undeduced or dependent auto type");
2061 return getTypeInfo(A->getDeducedType().getTypePtr());
2065 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2067 case Type::MacroQualified:
2069 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2071 case Type::ObjCTypeParam:
2072 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2074 case Type::Typedef: {
2075 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2076 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2077 // If the typedef has an aligned attribute on it, it overrides any computed
2078 // alignment we have. This violates the GCC documentation (which says that
2079 // attribute(aligned) can only round up) but matches its implementation.
2080 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2082 AlignIsRequired = true;
2085 AlignIsRequired = Info.AlignIsRequired;
2091 case Type::Elaborated:
2092 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2094 case Type::Attributed:
2096 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2098 case Type::Atomic: {
2099 // Start with the base type information.
2100 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2105 // An otherwise zero-sized type should still generate an
2106 // atomic operation.
2107 Width = Target->getCharWidth();
2109 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2110 // If the size of the type doesn't exceed the platform's max
2111 // atomic promotion width, make the size and alignment more
2112 // favorable to atomic operations:
2114 // Round the size up to a power of 2.
2115 if (!llvm::isPowerOf2_64(Width))
2116 Width = llvm::NextPowerOf2(Width);
2118 // Set the alignment equal to the size.
2119 Align = static_cast<unsigned>(Width);
2125 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2126 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2130 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2131 return TypeInfo(Width, Align, AlignIsRequired);
2134 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2135 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2136 if (I != MemoizedUnadjustedAlign.end())
2139 unsigned UnadjustedAlign;
2140 if (const auto *RT = T->getAs<RecordType>()) {
2141 const RecordDecl *RD = RT->getDecl();
2142 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2143 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2144 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2145 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2146 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2148 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2151 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2152 return UnadjustedAlign;
2155 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2156 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2157 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2158 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2159 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2160 getTargetInfo().getABI() == "elfv1-qpx" &&
2161 T->isSpecificBuiltinType(BuiltinType::Double))
2166 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2167 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2168 return CharUnits::fromQuantity(BitSize / getCharWidth());
2171 /// toBits - Convert a size in characters to a size in characters.
2172 int64_t ASTContext::toBits(CharUnits CharSize) const {
2173 return CharSize.getQuantity() * getCharWidth();
2176 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2177 /// This method does not work on incomplete types.
2178 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2179 return getTypeInfoInChars(T).first;
2181 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2182 return getTypeInfoInChars(T).first;
2185 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2186 /// characters. This method does not work on incomplete types.
2187 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2188 return toCharUnitsFromBits(getTypeAlign(T));
2190 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2191 return toCharUnitsFromBits(getTypeAlign(T));
2194 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2195 /// type, in characters, before alignment adustments. This method does
2196 /// not work on incomplete types.
2197 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2198 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2200 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2201 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2204 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2205 /// type for the current target in bits. This can be different than the ABI
2206 /// alignment in cases where it is beneficial for performance to overalign
2208 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2209 TypeInfo TI = getTypeInfo(T);
2210 unsigned ABIAlign = TI.Align;
2212 T = T->getBaseElementTypeUnsafe();
2214 // The preferred alignment of member pointers is that of a pointer.
2215 if (T->isMemberPointerType())
2216 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2218 if (!Target->allowsLargerPreferedTypeAlignment())
2221 // Double and long long should be naturally aligned if possible.
2222 if (const auto *CT = T->getAs<ComplexType>())
2223 T = CT->getElementType().getTypePtr();
2224 if (const auto *ET = T->getAs<EnumType>())
2225 T = ET->getDecl()->getIntegerType().getTypePtr();
2226 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2227 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2228 T->isSpecificBuiltinType(BuiltinType::ULongLong))
2229 // Don't increase the alignment if an alignment attribute was specified on a
2230 // typedef declaration.
2231 if (!TI.AlignIsRequired)
2232 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2237 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2238 /// for __attribute__((aligned)) on this target, to be used if no alignment
2239 /// value is specified.
2240 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2241 return getTargetInfo().getDefaultAlignForAttributeAligned();
2244 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2245 /// to a global variable of the specified type.
2246 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2247 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2248 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
2251 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2252 /// should be given to a global variable of the specified type.
2253 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2254 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2257 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2258 CharUnits Offset = CharUnits::Zero();
2259 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2260 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2261 Offset += Layout->getBaseClassOffset(Base);
2262 Layout = &getASTRecordLayout(Base);
2267 /// DeepCollectObjCIvars -
2268 /// This routine first collects all declared, but not synthesized, ivars in
2269 /// super class and then collects all ivars, including those synthesized for
2270 /// current class. This routine is used for implementation of current class
2271 /// when all ivars, declared and synthesized are known.
2272 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2274 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2275 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2276 DeepCollectObjCIvars(SuperClass, false, Ivars);
2278 for (const auto *I : OI->ivars())
2281 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2282 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2283 Iv= Iv->getNextIvar())
2284 Ivars.push_back(Iv);
2288 /// CollectInheritedProtocols - Collect all protocols in current class and
2289 /// those inherited by it.
2290 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2291 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2292 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2293 // We can use protocol_iterator here instead of
2294 // all_referenced_protocol_iterator since we are walking all categories.
2295 for (auto *Proto : OI->all_referenced_protocols()) {
2296 CollectInheritedProtocols(Proto, Protocols);
2299 // Categories of this Interface.
2300 for (const auto *Cat : OI->visible_categories())
2301 CollectInheritedProtocols(Cat, Protocols);
2303 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2305 CollectInheritedProtocols(SD, Protocols);
2306 SD = SD->getSuperClass();
2308 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2309 for (auto *Proto : OC->protocols()) {
2310 CollectInheritedProtocols(Proto, Protocols);
2312 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2313 // Insert the protocol.
2314 if (!Protocols.insert(
2315 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2318 for (auto *Proto : OP->protocols())
2319 CollectInheritedProtocols(Proto, Protocols);
2323 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2324 const RecordDecl *RD) {
2325 assert(RD->isUnion() && "Must be union type");
2326 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2328 for (const auto *Field : RD->fields()) {
2329 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2331 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2332 if (FieldSize != UnionSize)
2335 return !RD->field_empty();
2338 static bool isStructEmpty(QualType Ty) {
2339 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2341 if (!RD->field_empty())
2344 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2345 return ClassDecl->isEmpty();
2350 static llvm::Optional<int64_t>
2351 structHasUniqueObjectRepresentations(const ASTContext &Context,
2352 const RecordDecl *RD) {
2353 assert(!RD->isUnion() && "Must be struct/class type");
2354 const auto &Layout = Context.getASTRecordLayout(RD);
2356 int64_t CurOffsetInBits = 0;
2357 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2358 if (ClassDecl->isDynamicClass())
2361 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2362 for (const auto Base : ClassDecl->bases()) {
2363 // Empty types can be inherited from, and non-empty types can potentially
2364 // have tail padding, so just make sure there isn't an error.
2365 if (!isStructEmpty(Base.getType())) {
2366 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2367 Context, Base.getType()->getAs<RecordType>()->getDecl());
2370 Bases.emplace_back(Base.getType(), Size.getValue());
2374 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2375 const std::pair<QualType, int64_t> &R) {
2376 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2377 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2380 for (const auto Base : Bases) {
2381 int64_t BaseOffset = Context.toBits(
2382 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2383 int64_t BaseSize = Base.second;
2384 if (BaseOffset != CurOffsetInBits)
2386 CurOffsetInBits = BaseOffset + BaseSize;
2390 for (const auto *Field : RD->fields()) {
2391 if (!Field->getType()->isReferenceType() &&
2392 !Context.hasUniqueObjectRepresentations(Field->getType()))
2395 int64_t FieldSizeInBits =
2396 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2397 if (Field->isBitField()) {
2398 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2400 if (BitfieldSize > FieldSizeInBits)
2402 FieldSizeInBits = BitfieldSize;
2405 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2407 if (FieldOffsetInBits != CurOffsetInBits)
2410 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2413 return CurOffsetInBits;
2416 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2417 // C++17 [meta.unary.prop]:
2418 // The predicate condition for a template specialization
2419 // has_unique_object_representations<T> shall be
2420 // satisfied if and only if:
2421 // (9.1) - T is trivially copyable, and
2422 // (9.2) - any two objects of type T with the same value have the same
2423 // object representation, where two objects
2424 // of array or non-union class type are considered to have the same value
2425 // if their respective sequences of
2426 // direct subobjects have the same values, and two objects of union type
2427 // are considered to have the same
2428 // value if they have the same active member and the corresponding members
2429 // have the same value.
2430 // The set of scalar types for which this condition holds is
2431 // implementation-defined. [ Note: If a type has padding
2432 // bits, the condition does not hold; otherwise, the condition holds true
2433 // for unsigned integral types. -- end note ]
2434 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2436 // Arrays are unique only if their element type is unique.
2437 if (Ty->isArrayType())
2438 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2440 // (9.1) - T is trivially copyable...
2441 if (!Ty.isTriviallyCopyableType(*this))
2444 // All integrals and enums are unique.
2445 if (Ty->isIntegralOrEnumerationType())
2448 // All other pointers are unique.
2449 if (Ty->isPointerType())
2452 if (Ty->isMemberPointerType()) {
2453 const auto *MPT = Ty->getAs<MemberPointerType>();
2454 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2457 if (Ty->isRecordType()) {
2458 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2460 if (Record->isInvalidDecl())
2463 if (Record->isUnion())
2464 return unionHasUniqueObjectRepresentations(*this, Record);
2466 Optional<int64_t> StructSize =
2467 structHasUniqueObjectRepresentations(*this, Record);
2469 return StructSize &&
2470 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2473 // FIXME: More cases to handle here (list by rsmith):
2474 // vectors (careful about, eg, vector of 3 foo)
2475 // _Complex int and friends
2477 // Obj-C block pointers
2478 // Obj-C object pointers
2479 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2480 // clk_event_t, queue_t, reserve_id_t)
2481 // There're also Obj-C class types and the Obj-C selector type, but I think it
2482 // makes sense for those to return false here.
2487 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2489 // Count ivars declared in class extension.
2490 for (const auto *Ext : OI->known_extensions())
2491 count += Ext->ivar_size();
2493 // Count ivar defined in this class's implementation. This
2494 // includes synthesized ivars.
2495 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2496 count += ImplDecl->ivar_size();
2501 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2505 // nullptr_t is always treated as null.
2506 if (E->getType()->isNullPtrType()) return true;
2508 if (E->getType()->isAnyPointerType() &&
2509 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2510 Expr::NPC_ValueDependentIsNull))
2513 // Unfortunately, __null has type 'int'.
2514 if (isa<GNUNullExpr>(E)) return true;
2519 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2521 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2522 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2523 I = ObjCImpls.find(D);
2524 if (I != ObjCImpls.end())
2525 return cast<ObjCImplementationDecl>(I->second);
2529 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2531 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2532 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2533 I = ObjCImpls.find(D);
2534 if (I != ObjCImpls.end())
2535 return cast<ObjCCategoryImplDecl>(I->second);
2539 /// Set the implementation of ObjCInterfaceDecl.
2540 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2541 ObjCImplementationDecl *ImplD) {
2542 assert(IFaceD && ImplD && "Passed null params");
2543 ObjCImpls[IFaceD] = ImplD;
2546 /// Set the implementation of ObjCCategoryDecl.
2547 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2548 ObjCCategoryImplDecl *ImplD) {
2549 assert(CatD && ImplD && "Passed null params");
2550 ObjCImpls[CatD] = ImplD;
2553 const ObjCMethodDecl *
2554 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2555 return ObjCMethodRedecls.lookup(MD);
2558 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2559 const ObjCMethodDecl *Redecl) {
2560 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2561 ObjCMethodRedecls[MD] = Redecl;
2564 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2565 const NamedDecl *ND) const {
2566 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2568 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2569 return CD->getClassInterface();
2570 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2571 return IMD->getClassInterface();
2576 /// Get the copy initialization expression of VarDecl, or nullptr if
2578 ASTContext::BlockVarCopyInit
2579 ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
2580 assert(VD && "Passed null params");
2581 assert(VD->hasAttr<BlocksAttr>() &&
2582 "getBlockVarCopyInits - not __block var");
2583 auto I = BlockVarCopyInits.find(VD);
2584 if (I != BlockVarCopyInits.end())
2586 return {nullptr, false};
2589 /// Set the copy initialization expression of a block var decl.
2590 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2592 assert(VD && CopyExpr && "Passed null params");
2593 assert(VD->hasAttr<BlocksAttr>() &&
2594 "setBlockVarCopyInits - not __block var");
2595 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2598 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2599 unsigned DataSize) const {
2601 DataSize = TypeLoc::getFullDataSizeForType(T);
2603 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2604 "incorrect data size provided to CreateTypeSourceInfo!");
2607 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2608 new (TInfo) TypeSourceInfo(T);
2612 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2613 SourceLocation L) const {
2614 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2615 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2619 const ASTRecordLayout &
2620 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2621 return getObjCLayout(D, nullptr);
2624 const ASTRecordLayout &
2625 ASTContext::getASTObjCImplementationLayout(
2626 const ObjCImplementationDecl *D) const {
2627 return getObjCLayout(D->getClassInterface(), D);
2630 //===----------------------------------------------------------------------===//
2631 // Type creation/memoization methods
2632 //===----------------------------------------------------------------------===//
2635 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2636 unsigned fastQuals = quals.getFastQualifiers();
2637 quals.removeFastQualifiers();
2639 // Check if we've already instantiated this type.
2640 llvm::FoldingSetNodeID ID;
2641 ExtQuals::Profile(ID, baseType, quals);
2642 void *insertPos = nullptr;
2643 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2644 assert(eq->getQualifiers() == quals);
2645 return QualType(eq, fastQuals);
2648 // If the base type is not canonical, make the appropriate canonical type.
2650 if (!baseType->isCanonicalUnqualified()) {
2651 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2652 canonSplit.Quals.addConsistentQualifiers(quals);
2653 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2655 // Re-find the insert position.
2656 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2659 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2660 ExtQualNodes.InsertNode(eq, insertPos);
2661 return QualType(eq, fastQuals);
2664 QualType ASTContext::getAddrSpaceQualType(QualType T,
2665 LangAS AddressSpace) const {
2666 QualType CanT = getCanonicalType(T);
2667 if (CanT.getAddressSpace() == AddressSpace)
2670 // If we are composing extended qualifiers together, merge together
2671 // into one ExtQuals node.
2672 QualifierCollector Quals;
2673 const Type *TypeNode = Quals.strip(T);
2675 // If this type already has an address space specified, it cannot get
2677 assert(!Quals.hasAddressSpace() &&
2678 "Type cannot be in multiple addr spaces!");
2679 Quals.addAddressSpace(AddressSpace);
2681 return getExtQualType(TypeNode, Quals);
2684 QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2685 // If we are composing extended qualifiers together, merge together
2686 // into one ExtQuals node.
2687 QualifierCollector Quals;
2688 const Type *TypeNode = Quals.strip(T);
2690 // If the qualifier doesn't have an address space just return it.
2691 if (!Quals.hasAddressSpace())
2694 Quals.removeAddressSpace();
2696 // Removal of the address space can mean there are no longer any
2697 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2699 if (Quals.hasNonFastQualifiers())
2700 return getExtQualType(TypeNode, Quals);
2702 return QualType(TypeNode, Quals.getFastQualifiers());
2705 QualType ASTContext::getObjCGCQualType(QualType T,
2706 Qualifiers::GC GCAttr) const {
2707 QualType CanT = getCanonicalType(T);
2708 if (CanT.getObjCGCAttr() == GCAttr)
2711 if (const auto *ptr = T->getAs<PointerType>()) {
2712 QualType Pointee = ptr->getPointeeType();
2713 if (Pointee->isAnyPointerType()) {
2714 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2715 return getPointerType(ResultType);
2719 // If we are composing extended qualifiers together, merge together
2720 // into one ExtQuals node.
2721 QualifierCollector Quals;
2722 const Type *TypeNode = Quals.strip(T);
2724 // If this type already has an ObjCGC specified, it cannot get
2726 assert(!Quals.hasObjCGCAttr() &&
2727 "Type cannot have multiple ObjCGCs!");
2728 Quals.addObjCGCAttr(GCAttr);
2730 return getExtQualType(TypeNode, Quals);
2733 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2734 FunctionType::ExtInfo Info) {
2735 if (T->getExtInfo() == Info)
2739 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2740 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2742 const auto *FPT = cast<FunctionProtoType>(T);
2743 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2745 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2748 return cast<FunctionType>(Result.getTypePtr());
2751 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2752 QualType ResultType) {
2753 FD = FD->getMostRecentDecl();
2755 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
2756 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2757 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2758 if (FunctionDecl *Next = FD->getPreviousDecl())
2763 if (ASTMutationListener *L = getASTMutationListener())
2764 L->DeducedReturnType(FD, ResultType);
2767 /// Get a function type and produce the equivalent function type with the
2768 /// specified exception specification. Type sugar that can be present on a
2769 /// declaration of a function with an exception specification is permitted
2770 /// and preserved. Other type sugar (for instance, typedefs) is not.
2771 QualType ASTContext::getFunctionTypeWithExceptionSpec(
2772 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
2773 // Might have some parens.
2774 if (const auto *PT = dyn_cast<ParenType>(Orig))
2775 return getParenType(
2776 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
2778 // Might be wrapped in a macro qualified type.
2779 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2780 return getMacroQualifiedType(
2781 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2782 MQT->getMacroIdentifier());
2784 // Might have a calling-convention attribute.
2785 if (const auto *AT = dyn_cast<AttributedType>(Orig))
2786 return getAttributedType(
2788 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2789 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
2791 // Anything else must be a function type. Rebuild it with the new exception
2793 const auto *Proto = Orig->getAs<FunctionProtoType>();
2794 return getFunctionType(
2795 Proto->getReturnType(), Proto->getParamTypes(),
2796 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2799 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2801 return hasSameType(T, U) ||
2802 (getLangOpts().CPlusPlus17 &&
2803 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2804 getFunctionTypeWithExceptionSpec(U, EST_None)));
2807 void ASTContext::adjustExceptionSpec(
2808 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2812 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
2813 FD->setType(Updated);
2818 // Update the type in the type source information too.
2819 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2820 // If the type and the type-as-written differ, we may need to update
2821 // the type-as-written too.
2822 if (TSInfo->getType() != FD->getType())
2823 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
2825 // FIXME: When we get proper type location information for exceptions,
2826 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2827 // up the TypeSourceInfo;
2828 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2829 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2830 "TypeLoc size mismatch from updating exception specification");
2831 TSInfo->overrideType(Updated);
2835 /// getComplexType - Return the uniqued reference to the type for a complex
2836 /// number with the specified element type.
2837 QualType ASTContext::getComplexType(QualType T) const {
2838 // Unique pointers, to guarantee there is only one pointer of a particular
2840 llvm::FoldingSetNodeID ID;
2841 ComplexType::Profile(ID, T);
2843 void *InsertPos = nullptr;
2844 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2845 return QualType(CT, 0);
2847 // If the pointee type isn't canonical, this won't be a canonical type either,
2848 // so fill in the canonical type field.
2850 if (!T.isCanonical()) {
2851 Canonical = getComplexType(getCanonicalType(T));
2853 // Get the new insert position for the node we care about.
2854 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2855 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2857 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2858 Types.push_back(New);
2859 ComplexTypes.InsertNode(New, InsertPos);
2860 return QualType(New, 0);
2863 /// getPointerType - Return the uniqued reference to the type for a pointer to
2864 /// the specified type.
2865 QualType ASTContext::getPointerType(QualType T) const {
2866 // Unique pointers, to guarantee there is only one pointer of a particular
2868 llvm::FoldingSetNodeID ID;
2869 PointerType::Profile(ID, T);
2871 void *InsertPos = nullptr;
2872 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2873 return QualType(PT, 0);
2875 // If the pointee type isn't canonical, this won't be a canonical type either,
2876 // so fill in the canonical type field.
2878 if (!T.isCanonical()) {
2879 Canonical = getPointerType(getCanonicalType(T));
2881 // Get the new insert position for the node we care about.
2882 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2883 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2885 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2886 Types.push_back(New);
2887 PointerTypes.InsertNode(New, InsertPos);
2888 return QualType(New, 0);
2891 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2892 llvm::FoldingSetNodeID ID;
2893 AdjustedType::Profile(ID, Orig, New);
2894 void *InsertPos = nullptr;
2895 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2897 return QualType(AT, 0);
2899 QualType Canonical = getCanonicalType(New);
2901 // Get the new insert position for the node we care about.
2902 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2903 assert(!AT && "Shouldn't be in the map!");
2905 AT = new (*this, TypeAlignment)
2906 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2907 Types.push_back(AT);
2908 AdjustedTypes.InsertNode(AT, InsertPos);
2909 return QualType(AT, 0);
2912 QualType ASTContext::getDecayedType(QualType T) const {
2913 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2918 // A declaration of a parameter as "array of type" shall be
2919 // adjusted to "qualified pointer to type", where the type
2920 // qualifiers (if any) are those specified within the [ and ] of
2921 // the array type derivation.
2922 if (T->isArrayType())
2923 Decayed = getArrayDecayedType(T);
2926 // A declaration of a parameter as "function returning type"
2927 // shall be adjusted to "pointer to function returning type", as
2929 if (T->isFunctionType())
2930 Decayed = getPointerType(T);
2932 llvm::FoldingSetNodeID ID;
2933 AdjustedType::Profile(ID, T, Decayed);
2934 void *InsertPos = nullptr;
2935 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2937 return QualType(AT, 0);
2939 QualType Canonical = getCanonicalType(Decayed);
2941 // Get the new insert position for the node we care about.
2942 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2943 assert(!AT && "Shouldn't be in the map!");
2945 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2946 Types.push_back(AT);
2947 AdjustedTypes.InsertNode(AT, InsertPos);
2948 return QualType(AT, 0);
2951 /// getBlockPointerType - Return the uniqued reference to the type for
2952 /// a pointer to the specified block.
2953 QualType ASTContext::getBlockPointerType(QualType T) const {
2954 assert(T->isFunctionType() && "block of function types only");
2955 // Unique pointers, to guarantee there is only one block of a particular
2957 llvm::FoldingSetNodeID ID;
2958 BlockPointerType::Profile(ID, T);
2960 void *InsertPos = nullptr;
2961 if (BlockPointerType *PT =
2962 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2963 return QualType(PT, 0);
2965 // If the block pointee type isn't canonical, this won't be a canonical
2966 // type either so fill in the canonical type field.
2968 if (!T.isCanonical()) {
2969 Canonical = getBlockPointerType(getCanonicalType(T));
2971 // Get the new insert position for the node we care about.
2972 BlockPointerType *NewIP =
2973 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2974 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2976 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2977 Types.push_back(New);
2978 BlockPointerTypes.InsertNode(New, InsertPos);
2979 return QualType(New, 0);
2982 /// getLValueReferenceType - Return the uniqued reference to the type for an
2983 /// lvalue reference to the specified type.
2985 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2986 assert(getCanonicalType(T) != OverloadTy &&
2987 "Unresolved overloaded function type");
2989 // Unique pointers, to guarantee there is only one pointer of a particular
2991 llvm::FoldingSetNodeID ID;
2992 ReferenceType::Profile(ID, T, SpelledAsLValue);
2994 void *InsertPos = nullptr;
2995 if (LValueReferenceType *RT =
2996 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2997 return QualType(RT, 0);
2999 const auto *InnerRef = T->getAs<ReferenceType>();
3001 // If the referencee type isn't canonical, this won't be a canonical type
3002 // either, so fill in the canonical type field.
3004 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3005 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3006 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3008 // Get the new insert position for the node we care about.
3009 LValueReferenceType *NewIP =
3010 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3011 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3014 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3016 Types.push_back(New);
3017 LValueReferenceTypes.InsertNode(New, InsertPos);
3019 return QualType(New, 0);
3022 /// getRValueReferenceType - Return the uniqued reference to the type for an
3023 /// rvalue reference to the specified type.
3024 QualType ASTContext::getRValueReferenceType(QualType T) const {
3025 // Unique pointers, to guarantee there is only one pointer of a particular
3027 llvm::FoldingSetNodeID ID;
3028 ReferenceType::Profile(ID, T, false);
3030 void *InsertPos = nullptr;
3031 if (RValueReferenceType *RT =
3032 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3033 return QualType(RT, 0);
3035 const auto *InnerRef = T->getAs<ReferenceType>();
3037 // If the referencee type isn't canonical, this won't be a canonical type
3038 // either, so fill in the canonical type field.
3040 if (InnerRef || !T.isCanonical()) {
3041 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3042 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3044 // Get the new insert position for the node we care about.
3045 RValueReferenceType *NewIP =
3046 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3047 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3050 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3051 Types.push_back(New);
3052 RValueReferenceTypes.InsertNode(New, InsertPos);
3053 return QualType(New, 0);
3056 /// getMemberPointerType - Return the uniqued reference to the type for a
3057 /// member pointer to the specified type, in the specified class.
3058 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3059 // Unique pointers, to guarantee there is only one pointer of a particular
3061 llvm::FoldingSetNodeID ID;
3062 MemberPointerType::Profile(ID, T, Cls);
3064 void *InsertPos = nullptr;
3065 if (MemberPointerType *PT =
3066 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3067 return QualType(PT, 0);
3069 // If the pointee or class type isn't canonical, this won't be a canonical
3070 // type either, so fill in the canonical type field.
3072 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3073 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3075 // Get the new insert position for the node we care about.
3076 MemberPointerType *NewIP =
3077 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3078 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3080 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3081 Types.push_back(New);
3082 MemberPointerTypes.InsertNode(New, InsertPos);
3083 return QualType(New, 0);
3086 /// getConstantArrayType - Return the unique reference to the type for an
3087 /// array of the specified element type.
3088 QualType ASTContext::getConstantArrayType(QualType EltTy,
3089 const llvm::APInt &ArySizeIn,
3090 ArrayType::ArraySizeModifier ASM,
3091 unsigned IndexTypeQuals) const {
3092 assert((EltTy->isDependentType() ||
3093 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3094 "Constant array of VLAs is illegal!");
3096 // Convert the array size into a canonical width matching the pointer size for
3098 llvm::APInt ArySize(ArySizeIn);
3099 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3101 llvm::FoldingSetNodeID ID;
3102 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
3104 void *InsertPos = nullptr;
3105 if (ConstantArrayType *ATP =
3106 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3107 return QualType(ATP, 0);
3109 // If the element type isn't canonical or has qualifiers, this won't
3110 // be a canonical type either, so fill in the canonical type field.
3112 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3113 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3114 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
3115 ASM, IndexTypeQuals);
3116 Canon = getQualifiedType(Canon, canonSplit.Quals);
3118 // Get the new insert position for the node we care about.
3119 ConstantArrayType *NewIP =
3120 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3121 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3124 auto *New = new (*this,TypeAlignment)
3125 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
3126 ConstantArrayTypes.InsertNode(New, InsertPos);
3127 Types.push_back(New);
3128 return QualType(New, 0);
3131 /// getVariableArrayDecayedType - Turns the given type, which may be
3132 /// variably-modified, into the corresponding type with all the known
3133 /// sizes replaced with [*].
3134 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3135 // Vastly most common case.
3136 if (!type->isVariablyModifiedType()) return type;
3140 SplitQualType split = type.getSplitDesugaredType();
3141 const Type *ty = split.Ty;
3142 switch (ty->getTypeClass()) {
3143 #define TYPE(Class, Base)
3144 #define ABSTRACT_TYPE(Class, Base)
3145 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3146 #include "clang/AST/TypeNodes.def"
3147 llvm_unreachable("didn't desugar past all non-canonical types?");
3149 // These types should never be variably-modified.
3153 case Type::DependentVector:
3154 case Type::ExtVector:
3155 case Type::DependentSizedExtVector:
3156 case Type::DependentAddressSpace:
3157 case Type::ObjCObject:
3158 case Type::ObjCInterface:
3159 case Type::ObjCObjectPointer:
3162 case Type::UnresolvedUsing:
3163 case Type::TypeOfExpr:
3165 case Type::Decltype:
3166 case Type::UnaryTransform:
3167 case Type::DependentName:
3168 case Type::InjectedClassName:
3169 case Type::TemplateSpecialization:
3170 case Type::DependentTemplateSpecialization:
3171 case Type::TemplateTypeParm:
3172 case Type::SubstTemplateTypeParmPack:
3174 case Type::DeducedTemplateSpecialization:
3175 case Type::PackExpansion:
3176 llvm_unreachable("type should never be variably-modified");
3178 // These types can be variably-modified but should never need to
3180 case Type::FunctionNoProto:
3181 case Type::FunctionProto:
3182 case Type::BlockPointer:
3183 case Type::MemberPointer:
3187 // These types can be variably-modified. All these modifications
3188 // preserve structure except as noted by comments.
3189 // TODO: if we ever care about optimizing VLAs, there are no-op
3190 // optimizations available here.
3192 result = getPointerType(getVariableArrayDecayedType(
3193 cast<PointerType>(ty)->getPointeeType()));
3196 case Type::LValueReference: {
3197 const auto *lv = cast<LValueReferenceType>(ty);
3198 result = getLValueReferenceType(
3199 getVariableArrayDecayedType(lv->getPointeeType()),
3200 lv->isSpelledAsLValue());
3204 case Type::RValueReference: {
3205 const auto *lv = cast<RValueReferenceType>(ty);
3206 result = getRValueReferenceType(
3207 getVariableArrayDecayedType(lv->getPointeeType()));
3211 case Type::Atomic: {
3212 const auto *at = cast<AtomicType>(ty);
3213 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3217 case Type::ConstantArray: {
3218 const auto *cat = cast<ConstantArrayType>(ty);
3219 result = getConstantArrayType(
3220 getVariableArrayDecayedType(cat->getElementType()),
3222 cat->getSizeModifier(),
3223 cat->getIndexTypeCVRQualifiers());
3227 case Type::DependentSizedArray: {
3228 const auto *dat = cast<DependentSizedArrayType>(ty);
3229 result = getDependentSizedArrayType(
3230 getVariableArrayDecayedType(dat->getElementType()),
3232 dat->getSizeModifier(),
3233 dat->getIndexTypeCVRQualifiers(),
3234 dat->getBracketsRange());
3238 // Turn incomplete types into [*] types.
3239 case Type::IncompleteArray: {
3240 const auto *iat = cast<IncompleteArrayType>(ty);
3241 result = getVariableArrayType(
3242 getVariableArrayDecayedType(iat->getElementType()),
3245 iat->getIndexTypeCVRQualifiers(),
3250 // Turn VLA types into [*] types.
3251 case Type::VariableArray: {
3252 const auto *vat = cast<VariableArrayType>(ty);
3253 result = getVariableArrayType(
3254 getVariableArrayDecayedType(vat->getElementType()),
3257 vat->getIndexTypeCVRQualifiers(),
3258 vat->getBracketsRange());
3263 // Apply the top-level qualifiers from the original.
3264 return getQualifiedType(result, split.Quals);
3267 /// getVariableArrayType - Returns a non-unique reference to the type for a
3268 /// variable array of the specified element type.
3269 QualType ASTContext::getVariableArrayType(QualType EltTy,
3271 ArrayType::ArraySizeModifier ASM,
3272 unsigned IndexTypeQuals,
3273 SourceRange Brackets) const {
3274 // Since we don't unique expressions, it isn't possible to unique VLA's
3275 // that have an expression provided for their size.
3278 // Be sure to pull qualifiers off the element type.
3279 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3280 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3281 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3282 IndexTypeQuals, Brackets);
3283 Canon = getQualifiedType(Canon, canonSplit.Quals);
3286 auto *New = new (*this, TypeAlignment)
3287 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3289 VariableArrayTypes.push_back(New);
3290 Types.push_back(New);
3291 return QualType(New, 0);
3294 /// getDependentSizedArrayType - Returns a non-unique reference to
3295 /// the type for a dependently-sized array of the specified element
3297 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3299 ArrayType::ArraySizeModifier ASM,
3300 unsigned elementTypeQuals,
3301 SourceRange brackets) const {
3302 assert((!numElements || numElements->isTypeDependent() ||
3303 numElements->isValueDependent()) &&
3304 "Size must be type- or value-dependent!");
3306 // Dependently-sized array types that do not have a specified number
3307 // of elements will have their sizes deduced from a dependent
3308 // initializer. We do no canonicalization here at all, which is okay
3309 // because they can't be used in most locations.
3312 = new (*this, TypeAlignment)
3313 DependentSizedArrayType(*this, elementType, QualType(),
3314 numElements, ASM, elementTypeQuals,
3316 Types.push_back(newType);
3317 return QualType(newType, 0);
3320 // Otherwise, we actually build a new type every time, but we
3321 // also build a canonical type.
3323 SplitQualType canonElementType = getCanonicalType(elementType).split();
3325 void *insertPos = nullptr;
3326 llvm::FoldingSetNodeID ID;
3327 DependentSizedArrayType::Profile(ID, *this,
3328 QualType(canonElementType.Ty, 0),
3329 ASM, elementTypeQuals, numElements);
3331 // Look for an existing type with these properties.
3332 DependentSizedArrayType *canonTy =
3333 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3335 // If we don't have one, build one.
3337 canonTy = new (*this, TypeAlignment)
3338 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3339 QualType(), numElements, ASM, elementTypeQuals,
3341 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3342 Types.push_back(canonTy);
3345 // Apply qualifiers from the element type to the array.
3346 QualType canon = getQualifiedType(QualType(canonTy,0),
3347 canonElementType.Quals);
3349 // If we didn't need extra canonicalization for the element type or the size
3350 // expression, then just use that as our result.
3351 if (QualType(canonElementType.Ty, 0) == elementType &&
3352 canonTy->getSizeExpr() == numElements)
3355 // Otherwise, we need to build a type which follows the spelling
3356 // of the element type.
3358 = new (*this, TypeAlignment)
3359 DependentSizedArrayType(*this, elementType, canon, numElements,
3360 ASM, elementTypeQuals, brackets);
3361 Types.push_back(sugaredType);
3362 return QualType(sugaredType, 0);
3365 QualType ASTContext::getIncompleteArrayType(QualType elementType,
3366 ArrayType::ArraySizeModifier ASM,
3367 unsigned elementTypeQuals) const {
3368 llvm::FoldingSetNodeID ID;
3369 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3371 void *insertPos = nullptr;
3372 if (IncompleteArrayType *iat =
3373 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3374 return QualType(iat, 0);
3376 // If the element type isn't canonical, this won't be a canonical type
3377 // either, so fill in the canonical type field. We also have to pull
3378 // qualifiers off the element type.
3381 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3382 SplitQualType canonSplit = getCanonicalType(elementType).split();
3383 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3384 ASM, elementTypeQuals);
3385 canon = getQualifiedType(canon, canonSplit.Quals);
3387 // Get the new insert position for the node we care about.
3388 IncompleteArrayType *existing =
3389 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3390 assert(!existing && "Shouldn't be in the map!"); (void) existing;
3393 auto *newType = new (*this, TypeAlignment)
3394 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3396 IncompleteArrayTypes.InsertNode(newType, insertPos);
3397 Types.push_back(newType);
3398 return QualType(newType, 0);
3401 /// getVectorType - Return the unique reference to a vector type of
3402 /// the specified element type and size. VectorType must be a built-in type.
3403 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3404 VectorType::VectorKind VecKind) const {
3405 assert(vecType->isBuiltinType());
3407 // Check if we've already instantiated a vector of this type.
3408 llvm::FoldingSetNodeID ID;
3409 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3411 void *InsertPos = nullptr;
3412 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3413 return QualType(VTP, 0);
3415 // If the element type isn't canonical, this won't be a canonical type either,
3416 // so fill in the canonical type field.
3418 if (!vecType.isCanonical()) {
3419 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3421 // Get the new insert position for the node we care about.
3422 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3423 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3425 auto *New = new (*this, TypeAlignment)
3426 VectorType(vecType, NumElts, Canonical, VecKind);
3427 VectorTypes.InsertNode(New, InsertPos);
3428 Types.push_back(New);
3429 return QualType(New, 0);
3433 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3434 SourceLocation AttrLoc,
3435 VectorType::VectorKind VecKind) const {
3436 llvm::FoldingSetNodeID ID;
3437 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3439 void *InsertPos = nullptr;
3440 DependentVectorType *Canon =
3441 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3442 DependentVectorType *New;
3445 New = new (*this, TypeAlignment) DependentVectorType(
3446 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3448 QualType CanonVecTy = getCanonicalType(VecType);
3449 if (CanonVecTy == VecType) {
3450 New = new (*this, TypeAlignment) DependentVectorType(
3451 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3453 DependentVectorType *CanonCheck =
3454 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3455 assert(!CanonCheck &&
3456 "Dependent-sized vector_size canonical type broken");
3458 DependentVectorTypes.InsertNode(New, InsertPos);
3460 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3462 New = new (*this, TypeAlignment) DependentVectorType(
3463 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3467 Types.push_back(New);
3468 return QualType(New, 0);
3471 /// getExtVectorType - Return the unique reference to an extended vector type of
3472 /// the specified element type and size. VectorType must be a built-in type.
3474 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3475 assert(vecType->isBuiltinType() || vecType->isDependentType());
3477 // Check if we've already instantiated a vector of this type.
3478 llvm::FoldingSetNodeID ID;
3479 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3480 VectorType::GenericVector);
3481 void *InsertPos = nullptr;
3482 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3483 return QualType(VTP, 0);
3485 // If the element type isn't canonical, this won't be a canonical type either,
3486 // so fill in the canonical type field.
3488 if (!vecType.isCanonical()) {
3489 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3491 // Get the new insert position for the node we care about.
3492 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3493 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3495 auto *New = new (*this, TypeAlignment)
3496 ExtVectorType(vecType, NumElts, Canonical);
3497 VectorTypes.InsertNode(New, InsertPos);
3498 Types.push_back(New);
3499 return QualType(New, 0);
3503 ASTContext::getDependentSizedExtVectorType(QualType vecType,
3505 SourceLocation AttrLoc) const {
3506 llvm::FoldingSetNodeID ID;
3507 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
3510 void *InsertPos = nullptr;
3511 DependentSizedExtVectorType *Canon
3512 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3513 DependentSizedExtVectorType *New;
3515 // We already have a canonical version of this array type; use it as
3516 // the canonical type for a newly-built type.
3517 New = new (*this, TypeAlignment)
3518 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3521 QualType CanonVecTy = getCanonicalType(vecType);
3522 if (CanonVecTy == vecType) {
3523 New = new (*this, TypeAlignment)
3524 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3527 DependentSizedExtVectorType *CanonCheck
3528 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3529 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3531 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3533 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3535 New = new (*this, TypeAlignment)
3536 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
3540 Types.push_back(New);
3541 return QualType(New, 0);
3544 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3545 Expr *AddrSpaceExpr,
3546 SourceLocation AttrLoc) const {
3547 assert(AddrSpaceExpr->isInstantiationDependent());
3549 QualType canonPointeeType = getCanonicalType(PointeeType);
3551 void *insertPos = nullptr;
3552 llvm::FoldingSetNodeID ID;
3553 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3556 DependentAddressSpaceType *canonTy =
3557 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3560 canonTy = new (*this, TypeAlignment)
3561 DependentAddressSpaceType(*this, canonPointeeType,
3562 QualType(), AddrSpaceExpr, AttrLoc);
3563 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3564 Types.push_back(canonTy);
3567 if (canonPointeeType == PointeeType &&
3568 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
3569 return QualType(canonTy, 0);
3572 = new (*this, TypeAlignment)
3573 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
3574 AddrSpaceExpr, AttrLoc);
3575 Types.push_back(sugaredType);
3576 return QualType(sugaredType, 0);
3579 /// Determine whether \p T is canonical as the result type of a function.
3580 static bool isCanonicalResultType(QualType T) {
3581 return T.isCanonical() &&
3582 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3583 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3586 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
3588 ASTContext::getFunctionNoProtoType(QualType ResultTy,
3589 const FunctionType::ExtInfo &Info) const {
3590 // Unique functions, to guarantee there is only one function of a particular
3592 llvm::FoldingSetNodeID ID;
3593 FunctionNoProtoType::Profile(ID, ResultTy, Info);
3595 void *InsertPos = nullptr;
3596 if (FunctionNoProtoType *FT =
3597 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3598 return QualType(FT, 0);
3601 if (!isCanonicalResultType(ResultTy)) {
3603 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
3605 // Get the new insert position for the node we care about.
3606 FunctionNoProtoType *NewIP =
3607 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3608 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3611 auto *New = new (*this, TypeAlignment)
3612 FunctionNoProtoType(ResultTy, Canonical, Info);
3613 Types.push_back(New);
3614 FunctionNoProtoTypes.InsertNode(New, InsertPos);
3615 return QualType(New, 0);
3619 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3620 CanQualType CanResultType = getCanonicalType(ResultType);
3622 // Canonical result types do not have ARC lifetime qualifiers.
3623 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3624 Qualifiers Qs = CanResultType.getQualifiers();
3625 Qs.removeObjCLifetime();
3626 return CanQualType::CreateUnsafe(
3627 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3630 return CanResultType;
3633 static bool isCanonicalExceptionSpecification(
3634 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3635 if (ESI.Type == EST_None)
3637 if (!NoexceptInType)
3640 // C++17 onwards: exception specification is part of the type, as a simple
3641 // boolean "can this function type throw".
3642 if (ESI.Type == EST_BasicNoexcept)
3645 // A noexcept(expr) specification is (possibly) canonical if expr is
3647 if (ESI.Type == EST_DependentNoexcept)
3650 // A dynamic exception specification is canonical if it only contains pack
3651 // expansions (so we can't tell whether it's non-throwing) and all its
3652 // contained types are canonical.
3653 if (ESI.Type == EST_Dynamic) {
3654 bool AnyPackExpansions = false;
3655 for (QualType ET : ESI.Exceptions) {
3656 if (!ET.isCanonical())
3658 if (ET->getAs<PackExpansionType>())
3659 AnyPackExpansions = true;
3661 return AnyPackExpansions;
3667 QualType ASTContext::getFunctionTypeInternal(
3668 QualType ResultTy, ArrayRef<QualType> ArgArray,
3669 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
3670 size_t NumArgs = ArgArray.size();
3672 // Unique functions, to guarantee there is only one function of a particular
3674 llvm::FoldingSetNodeID ID;
3675 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3679 bool Unique = false;
3681 void *InsertPos = nullptr;
3682 if (FunctionProtoType *FPT =
3683 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3684 QualType Existing = QualType(FPT, 0);
3686 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3687 // it so long as our exception specification doesn't contain a dependent
3688 // noexcept expression, or we're just looking for a canonical type.
3689 // Otherwise, we're going to need to create a type
3690 // sugar node to hold the concrete expression.
3691 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
3692 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3695 // We need a new type sugar node for this one, to hold the new noexcept
3696 // expression. We do no canonicalization here, but that's OK since we don't
3697 // expect to see the same noexcept expression much more than once.
3698 Canonical = getCanonicalType(Existing);
3702 bool NoexceptInType = getLangOpts().CPlusPlus17;
3703 bool IsCanonicalExceptionSpec =
3704 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3706 // Determine whether the type being created is already canonical or not.
3707 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
3708 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
3709 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3710 if (!ArgArray[i].isCanonicalAsParam())
3711 isCanonical = false;
3713 if (OnlyWantCanonical)
3714 assert(isCanonical &&
3715 "given non-canonical parameters constructing canonical type");
3717 // If this type isn't canonical, get the canonical version of it if we don't
3718 // already have it. The exception spec is only partially part of the
3719 // canonical type, and only in C++17 onwards.
3720 if (!isCanonical && Canonical.isNull()) {
3721 SmallVector<QualType, 16> CanonicalArgs;
3722 CanonicalArgs.reserve(NumArgs);
3723 for (unsigned i = 0; i != NumArgs; ++i)
3724 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3726 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
3727 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3728 CanonicalEPI.HasTrailingReturn = false;
3730 if (IsCanonicalExceptionSpec) {
3731 // Exception spec is already OK.
3732 } else if (NoexceptInType) {
3733 switch (EPI.ExceptionSpec.Type) {
3734 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3735 // We don't know yet. It shouldn't matter what we pick here; no-one
3736 // should ever look at this.
3738 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
3739 CanonicalEPI.ExceptionSpec.Type = EST_None;
3742 // A dynamic exception specification is almost always "not noexcept",
3743 // with the exception that a pack expansion might expand to no types.
3745 bool AnyPacks = false;
3746 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3747 if (ET->getAs<PackExpansionType>())
3749 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3752 CanonicalEPI.ExceptionSpec.Type = EST_None;
3754 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3755 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3760 case EST_DynamicNone:
3761 case EST_BasicNoexcept:
3762 case EST_NoexceptTrue:
3764 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3767 case EST_DependentNoexcept:
3768 llvm_unreachable("dependent noexcept is already canonical");
3771 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3774 // Adjust the canonical function result type.
3775 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3777 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
3779 // Get the new insert position for the node we care about.
3780 FunctionProtoType *NewIP =
3781 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3782 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3785 // Compute the needed size to hold this FunctionProtoType and the
3786 // various trailing objects.
3787 auto ESH = FunctionProtoType::getExceptionSpecSize(
3788 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3789 size_t Size = FunctionProtoType::totalSizeToAlloc<
3790 QualType, FunctionType::FunctionTypeExtraBitfields,
3791 FunctionType::ExceptionType, Expr *, FunctionDecl *,
3792 FunctionProtoType::ExtParameterInfo, Qualifiers>(
3793 NumArgs, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
3794 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
3795 EPI.ExtParameterInfos ? NumArgs : 0,
3796 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
3798 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
3799 FunctionProtoType::ExtProtoInfo newEPI = EPI;
3800 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3801 Types.push_back(FTP);
3803 FunctionProtoTypes.InsertNode(FTP, InsertPos);
3804 return QualType(FTP, 0);
3807 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
3808 llvm::FoldingSetNodeID ID;
3809 PipeType::Profile(ID, T, ReadOnly);
3811 void *InsertPos = nullptr;
3812 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3813 return QualType(PT, 0);
3815 // If the pipe element type isn't canonical, this won't be a canonical type
3816 // either, so fill in the canonical type field.
3818 if (!T.isCanonical()) {
3819 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
3821 // Get the new insert position for the node we care about.
3822 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3823 assert(!NewIP && "Shouldn't be in the map!");
3826 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
3827 Types.push_back(New);
3828 PipeTypes.InsertNode(New, InsertPos);
3829 return QualType(New, 0);
3832 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3833 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3834 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3838 QualType ASTContext::getReadPipeType(QualType T) const {
3839 return getPipeType(T, true);
3842 QualType ASTContext::getWritePipeType(QualType T) const {
3843 return getPipeType(T, false);
3847 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3848 if (!isa<CXXRecordDecl>(D)) return false;
3849 const auto *RD = cast<CXXRecordDecl>(D);
3850 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3852 if (RD->getDescribedClassTemplate() &&
3853 !isa<ClassTemplateSpecializationDecl>(RD))
3859 /// getInjectedClassNameType - Return the unique reference to the
3860 /// injected class name type for the specified templated declaration.
3861 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
3862 QualType TST) const {
3863 assert(NeedsInjectedClassNameType(Decl));
3864 if (Decl->TypeForDecl) {
3865 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3866 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3867 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3868 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3869 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3872 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3873 Decl->TypeForDecl = newType;
3874 Types.push_back(newType);
3876 return QualType(Decl->TypeForDecl, 0);
3879 /// getTypeDeclType - Return the unique reference to the type for the
3880 /// specified type declaration.
3881 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3882 assert(Decl && "Passed null for Decl param");
3883 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3885 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3886 return getTypedefType(Typedef);
3888 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3889 "Template type parameter types are always available.");
3891 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
3892 assert(Record->isFirstDecl() && "struct/union has previous declaration");
3893 assert(!NeedsInjectedClassNameType(Record));
3894 return getRecordType(Record);
3895 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
3896 assert(Enum->isFirstDecl() && "enum has previous declaration");
3897 return getEnumType(Enum);
3898 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3899 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3900 Decl->TypeForDecl = newType;
3901 Types.push_back(newType);
3903 llvm_unreachable("TypeDecl without a type?");
3905 return QualType(Decl->TypeForDecl, 0);
3908 /// getTypedefType - Return the unique reference to the type for the
3909 /// specified typedef name decl.
3911 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3912 QualType Canonical) const {
3913 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3915 if (Canonical.isNull())
3916 Canonical = getCanonicalType(Decl->getUnderlyingType());
3917 auto *newType = new (*this, TypeAlignment)
3918 TypedefType(Type::Typedef, Decl, Canonical);
3919 Decl->TypeForDecl = newType;
3920 Types.push_back(newType);
3921 return QualType(newType, 0);
3924 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3925 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3927 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3928 if (PrevDecl->TypeForDecl)
3929 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3931 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
3932 Decl->TypeForDecl = newType;
3933 Types.push_back(newType);
3934 return QualType(newType, 0);
3937 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3938 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3940 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3941 if (PrevDecl->TypeForDecl)
3942 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3944 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
3945 Decl->TypeForDecl = newType;
3946 Types.push_back(newType);
3947 return QualType(newType, 0);
3950 QualType ASTContext::getAttributedType(attr::Kind attrKind,
3951 QualType modifiedType,
3952 QualType equivalentType) {
3953 llvm::FoldingSetNodeID id;
3954 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3956 void *insertPos = nullptr;
3957 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3958 if (type) return QualType(type, 0);
3960 QualType canon = getCanonicalType(equivalentType);
3961 type = new (*this, TypeAlignment)
3962 AttributedType(canon, attrKind, modifiedType, equivalentType);
3964 Types.push_back(type);
3965 AttributedTypes.InsertNode(type, insertPos);
3967 return QualType(type, 0);
3970 /// Retrieve a substitution-result type.
3972 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3973 QualType Replacement) const {
3974 assert(Replacement.isCanonical()
3975 && "replacement types must always be canonical");
3977 llvm::FoldingSetNodeID ID;
3978 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3979 void *InsertPos = nullptr;
3980 SubstTemplateTypeParmType *SubstParm
3981 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3984 SubstParm = new (*this, TypeAlignment)
3985 SubstTemplateTypeParmType(Parm, Replacement);
3986 Types.push_back(SubstParm);
3987 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3990 return QualType(SubstParm, 0);
3994 QualType ASTContext::getSubstTemplateTypeParmPackType(
3995 const TemplateTypeParmType *Parm,
3996 const TemplateArgument &ArgPack) {
3998 for (const auto &P : ArgPack.pack_elements()) {
3999 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4000 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4004 llvm::FoldingSetNodeID ID;
4005 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4006 void *InsertPos = nullptr;
4007 if (SubstTemplateTypeParmPackType *SubstParm
4008 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4009 return QualType(SubstParm, 0);
4012 if (!Parm->isCanonicalUnqualified()) {
4013 Canon = getCanonicalType(QualType(Parm, 0));
4014 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4016 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4020 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4022 Types.push_back(SubstParm);
4023 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4024 return QualType(SubstParm, 0);
4027 /// Retrieve the template type parameter type for a template
4028 /// parameter or parameter pack with the given depth, index, and (optionally)
4030 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4032 TemplateTypeParmDecl *TTPDecl) const {
4033 llvm::FoldingSetNodeID ID;
4034 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4035 void *InsertPos = nullptr;
4036 TemplateTypeParmType *TypeParm
4037 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4040 return QualType(TypeParm, 0);
4043 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4044 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4046 TemplateTypeParmType *TypeCheck
4047 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4048 assert(!TypeCheck && "Template type parameter canonical type broken");
4051 TypeParm = new (*this, TypeAlignment)
4052 TemplateTypeParmType(Depth, Index, ParameterPack);
4054 Types.push_back(TypeParm);
4055 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4057 return QualType(TypeParm, 0);
4061 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4062 SourceLocation NameLoc,
4063 const TemplateArgumentListInfo &Args,
4064 QualType Underlying) const {
4065 assert(!Name.getAsDependentTemplateName() &&
4066 "No dependent template names here!");
4067 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4069 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4070 TemplateSpecializationTypeLoc TL =
4071 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4072 TL.setTemplateKeywordLoc(SourceLocation());
4073 TL.setTemplateNameLoc(NameLoc);
4074 TL.setLAngleLoc(Args.getLAngleLoc());
4075 TL.setRAngleLoc(Args.getRAngleLoc());
4076 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4077 TL.setArgLocInfo(i, Args[i].getLocInfo());
4082 ASTContext::getTemplateSpecializationType(TemplateName Template,
4083 const TemplateArgumentListInfo &Args,
4084 QualType Underlying) const {
4085 assert(!Template.getAsDependentTemplateName() &&
4086 "No dependent template names here!");
4088 SmallVector<TemplateArgument, 4> ArgVec;
4089 ArgVec.reserve(Args.size());
4090 for (const TemplateArgumentLoc &Arg : Args.arguments())
4091 ArgVec.push_back(Arg.getArgument());
4093 return getTemplateSpecializationType(Template, ArgVec, Underlying);
4097 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4098 for (const TemplateArgument &Arg : Args)
4099 if (Arg.isPackExpansion())
4107 ASTContext::getTemplateSpecializationType(TemplateName Template,
4108 ArrayRef<TemplateArgument> Args,
4109 QualType Underlying) const {
4110 assert(!Template.getAsDependentTemplateName() &&
4111 "No dependent template names here!");
4112 // Look through qualified template names.
4113 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4114 Template = TemplateName(QTN->getTemplateDecl());
4117 Template.getAsTemplateDecl() &&
4118 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4120 if (!Underlying.isNull())
4121 CanonType = getCanonicalType(Underlying);
4123 // We can get here with an alias template when the specialization contains
4124 // a pack expansion that does not match up with a parameter pack.
4125 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4126 "Caller must compute aliased type");
4127 IsTypeAlias = false;
4128 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4131 // Allocate the (non-canonical) template specialization type, but don't
4132 // try to unique it: these types typically have location information that
4133 // we don't unique and don't want to lose.
4134 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4135 sizeof(TemplateArgument) * Args.size() +
4136 (IsTypeAlias? sizeof(QualType) : 0),
4139 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4140 IsTypeAlias ? Underlying : QualType());
4142 Types.push_back(Spec);
4143 return QualType(Spec, 0);
4146 QualType ASTContext::getCanonicalTemplateSpecializationType(
4147 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4148 assert(!Template.getAsDependentTemplateName() &&
4149 "No dependent template names here!");
4151 // Look through qualified template names.
4152 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4153 Template = TemplateName(QTN->getTemplateDecl());
4155 // Build the canonical template specialization type.
4156 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4157 SmallVector<TemplateArgument, 4> CanonArgs;
4158 unsigned NumArgs = Args.size();
4159 CanonArgs.reserve(NumArgs);
4160 for (const TemplateArgument &Arg : Args)
4161 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
4163 // Determine whether this canonical template specialization type already
4165 llvm::FoldingSetNodeID ID;
4166 TemplateSpecializationType::Profile(ID, CanonTemplate,
4169 void *InsertPos = nullptr;
4170 TemplateSpecializationType *Spec
4171 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4174 // Allocate a new canonical template specialization type.
4175 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4176 sizeof(TemplateArgument) * NumArgs),
4178 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4180 QualType(), QualType());
4181 Types.push_back(Spec);
4182 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4185 assert(Spec->isDependentType() &&
4186 "Non-dependent template-id type must have a canonical type");
4187 return QualType(Spec, 0);
4190 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4191 NestedNameSpecifier *NNS,
4193 TagDecl *OwnedTagDecl) const {
4194 llvm::FoldingSetNodeID ID;
4195 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4197 void *InsertPos = nullptr;
4198 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4200 return QualType(T, 0);
4202 QualType Canon = NamedType;
4203 if (!Canon.isCanonical()) {
4204 Canon = getCanonicalType(NamedType);
4205 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4206 assert(!CheckT && "Elaborated canonical type broken");
4210 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4212 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4215 ElaboratedTypes.InsertNode(T, InsertPos);
4216 return QualType(T, 0);
4220 ASTContext::getParenType(QualType InnerType) const {
4221 llvm::FoldingSetNodeID ID;
4222 ParenType::Profile(ID, InnerType);
4224 void *InsertPos = nullptr;
4225 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4227 return QualType(T, 0);
4229 QualType Canon = InnerType;
4230 if (!Canon.isCanonical()) {
4231 Canon = getCanonicalType(InnerType);
4232 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4233 assert(!CheckT && "Paren canonical type broken");
4237 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4239 ParenTypes.InsertNode(T, InsertPos);
4240 return QualType(T, 0);
4244 ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4245 const IdentifierInfo *MacroII) const {
4246 QualType Canon = UnderlyingTy;
4247 if (!Canon.isCanonical())
4248 Canon = getCanonicalType(UnderlyingTy);
4250 auto *newType = new (*this, TypeAlignment)
4251 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4252 Types.push_back(newType);
4253 return QualType(newType, 0);
4256 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4257 NestedNameSpecifier *NNS,
4258 const IdentifierInfo *Name,
4259 QualType Canon) const {
4260 if (Canon.isNull()) {
4261 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4262 if (CanonNNS != NNS)
4263 Canon = getDependentNameType(Keyword, CanonNNS, Name);
4266 llvm::FoldingSetNodeID ID;
4267 DependentNameType::Profile(ID, Keyword, NNS, Name);
4269 void *InsertPos = nullptr;
4270 DependentNameType *T
4271 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
4273 return QualType(T, 0);
4275 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
4277 DependentNameTypes.InsertNode(T, InsertPos);
4278 return QualType(T, 0);
4282 ASTContext::getDependentTemplateSpecializationType(
4283 ElaboratedTypeKeyword Keyword,
4284 NestedNameSpecifier *NNS,
4285 const IdentifierInfo *Name,
4286 const TemplateArgumentListInfo &Args) const {
4287 // TODO: avoid this copy
4288 SmallVector<TemplateArgument, 16> ArgCopy;
4289 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4290 ArgCopy.push_back(Args[I].getArgument());
4291 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
4295 ASTContext::getDependentTemplateSpecializationType(
4296 ElaboratedTypeKeyword Keyword,
4297 NestedNameSpecifier *NNS,
4298 const IdentifierInfo *Name,
4299 ArrayRef<TemplateArgument> Args) const {
4300 assert((!NNS || NNS->isDependent()) &&
4301 "nested-name-specifier must be dependent");
4303 llvm::FoldingSetNodeID ID;
4304 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
4307 void *InsertPos = nullptr;
4308 DependentTemplateSpecializationType *T
4309 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4311 return QualType(T, 0);
4313 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4315 ElaboratedTypeKeyword CanonKeyword = Keyword;
4316 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4318 bool AnyNonCanonArgs = false;
4319 unsigned NumArgs = Args.size();
4320 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
4321 for (unsigned I = 0; I != NumArgs; ++I) {
4322 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4323 if (!CanonArgs[I].structurallyEquals(Args[I]))
4324 AnyNonCanonArgs = true;
4328 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4329 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
4333 // Find the insert position again.
4334 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4337 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4338 sizeof(TemplateArgument) * NumArgs),
4340 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
4343 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
4344 return QualType(T, 0);
4347 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4348 TemplateArgument Arg;
4349 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4350 QualType ArgType = getTypeDeclType(TTP);
4351 if (TTP->isParameterPack())
4352 ArgType = getPackExpansionType(ArgType, None);
4354 Arg = TemplateArgument(ArgType);
4355 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4356 Expr *E = new (*this) DeclRefExpr(
4357 *this, NTTP, /*enclosing*/ false,
4358 NTTP->getType().getNonLValueExprType(*this),
4359 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4361 if (NTTP->isParameterPack())
4362 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4364 Arg = TemplateArgument(E);
4366 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4367 if (TTP->isParameterPack())
4368 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4370 Arg = TemplateArgument(TemplateName(TTP));
4373 if (Param->isTemplateParameterPack())
4374 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4380 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4381 SmallVectorImpl<TemplateArgument> &Args) {
4382 Args.reserve(Args.size() + Params->size());
4384 for (NamedDecl *Param : *Params)
4385 Args.push_back(getInjectedTemplateArg(Param));
4388 QualType ASTContext::getPackExpansionType(QualType Pattern,
4389 Optional<unsigned> NumExpansions) {
4390 llvm::FoldingSetNodeID ID;
4391 PackExpansionType::Profile(ID, Pattern, NumExpansions);
4393 // A deduced type can deduce to a pack, eg
4394 // auto ...x = some_pack;
4395 // That declaration isn't (yet) valid, but is created as part of building an
4396 // init-capture pack:
4397 // [...x = some_pack] {}
4398 assert((Pattern->containsUnexpandedParameterPack() ||
4399 Pattern->getContainedDeducedType()) &&
4400 "Pack expansions must expand one or more parameter packs");
4401 void *InsertPos = nullptr;
4402 PackExpansionType *T
4403 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4405 return QualType(T, 0);
4408 if (!Pattern.isCanonical()) {
4409 Canon = getCanonicalType(Pattern);
4410 // The canonical type might not contain an unexpanded parameter pack, if it
4411 // contains an alias template specialization which ignores one of its
4413 if (Canon->containsUnexpandedParameterPack()) {
4414 Canon = getPackExpansionType(Canon, NumExpansions);
4416 // Find the insert position again, in case we inserted an element into
4417 // PackExpansionTypes and invalidated our insert position.
4418 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4422 T = new (*this, TypeAlignment)
4423 PackExpansionType(Pattern, Canon, NumExpansions);
4425 PackExpansionTypes.InsertNode(T, InsertPos);
4426 return QualType(T, 0);
4429 /// CmpProtocolNames - Comparison predicate for sorting protocols
4431 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4432 ObjCProtocolDecl *const *RHS) {
4433 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
4436 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4437 if (Protocols.empty()) return true;
4439 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4442 for (unsigned i = 1; i != Protocols.size(); ++i)
4443 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
4444 Protocols[i]->getCanonicalDecl() != Protocols[i])
4450 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
4451 // Sort protocols, keyed by name.
4452 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
4455 for (ObjCProtocolDecl *&P : Protocols)
4456 P = P->getCanonicalDecl();
4458 // Remove duplicates.
4459 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4460 Protocols.erase(ProtocolsEnd, Protocols.end());
4463 QualType ASTContext::getObjCObjectType(QualType BaseType,
4464 ObjCProtocolDecl * const *Protocols,
4465 unsigned NumProtocols) const {
4466 return getObjCObjectType(BaseType, {},
4467 llvm::makeArrayRef(Protocols, NumProtocols),
4468 /*isKindOf=*/false);
4471 QualType ASTContext::getObjCObjectType(
4473 ArrayRef<QualType> typeArgs,
4474 ArrayRef<ObjCProtocolDecl *> protocols,
4475 bool isKindOf) const {
4476 // If the base type is an interface and there aren't any protocols or
4477 // type arguments to add, then the interface type will do just fine.
4478 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4479 isa<ObjCInterfaceType>(baseType))
4482 // Look in the folding set for an existing type.
4483 llvm::FoldingSetNodeID ID;
4484 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4485 void *InsertPos = nullptr;
4486 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4487 return QualType(QT, 0);
4489 // Determine the type arguments to be used for canonicalization,
4490 // which may be explicitly specified here or written on the base
4492 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4493 if (effectiveTypeArgs.empty()) {
4494 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
4495 effectiveTypeArgs = baseObject->getTypeArgs();
4498 // Build the canonical type, which has the canonical base type and a
4499 // sorted-and-uniqued list of protocols and the type arguments
4502 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4503 effectiveTypeArgs.end(),
4504 [&](QualType type) {
4505 return type.isCanonical();
4507 bool protocolsSorted = areSortedAndUniqued(protocols);
4508 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4509 // Determine the canonical type arguments.
4510 ArrayRef<QualType> canonTypeArgs;
4511 SmallVector<QualType, 4> canonTypeArgsVec;
4512 if (!typeArgsAreCanonical) {
4513 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4514 for (auto typeArg : effectiveTypeArgs)
4515 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4516 canonTypeArgs = canonTypeArgsVec;
4518 canonTypeArgs = effectiveTypeArgs;
4521 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4522 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4523 if (!protocolsSorted) {
4524 canonProtocolsVec.append(protocols.begin(), protocols.end());
4525 SortAndUniqueProtocols(canonProtocolsVec);
4526 canonProtocols = canonProtocolsVec;
4528 canonProtocols = protocols;
4531 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
4532 canonProtocols, isKindOf);
4534 // Regenerate InsertPos.
4535 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4538 unsigned size = sizeof(ObjCObjectTypeImpl);
4539 size += typeArgs.size() * sizeof(QualType);
4540 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4541 void *mem = Allocate(size, TypeAlignment);
4543 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4547 ObjCObjectTypes.InsertNode(T, InsertPos);
4548 return QualType(T, 0);
4551 /// Apply Objective-C protocol qualifiers to the given type.
4552 /// If this is for the canonical type of a type parameter, we can apply
4553 /// protocol qualifiers on the ObjCObjectPointerType.
4555 ASTContext::applyObjCProtocolQualifiers(QualType type,
4556 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4557 bool allowOnPointerType) const {
4560 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4561 return getObjCTypeParamType(objT->getDecl(), protocols);
4564 // Apply protocol qualifiers to ObjCObjectPointerType.
4565 if (allowOnPointerType) {
4566 if (const auto *objPtr =
4567 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4568 const ObjCObjectType *objT = objPtr->getObjectType();
4569 // Merge protocol lists and construct ObjCObjectType.
4570 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4571 protocolsVec.append(objT->qual_begin(),
4573 protocolsVec.append(protocols.begin(), protocols.end());
4574 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4575 type = getObjCObjectType(
4576 objT->getBaseType(),
4577 objT->getTypeArgsAsWritten(),
4579 objT->isKindOfTypeAsWritten());
4580 return getObjCObjectPointerType(type);
4584 // Apply protocol qualifiers to ObjCObjectType.
4585 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4586 // FIXME: Check for protocols to which the class type is already
4587 // known to conform.
4589 return getObjCObjectType(objT->getBaseType(),
4590 objT->getTypeArgsAsWritten(),
4592 objT->isKindOfTypeAsWritten());
4595 // If the canonical type is ObjCObjectType, ...
4596 if (type->isObjCObjectType()) {
4597 // Silently overwrite any existing protocol qualifiers.
4598 // TODO: determine whether that's the right thing to do.
4600 // FIXME: Check for protocols to which the class type is already
4601 // known to conform.
4602 return getObjCObjectType(type, {}, protocols, false);
4605 // id<protocol-list>
4606 if (type->isObjCIdType()) {
4607 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4608 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
4609 objPtr->isKindOfType());
4610 return getObjCObjectPointerType(type);
4613 // Class<protocol-list>
4614 if (type->isObjCClassType()) {
4615 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4616 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
4617 objPtr->isKindOfType());
4618 return getObjCObjectPointerType(type);
4626 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4627 ArrayRef<ObjCProtocolDecl *> protocols,
4628 QualType Canonical) const {
4629 // Look in the folding set for an existing type.
4630 llvm::FoldingSetNodeID ID;
4631 ObjCTypeParamType::Profile(ID, Decl, protocols);
4632 void *InsertPos = nullptr;
4633 if (ObjCTypeParamType *TypeParam =
4634 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4635 return QualType(TypeParam, 0);
4637 if (Canonical.isNull()) {
4638 // We canonicalize to the underlying type.
4639 Canonical = getCanonicalType(Decl->getUnderlyingType());
4640 if (!protocols.empty()) {
4641 // Apply the protocol qualifers.
4643 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4644 Canonical, protocols, hasError, true /*allowOnPointerType*/));
4645 assert(!hasError && "Error when apply protocol qualifier to bound type");
4649 unsigned size = sizeof(ObjCTypeParamType);
4650 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4651 void *mem = Allocate(size, TypeAlignment);
4652 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
4654 Types.push_back(newType);
4655 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4656 return QualType(newType, 0);
4659 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4660 /// protocol list adopt all protocols in QT's qualified-id protocol
4662 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4663 ObjCInterfaceDecl *IC) {
4664 if (!QT->isObjCQualifiedIdType())
4667 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
4668 // If both the right and left sides have qualifiers.
4669 for (auto *Proto : OPT->quals()) {
4670 if (!IC->ClassImplementsProtocol(Proto, false))
4678 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4679 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
4681 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4682 ObjCInterfaceDecl *IDecl) {
4683 if (!QT->isObjCQualifiedIdType())
4685 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
4688 if (!IDecl->hasDefinition())
4690 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4691 CollectInheritedProtocols(IDecl, InheritedProtocols);
4692 if (InheritedProtocols.empty())
4694 // Check that if every protocol in list of id<plist> conforms to a protocol
4695 // of IDecl's, then bridge casting is ok.
4696 bool Conforms = false;
4697 for (auto *Proto : OPT->quals()) {
4699 for (auto *PI : InheritedProtocols) {
4700 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4711 for (auto *PI : InheritedProtocols) {
4712 // If both the right and left sides have qualifiers.
4713 bool Adopts = false;
4714 for (auto *Proto : OPT->quals()) {
4715 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
4716 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
4725 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4726 /// the given object type.
4727 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
4728 llvm::FoldingSetNodeID ID;
4729 ObjCObjectPointerType::Profile(ID, ObjectT);
4731 void *InsertPos = nullptr;
4732 if (ObjCObjectPointerType *QT =
4733 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4734 return QualType(QT, 0);
4736 // Find the canonical object type.
4738 if (!ObjectT.isCanonical()) {
4739 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4741 // Regenerate InsertPos.
4742 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4746 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4748 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
4750 Types.push_back(QType);
4751 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
4752 return QualType(QType, 0);
4755 /// getObjCInterfaceType - Return the unique reference to the type for the
4756 /// specified ObjC interface decl. The list of protocols is optional.
4757 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4758 ObjCInterfaceDecl *PrevDecl) const {
4759 if (Decl->TypeForDecl)
4760 return QualType(Decl->TypeForDecl, 0);
4763 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4764 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4765 return QualType(PrevDecl->TypeForDecl, 0);
4768 // Prefer the definition, if there is one.
4769 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4772 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4773 auto *T = new (Mem) ObjCInterfaceType(Decl);
4774 Decl->TypeForDecl = T;
4776 return QualType(T, 0);
4779 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4780 /// TypeOfExprType AST's (since expression's are never shared). For example,
4781 /// multiple declarations that refer to "typeof(x)" all contain different
4782 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
4783 /// on canonical type's (which are always unique).
4784 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
4785 TypeOfExprType *toe;
4786 if (tofExpr->isTypeDependent()) {
4787 llvm::FoldingSetNodeID ID;
4788 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
4790 void *InsertPos = nullptr;
4791 DependentTypeOfExprType *Canon
4792 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4794 // We already have a "canonical" version of an identical, dependent
4795 // typeof(expr) type. Use that as our canonical type.
4796 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
4797 QualType((TypeOfExprType*)Canon, 0));
4799 // Build a new, canonical typeof(expr) type.
4801 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
4802 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4806 QualType Canonical = getCanonicalType(tofExpr->getType());
4807 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
4809 Types.push_back(toe);
4810 return QualType(toe, 0);
4813 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
4814 /// TypeOfType nodes. The only motivation to unique these nodes would be
4815 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
4816 /// an issue. This doesn't affect the type checker, since it operates
4817 /// on canonical types (which are always unique).
4818 QualType ASTContext::getTypeOfType(QualType tofType) const {
4819 QualType Canonical = getCanonicalType(tofType);
4820 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
4821 Types.push_back(tot);
4822 return QualType(tot, 0);
4825 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
4826 /// nodes. This would never be helpful, since each such type has its own
4827 /// expression, and would not give a significant memory saving, since there
4828 /// is an Expr tree under each such type.
4829 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
4832 // C++11 [temp.type]p2:
4833 // If an expression e involves a template parameter, decltype(e) denotes a
4834 // unique dependent type. Two such decltype-specifiers refer to the same
4835 // type only if their expressions are equivalent (14.5.6.1).
4836 if (e->isInstantiationDependent()) {
4837 llvm::FoldingSetNodeID ID;
4838 DependentDecltypeType::Profile(ID, *this, e);
4840 void *InsertPos = nullptr;
4841 DependentDecltypeType *Canon
4842 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
4844 // Build a new, canonical decltype(expr) type.
4845 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
4846 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
4848 dt = new (*this, TypeAlignment)
4849 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
4851 dt = new (*this, TypeAlignment)
4852 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
4854 Types.push_back(dt);
4855 return QualType(dt, 0);
4858 /// getUnaryTransformationType - We don't unique these, since the memory
4859 /// savings are minimal and these are rare.
4860 QualType ASTContext::getUnaryTransformType(QualType BaseType,
4861 QualType UnderlyingType,
4862 UnaryTransformType::UTTKind Kind)
4864 UnaryTransformType *ut = nullptr;
4866 if (BaseType->isDependentType()) {
4867 // Look in the folding set for an existing type.
4868 llvm::FoldingSetNodeID ID;
4869 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4871 void *InsertPos = nullptr;
4872 DependentUnaryTransformType *Canon
4873 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4876 // Build a new, canonical __underlying_type(type) type.
4877 Canon = new (*this, TypeAlignment)
4878 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4880 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4882 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4884 QualType(Canon, 0));
4886 QualType CanonType = getCanonicalType(UnderlyingType);
4887 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4888 UnderlyingType, Kind,
4891 Types.push_back(ut);
4892 return QualType(ut, 0);
4895 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
4896 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4897 /// canonical deduced-but-dependent 'auto' type.
4898 QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
4899 bool IsDependent, bool IsPack) const {
4900 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
4901 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
4902 return getAutoDeductType();
4904 // Look in the folding set for an existing type.
4905 void *InsertPos = nullptr;
4906 llvm::FoldingSetNodeID ID;
4907 AutoType::Profile(ID, DeducedType, Keyword, IsDependent, IsPack);
4908 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4909 return QualType(AT, 0);
4911 auto *AT = new (*this, TypeAlignment)
4912 AutoType(DeducedType, Keyword, IsDependent, IsPack);
4913 Types.push_back(AT);
4915 AutoTypes.InsertNode(AT, InsertPos);
4916 return QualType(AT, 0);
4919 /// Return the uniqued reference to the deduced template specialization type
4920 /// which has been deduced to the given type, or to the canonical undeduced
4921 /// such type, or the canonical deduced-but-dependent such type.
4922 QualType ASTContext::getDeducedTemplateSpecializationType(
4923 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4924 // Look in the folding set for an existing type.
4925 void *InsertPos = nullptr;
4926 llvm::FoldingSetNodeID ID;
4927 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4929 if (DeducedTemplateSpecializationType *DTST =
4930 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4931 return QualType(DTST, 0);
4933 auto *DTST = new (*this, TypeAlignment)
4934 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4935 Types.push_back(DTST);
4937 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4938 return QualType(DTST, 0);
4941 /// getAtomicType - Return the uniqued reference to the atomic type for
4942 /// the given value type.
4943 QualType ASTContext::getAtomicType(QualType T) const {
4944 // Unique pointers, to guarantee there is only one pointer of a particular
4946 llvm::FoldingSetNodeID ID;
4947 AtomicType::Profile(ID, T);
4949 void *InsertPos = nullptr;
4950 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4951 return QualType(AT, 0);
4953 // If the atomic value type isn't canonical, this won't be a canonical type
4954 // either, so fill in the canonical type field.
4956 if (!T.isCanonical()) {
4957 Canonical = getAtomicType(getCanonicalType(T));
4959 // Get the new insert position for the node we care about.
4960 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
4961 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4963 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4964 Types.push_back(New);
4965 AtomicTypes.InsertNode(New, InsertPos);
4966 return QualType(New, 0);
4969 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
4970 QualType ASTContext::getAutoDeductType() const {
4971 if (AutoDeductTy.isNull())
4972 AutoDeductTy = QualType(
4973 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
4974 /*dependent*/false, /*pack*/false),
4976 return AutoDeductTy;
4979 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4980 QualType ASTContext::getAutoRRefDeductType() const {
4981 if (AutoRRefDeductTy.isNull())
4982 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4983 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4984 return AutoRRefDeductTy;
4987 /// getTagDeclType - Return the unique reference to the type for the
4988 /// specified TagDecl (struct/union/class/enum) decl.
4989 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
4991 // FIXME: What is the design on getTagDeclType when it requires casting
4992 // away const? mutable?
4993 return getTypeDeclType(const_cast<TagDecl*>(Decl));
4996 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4997 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4998 /// needs to agree with the definition in <stddef.h>.
4999 CanQualType ASTContext::getSizeType() const {
5000 return getFromTargetType(Target->getSizeType());
5003 /// Return the unique signed counterpart of the integer type
5004 /// corresponding to size_t.
5005 CanQualType ASTContext::getSignedSizeType() const {
5006 return getFromTargetType(Target->getSignedSizeType());
5009 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5010 CanQualType ASTContext::getIntMaxType() const {
5011 return getFromTargetType(Target->getIntMaxType());
5014 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5015 CanQualType ASTContext::getUIntMaxType() const {
5016 return getFromTargetType(Target->getUIntMaxType());
5019 /// getSignedWCharType - Return the type of "signed wchar_t".
5020 /// Used when in C++, as a GCC extension.
5021 QualType ASTContext::getSignedWCharType() const {
5022 // FIXME: derive from "Target" ?
5026 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5027 /// Used when in C++, as a GCC extension.
5028 QualType ASTContext::getUnsignedWCharType() const {
5029 // FIXME: derive from "Target" ?
5030 return UnsignedIntTy;
5033 QualType ASTContext::getIntPtrType() const {
5034 return getFromTargetType(Target->getIntPtrType());
5037 QualType ASTContext::getUIntPtrType() const {
5038 return getCorrespondingUnsignedType(getIntPtrType());
5041 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5042 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5043 QualType ASTContext::getPointerDiffType() const {
5044 return getFromTargetType(Target->getPtrDiffType(0));
5047 /// Return the unique unsigned counterpart of "ptrdiff_t"
5048 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5049 /// in the definition of %tu format specifier.
5050 QualType ASTContext::getUnsignedPointerDiffType() const {
5051 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5054 /// Return the unique type for "pid_t" defined in
5055 /// <sys/types.h>. We need this to compute the correct type for vfork().
5056 QualType ASTContext::getProcessIDType() const {
5057 return getFromTargetType(Target->getProcessIDType());
5060 //===----------------------------------------------------------------------===//
5062 //===----------------------------------------------------------------------===//
5064 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5065 // Push qualifiers into arrays, and then discard any remaining
5067 T = getCanonicalType(T);
5068 T = getVariableArrayDecayedType(T);
5069 const Type *Ty = T.getTypePtr();
5071 if (isa<ArrayType>(Ty)) {
5072 Result = getArrayDecayedType(QualType(Ty,0));
5073 } else if (isa<FunctionType>(Ty)) {
5074 Result = getPointerType(QualType(Ty, 0));
5076 Result = QualType(Ty, 0);
5079 return CanQualType::CreateUnsafe(Result);
5082 QualType ASTContext::getUnqualifiedArrayType(QualType type,
5083 Qualifiers &quals) {
5084 SplitQualType splitType = type.getSplitUnqualifiedType();
5086 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5087 // the unqualified desugared type and then drops it on the floor.
5088 // We then have to strip that sugar back off with
5089 // getUnqualifiedDesugaredType(), which is silly.
5091 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5093 // If we don't have an array, just use the results in splitType.
5095 quals = splitType.Quals;
5096 return QualType(splitType.Ty, 0);
5099 // Otherwise, recurse on the array's element type.
5100 QualType elementType = AT->getElementType();
5101 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5103 // If that didn't change the element type, AT has no qualifiers, so we
5104 // can just use the results in splitType.
5105 if (elementType == unqualElementType) {
5106 assert(quals.empty()); // from the recursive call
5107 quals = splitType.Quals;
5108 return QualType(splitType.Ty, 0);
5111 // Otherwise, add in the qualifiers from the outermost type, then
5112 // build the type back up.
5113 quals.addConsistentQualifiers(splitType.Quals);
5115 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5116 return getConstantArrayType(unqualElementType, CAT->getSize(),
5117 CAT->getSizeModifier(), 0);
5120 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5121 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5124 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5125 return getVariableArrayType(unqualElementType,
5127 VAT->getSizeModifier(),
5128 VAT->getIndexTypeCVRQualifiers(),
5129 VAT->getBracketsRange());
5132 const auto *DSAT = cast<DependentSizedArrayType>(AT);
5133 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5134 DSAT->getSizeModifier(), 0,
5138 /// Attempt to unwrap two types that may both be array types with the same bound
5139 /// (or both be array types of unknown bound) for the purpose of comparing the
5140 /// cv-decomposition of two types per C++ [conv.qual].
5141 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5142 bool UnwrappedAny = false;
5144 auto *AT1 = getAsArrayType(T1);
5145 if (!AT1) return UnwrappedAny;
5147 auto *AT2 = getAsArrayType(T2);
5148 if (!AT2) return UnwrappedAny;
5150 // If we don't have two array types with the same constant bound nor two
5151 // incomplete array types, we've unwrapped everything we can.
5152 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5153 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5154 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
5155 return UnwrappedAny;
5156 } else if (!isa<IncompleteArrayType>(AT1) ||
5157 !isa<IncompleteArrayType>(AT2)) {
5158 return UnwrappedAny;
5161 T1 = AT1->getElementType();
5162 T2 = AT2->getElementType();
5163 UnwrappedAny = true;
5167 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5169 /// If T1 and T2 are both pointer types of the same kind, or both array types
5170 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5171 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5173 /// This function will typically be called in a loop that successively
5174 /// "unwraps" pointer and pointer-to-member types to compare them at each
5177 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
5178 /// pair of types that can't be unwrapped further.
5179 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
5180 UnwrapSimilarArrayTypes(T1, T2);
5182 const auto *T1PtrType = T1->getAs<PointerType>();
5183 const auto *T2PtrType = T2->getAs<PointerType>();
5184 if (T1PtrType && T2PtrType) {
5185 T1 = T1PtrType->getPointeeType();
5186 T2 = T2PtrType->getPointeeType();
5190 const auto *T1MPType = T1->getAs<MemberPointerType>();
5191 const auto *T2MPType = T2->getAs<MemberPointerType>();
5192 if (T1MPType && T2MPType &&
5193 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
5194 QualType(T2MPType->getClass(), 0))) {
5195 T1 = T1MPType->getPointeeType();
5196 T2 = T2MPType->getPointeeType();
5200 if (getLangOpts().ObjC) {
5201 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5202 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
5203 if (T1OPType && T2OPType) {
5204 T1 = T1OPType->getPointeeType();
5205 T2 = T2OPType->getPointeeType();
5210 // FIXME: Block pointers, too?
5215 bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5218 T1 = getUnqualifiedArrayType(T1, Quals);
5219 T2 = getUnqualifiedArrayType(T2, Quals);
5220 if (hasSameType(T1, T2))
5222 if (!UnwrapSimilarTypes(T1, T2))
5227 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5229 Qualifiers Quals1, Quals2;
5230 T1 = getUnqualifiedArrayType(T1, Quals1);
5231 T2 = getUnqualifiedArrayType(T2, Quals2);
5233 Quals1.removeCVRQualifiers();
5234 Quals2.removeCVRQualifiers();
5235 if (Quals1 != Quals2)
5238 if (hasSameType(T1, T2))
5241 if (!UnwrapSimilarTypes(T1, T2))
5247 ASTContext::getNameForTemplate(TemplateName Name,
5248 SourceLocation NameLoc) const {
5249 switch (Name.getKind()) {
5250 case TemplateName::QualifiedTemplate:
5251 case TemplateName::Template:
5252 // DNInfo work in progress: CHECKME: what about DNLoc?
5253 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5256 case TemplateName::OverloadedTemplate: {
5257 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5258 // DNInfo work in progress: CHECKME: what about DNLoc?
5259 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5262 case TemplateName::AssumedTemplate: {
5263 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5264 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5267 case TemplateName::DependentTemplate: {
5268 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5269 DeclarationName DName;
5270 if (DTN->isIdentifier()) {
5271 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5272 return DeclarationNameInfo(DName, NameLoc);
5274 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5275 // DNInfo work in progress: FIXME: source locations?
5276 DeclarationNameLoc DNLoc;
5277 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5278 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5279 return DeclarationNameInfo(DName, NameLoc, DNLoc);
5283 case TemplateName::SubstTemplateTemplateParm: {
5284 SubstTemplateTemplateParmStorage *subst
5285 = Name.getAsSubstTemplateTemplateParm();
5286 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5290 case TemplateName::SubstTemplateTemplateParmPack: {
5291 SubstTemplateTemplateParmPackStorage *subst
5292 = Name.getAsSubstTemplateTemplateParmPack();
5293 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5298 llvm_unreachable("bad template name kind!");
5301 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
5302 switch (Name.getKind()) {
5303 case TemplateName::QualifiedTemplate:
5304 case TemplateName::Template: {
5305 TemplateDecl *Template = Name.getAsTemplateDecl();
5306 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
5307 Template = getCanonicalTemplateTemplateParmDecl(TTP);
5309 // The canonical template name is the canonical template declaration.
5310 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
5313 case TemplateName::OverloadedTemplate:
5314 case TemplateName::AssumedTemplate:
5315 llvm_unreachable("cannot canonicalize unresolved template");
5317 case TemplateName::DependentTemplate: {
5318 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5319 assert(DTN && "Non-dependent template names must refer to template decls.");
5320 return DTN->CanonicalTemplateName;
5323 case TemplateName::SubstTemplateTemplateParm: {
5324 SubstTemplateTemplateParmStorage *subst
5325 = Name.getAsSubstTemplateTemplateParm();
5326 return getCanonicalTemplateName(subst->getReplacement());
5329 case TemplateName::SubstTemplateTemplateParmPack: {
5330 SubstTemplateTemplateParmPackStorage *subst
5331 = Name.getAsSubstTemplateTemplateParmPack();
5332 TemplateTemplateParmDecl *canonParameter
5333 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5334 TemplateArgument canonArgPack
5335 = getCanonicalTemplateArgument(subst->getArgumentPack());
5336 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5340 llvm_unreachable("bad template name!");
5343 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5344 X = getCanonicalTemplateName(X);
5345 Y = getCanonicalTemplateName(Y);
5346 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5350 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
5351 switch (Arg.getKind()) {
5352 case TemplateArgument::Null:
5355 case TemplateArgument::Expression:
5358 case TemplateArgument::Declaration: {
5359 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
5360 return TemplateArgument(D, Arg.getParamTypeForDecl());
5363 case TemplateArgument::NullPtr:
5364 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5367 case TemplateArgument::Template:
5368 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
5370 case TemplateArgument::TemplateExpansion:
5371 return TemplateArgument(getCanonicalTemplateName(
5372 Arg.getAsTemplateOrTemplatePattern()),
5373 Arg.getNumTemplateExpansions());
5375 case TemplateArgument::Integral:
5376 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
5378 case TemplateArgument::Type:
5379 return TemplateArgument(getCanonicalType(Arg.getAsType()));
5381 case TemplateArgument::Pack: {
5382 if (Arg.pack_size() == 0)
5385 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
5387 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
5388 AEnd = Arg.pack_end();
5389 A != AEnd; (void)++A, ++Idx)
5390 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
5392 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
5396 // Silence GCC warning
5397 llvm_unreachable("Unhandled template argument kind");
5400 NestedNameSpecifier *
5401 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
5405 switch (NNS->getKind()) {
5406 case NestedNameSpecifier::Identifier:
5407 // Canonicalize the prefix but keep the identifier the same.
5408 return NestedNameSpecifier::Create(*this,
5409 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5410 NNS->getAsIdentifier());
5412 case NestedNameSpecifier::Namespace:
5413 // A namespace is canonical; build a nested-name-specifier with
5414 // this namespace and no prefix.
5415 return NestedNameSpecifier::Create(*this, nullptr,
5416 NNS->getAsNamespace()->getOriginalNamespace());
5418 case NestedNameSpecifier::NamespaceAlias:
5419 // A namespace is canonical; build a nested-name-specifier with
5420 // this namespace and no prefix.
5421 return NestedNameSpecifier::Create(*this, nullptr,
5422 NNS->getAsNamespaceAlias()->getNamespace()
5423 ->getOriginalNamespace());
5425 case NestedNameSpecifier::TypeSpec:
5426 case NestedNameSpecifier::TypeSpecWithTemplate: {
5427 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
5429 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5430 // break it apart into its prefix and identifier, then reconsititute those
5431 // as the canonical nested-name-specifier. This is required to canonicalize
5432 // a dependent nested-name-specifier involving typedefs of dependent-name
5434 // typedef typename T::type T1;
5435 // typedef typename T1::type T2;
5436 if (const auto *DNT = T->getAs<DependentNameType>())
5437 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
5438 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
5440 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5441 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5443 return NestedNameSpecifier::Create(*this, nullptr, false,
5444 const_cast<Type *>(T.getTypePtr()));
5447 case NestedNameSpecifier::Global:
5448 case NestedNameSpecifier::Super:
5449 // The global specifier and __super specifer are canonical and unique.
5453 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5456 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
5457 // Handle the non-qualified case efficiently.
5458 if (!T.hasLocalQualifiers()) {
5459 // Handle the common positive case fast.
5460 if (const auto *AT = dyn_cast<ArrayType>(T))
5464 // Handle the common negative case fast.
5465 if (!isa<ArrayType>(T.getCanonicalType()))
5468 // Apply any qualifiers from the array type to the element type. This
5469 // implements C99 6.7.3p8: "If the specification of an array type includes
5470 // any type qualifiers, the element type is so qualified, not the array type."
5472 // If we get here, we either have type qualifiers on the type, or we have
5473 // sugar such as a typedef in the way. If we have type qualifiers on the type
5474 // we must propagate them down into the element type.
5476 SplitQualType split = T.getSplitDesugaredType();
5477 Qualifiers qs = split.Quals;
5479 // If we have a simple case, just return now.
5480 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
5481 if (!ATy || qs.empty())
5484 // Otherwise, we have an array and we have qualifiers on it. Push the
5485 // qualifiers into the array element type and return a new array type.
5486 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
5488 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
5489 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5490 CAT->getSizeModifier(),
5491 CAT->getIndexTypeCVRQualifiers()));
5492 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
5493 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5494 IAT->getSizeModifier(),
5495 IAT->getIndexTypeCVRQualifiers()));
5497 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
5498 return cast<ArrayType>(
5499 getDependentSizedArrayType(NewEltTy,
5500 DSAT->getSizeExpr(),
5501 DSAT->getSizeModifier(),
5502 DSAT->getIndexTypeCVRQualifiers(),
5503 DSAT->getBracketsRange()));
5505 const auto *VAT = cast<VariableArrayType>(ATy);
5506 return cast<ArrayType>(getVariableArrayType(NewEltTy,
5508 VAT->getSizeModifier(),
5509 VAT->getIndexTypeCVRQualifiers(),
5510 VAT->getBracketsRange()));
5513 QualType ASTContext::getAdjustedParameterType(QualType T) const {
5514 if (T->isArrayType() || T->isFunctionType())
5515 return getDecayedType(T);
5519 QualType ASTContext::getSignatureParameterType(QualType T) const {
5520 T = getVariableArrayDecayedType(T);
5521 T = getAdjustedParameterType(T);
5522 return T.getUnqualifiedType();
5525 QualType ASTContext::getExceptionObjectType(QualType T) const {
5526 // C++ [except.throw]p3:
5527 // A throw-expression initializes a temporary object, called the exception
5528 // object, the type of which is determined by removing any top-level
5529 // cv-qualifiers from the static type of the operand of throw and adjusting
5530 // the type from "array of T" or "function returning T" to "pointer to T"
5531 // or "pointer to function returning T", [...]
5532 T = getVariableArrayDecayedType(T);
5533 if (T->isArrayType() || T->isFunctionType())
5534 T = getDecayedType(T);
5535 return T.getUnqualifiedType();
5538 /// getArrayDecayedType - Return the properly qualified result of decaying the
5539 /// specified array type to a pointer. This operation is non-trivial when
5540 /// handling typedefs etc. The canonical type of "T" must be an array type,
5541 /// this returns a pointer to a properly qualified element of the array.
5543 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
5544 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
5545 // Get the element type with 'getAsArrayType' so that we don't lose any
5546 // typedefs in the element type of the array. This also handles propagation
5547 // of type qualifiers from the array type into the element type if present
5549 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5550 assert(PrettyArrayType && "Not an array type!");
5552 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
5554 // int x[restrict 4] -> int *restrict
5555 QualType Result = getQualifiedType(PtrTy,
5556 PrettyArrayType->getIndexTypeQualifiers());
5558 // int x[_Nullable] -> int * _Nullable
5559 if (auto Nullability = Ty->getNullability(*this)) {
5560 Result = const_cast<ASTContext *>(this)->getAttributedType(
5561 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5566 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5567 return getBaseElementType(array->getElementType());
5570 QualType ASTContext::getBaseElementType(QualType type) const {
5573 SplitQualType split = type.getSplitDesugaredType();
5574 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
5577 type = array->getElementType();
5578 qs.addConsistentQualifiers(split.Quals);
5581 return getQualifiedType(type, qs);
5584 /// getConstantArrayElementCount - Returns number of constant array elements.
5586 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5587 uint64_t ElementCount = 1;
5589 ElementCount *= CA->getSize().getZExtValue();
5590 CA = dyn_cast_or_null<ConstantArrayType>(
5591 CA->getElementType()->getAsArrayTypeUnsafe());
5593 return ElementCount;
5596 /// getFloatingRank - Return a relative rank for floating point types.
5597 /// This routine will assert if passed a built-in type that isn't a float.
5598 static FloatingRank getFloatingRank(QualType T) {
5599 if (const auto *CT = T->getAs<ComplexType>())
5600 return getFloatingRank(CT->getElementType());
5602 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5603 switch (T->getAs<BuiltinType>()->getKind()) {
5604 default: llvm_unreachable("getFloatingRank(): not a floating type");
5605 case BuiltinType::Float16: return Float16Rank;
5606 case BuiltinType::Half: return HalfRank;
5607 case BuiltinType::Float: return FloatRank;
5608 case BuiltinType::Double: return DoubleRank;
5609 case BuiltinType::LongDouble: return LongDoubleRank;
5610 case BuiltinType::Float128: return Float128Rank;
5614 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5615 /// point or a complex type (based on typeDomain/typeSize).
5616 /// 'typeDomain' is a real floating point or complex type.
5617 /// 'typeSize' is a real floating point or complex type.
5618 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5619 QualType Domain) const {
5620 FloatingRank EltRank = getFloatingRank(Size);
5621 if (Domain->isComplexType()) {
5624 case HalfRank: llvm_unreachable("Complex half is not supported");
5625 case FloatRank: return FloatComplexTy;
5626 case DoubleRank: return DoubleComplexTy;
5627 case LongDoubleRank: return LongDoubleComplexTy;
5628 case Float128Rank: return Float128ComplexTy;
5632 assert(Domain->isRealFloatingType() && "Unknown domain!");
5634 case Float16Rank: return HalfTy;
5635 case HalfRank: return HalfTy;
5636 case FloatRank: return FloatTy;
5637 case DoubleRank: return DoubleTy;
5638 case LongDoubleRank: return LongDoubleTy;
5639 case Float128Rank: return Float128Ty;
5641 llvm_unreachable("getFloatingRank(): illegal value for rank");
5644 /// getFloatingTypeOrder - Compare the rank of the two specified floating
5645 /// point types, ignoring the domain of the type (i.e. 'double' ==
5646 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
5647 /// LHS < RHS, return -1.
5648 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
5649 FloatingRank LHSR = getFloatingRank(LHS);
5650 FloatingRank RHSR = getFloatingRank(RHS);
5659 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
5660 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5662 return getFloatingTypeOrder(LHS, RHS);
5665 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5666 /// routine will assert if passed a built-in type that isn't an integer or enum,
5667 /// or if it is not canonicalized.
5668 unsigned ASTContext::getIntegerRank(const Type *T) const {
5669 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
5671 switch (cast<BuiltinType>(T)->getKind()) {
5672 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
5673 case BuiltinType::Bool:
5674 return 1 + (getIntWidth(BoolTy) << 3);
5675 case BuiltinType::Char_S:
5676 case BuiltinType::Char_U:
5677 case BuiltinType::SChar:
5678 case BuiltinType::UChar:
5679 return 2 + (getIntWidth(CharTy) << 3);
5680 case BuiltinType::Short:
5681 case BuiltinType::UShort:
5682 return 3 + (getIntWidth(ShortTy) << 3);
5683 case BuiltinType::Int:
5684 case BuiltinType::UInt:
5685 return 4 + (getIntWidth(IntTy) << 3);
5686 case BuiltinType::Long:
5687 case BuiltinType::ULong:
5688 return 5 + (getIntWidth(LongTy) << 3);
5689 case BuiltinType::LongLong:
5690 case BuiltinType::ULongLong:
5691 return 6 + (getIntWidth(LongLongTy) << 3);
5692 case BuiltinType::Int128:
5693 case BuiltinType::UInt128:
5694 return 7 + (getIntWidth(Int128Ty) << 3);
5698 /// Whether this is a promotable bitfield reference according
5699 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5701 /// \returns the type this bit-field will promote to, or NULL if no
5702 /// promotion occurs.
5703 QualType ASTContext::isPromotableBitField(Expr *E) const {
5704 if (E->isTypeDependent() || E->isValueDependent())
5707 // C++ [conv.prom]p5:
5708 // If the bit-field has an enumerated type, it is treated as any other
5709 // value of that type for promotion purposes.
5710 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5713 // FIXME: We should not do this unless E->refersToBitField() is true. This
5714 // matters in C where getSourceBitField() will find bit-fields for various
5715 // cases where the source expression is not a bit-field designator.
5717 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
5721 QualType FT = Field->getType();
5723 uint64_t BitWidth = Field->getBitWidthValue(*this);
5724 uint64_t IntSize = getTypeSize(IntTy);
5725 // C++ [conv.prom]p5:
5726 // A prvalue for an integral bit-field can be converted to a prvalue of type
5727 // int if int can represent all the values of the bit-field; otherwise, it
5728 // can be converted to unsigned int if unsigned int can represent all the
5729 // values of the bit-field. If the bit-field is larger yet, no integral
5730 // promotion applies to it.
5732 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5733 // If an int can represent all values of the original type (as restricted by
5734 // the width, for a bit-field), the value is converted to an int; otherwise,
5735 // it is converted to an unsigned int.
5737 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5738 // We perform that promotion here to match GCC and C++.
5739 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5740 // greater than that of 'int'. We perform that promotion to match GCC.
5741 if (BitWidth < IntSize)
5744 if (BitWidth == IntSize)
5745 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5747 // Bit-fields wider than int are not subject to promotions, and therefore act
5748 // like the base type. GCC has some weird bugs in this area that we
5749 // deliberately do not follow (GCC follows a pre-standard resolution to
5750 // C's DR315 which treats bit-width as being part of the type, and this leaks
5751 // into their semantics in some cases).
5755 /// getPromotedIntegerType - Returns the type that Promotable will
5756 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5758 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
5759 assert(!Promotable.isNull());
5760 assert(Promotable->isPromotableIntegerType());
5761 if (const auto *ET = Promotable->getAs<EnumType>())
5762 return ET->getDecl()->getPromotionType();
5764 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
5765 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5766 // (3.9.1) can be converted to a prvalue of the first of the following
5767 // types that can represent all the values of its underlying type:
5768 // int, unsigned int, long int, unsigned long int, long long int, or
5769 // unsigned long long int [...]
5770 // FIXME: Is there some better way to compute this?
5771 if (BT->getKind() == BuiltinType::WChar_S ||
5772 BT->getKind() == BuiltinType::WChar_U ||
5773 BT->getKind() == BuiltinType::Char8 ||
5774 BT->getKind() == BuiltinType::Char16 ||
5775 BT->getKind() == BuiltinType::Char32) {
5776 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5777 uint64_t FromSize = getTypeSize(BT);
5778 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5779 LongLongTy, UnsignedLongLongTy };
5780 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5781 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5782 if (FromSize < ToSize ||
5783 (FromSize == ToSize &&
5784 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5785 return PromoteTypes[Idx];
5787 llvm_unreachable("char type should fit into long long");
5791 // At this point, we should have a signed or unsigned integer type.
5792 if (Promotable->isSignedIntegerType())
5794 uint64_t PromotableSize = getIntWidth(Promotable);
5795 uint64_t IntSize = getIntWidth(IntTy);
5796 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5797 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5800 /// Recurses in pointer/array types until it finds an objc retainable
5801 /// type and returns its ownership.
5802 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5803 while (!T.isNull()) {
5804 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5805 return T.getObjCLifetime();
5806 if (T->isArrayType())
5807 T = getBaseElementType(T);
5808 else if (const auto *PT = T->getAs<PointerType>())
5809 T = PT->getPointeeType();
5810 else if (const auto *RT = T->getAs<ReferenceType>())
5811 T = RT->getPointeeType();
5816 return Qualifiers::OCL_None;
5819 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5820 // Incomplete enum types are not treated as integer types.
5821 // FIXME: In C++, enum types are never integer types.
5822 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5823 return ET->getDecl()->getIntegerType().getTypePtr();
5827 /// getIntegerTypeOrder - Returns the highest ranked integer type:
5828 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
5829 /// LHS < RHS, return -1.
5830 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
5831 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5832 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
5834 // Unwrap enums to their underlying type.
5835 if (const auto *ET = dyn_cast<EnumType>(LHSC))
5836 LHSC = getIntegerTypeForEnum(ET);
5837 if (const auto *ET = dyn_cast<EnumType>(RHSC))
5838 RHSC = getIntegerTypeForEnum(ET);
5840 if (LHSC == RHSC) return 0;
5842 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5843 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
5845 unsigned LHSRank = getIntegerRank(LHSC);
5846 unsigned RHSRank = getIntegerRank(RHSC);
5848 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5849 if (LHSRank == RHSRank) return 0;
5850 return LHSRank > RHSRank ? 1 : -1;
5853 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5855 // If the unsigned [LHS] type is larger, return it.
5856 if (LHSRank >= RHSRank)
5859 // If the signed type can represent all values of the unsigned type, it
5860 // wins. Because we are dealing with 2's complement and types that are
5861 // powers of two larger than each other, this is always safe.
5865 // If the unsigned [RHS] type is larger, return it.
5866 if (RHSRank >= LHSRank)
5869 // If the signed type can represent all values of the unsigned type, it
5870 // wins. Because we are dealing with 2's complement and types that are
5871 // powers of two larger than each other, this is always safe.
5875 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
5876 if (CFConstantStringTypeDecl)
5877 return CFConstantStringTypeDecl;
5879 assert(!CFConstantStringTagDecl &&
5880 "tag and typedef should be initialized together");
5881 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5882 CFConstantStringTagDecl->startDefinition();
5892 /// typedef struct __NSConstantString_tag {
5895 /// const char *str;
5897 /// } __NSConstantString;
5899 /// Swift ABI (4.1, 4.2)
5901 /// typedef struct __NSConstantString_tag {
5902 /// uintptr_t _cfisa;
5903 /// uintptr_t _swift_rc;
5904 /// _Atomic(uint64_t) _cfinfoa;
5905 /// const char *_ptr;
5906 /// uint32_t _length;
5907 /// } __NSConstantString;
5911 /// typedef struct __NSConstantString_tag {
5912 /// uintptr_t _cfisa;
5913 /// uintptr_t _swift_rc;
5914 /// _Atomic(uint64_t) _cfinfoa;
5915 /// const char *_ptr;
5916 /// uintptr_t _length;
5917 /// } __NSConstantString;
5919 const auto CFRuntime = getLangOpts().CFRuntime;
5920 if (static_cast<unsigned>(CFRuntime) <
5921 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
5922 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
5923 Fields[Count++] = { IntTy, "flags" };
5924 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
5925 Fields[Count++] = { LongTy, "length" };
5927 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
5928 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
5929 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
5930 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
5931 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5932 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5933 Fields[Count++] = { IntTy, "_ptr" };
5935 Fields[Count++] = { getUIntPtrType(), "_ptr" };
5939 for (unsigned i = 0; i < Count; ++i) {
5941 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
5942 SourceLocation(), &Idents.get(Fields[i].Name),
5943 Fields[i].Type, /*TInfo=*/nullptr,
5944 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5945 Field->setAccess(AS_public);
5946 CFConstantStringTagDecl->addDecl(Field);
5949 CFConstantStringTagDecl->completeDefinition();
5950 // This type is designed to be compatible with NSConstantString, but cannot
5951 // use the same name, since NSConstantString is an interface.
5952 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5953 CFConstantStringTypeDecl =
5954 buildImplicitTypedef(tagType, "__NSConstantString");
5956 return CFConstantStringTypeDecl;
5959 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5960 if (!CFConstantStringTagDecl)
5961 getCFConstantStringDecl(); // Build the tag and the typedef.
5962 return CFConstantStringTagDecl;
5965 // getCFConstantStringType - Return the type used for constant CFStrings.
5966 QualType ASTContext::getCFConstantStringType() const {
5967 return getTypedefType(getCFConstantStringDecl());
5970 QualType ASTContext::getObjCSuperType() const {
5971 if (ObjCSuperType.isNull()) {
5972 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
5973 TUDecl->addDecl(ObjCSuperTypeDecl);
5974 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5976 return ObjCSuperType;
5979 void ASTContext::setCFConstantStringType(QualType T) {
5980 const auto *TD = T->getAs<TypedefType>();
5981 assert(TD && "Invalid CFConstantStringType");
5982 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5983 const auto *TagType =
5984 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5985 assert(TagType && "Invalid CFConstantStringType");
5986 CFConstantStringTagDecl = TagType->getDecl();
5989 QualType ASTContext::getBlockDescriptorType() const {
5990 if (BlockDescriptorType)
5991 return getTagDeclType(BlockDescriptorType);
5994 // FIXME: Needs the FlagAppleBlock bit.
5995 RD = buildImplicitRecord("__block_descriptor");
5996 RD->startDefinition();
5998 QualType FieldTypes[] = {
6003 static const char *const FieldNames[] = {
6008 for (size_t i = 0; i < 2; ++i) {
6009 FieldDecl *Field = FieldDecl::Create(
6010 *this, RD, SourceLocation(), SourceLocation(),
6011 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6012 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6013 Field->setAccess(AS_public);
6017 RD->completeDefinition();
6019 BlockDescriptorType = RD;
6021 return getTagDeclType(BlockDescriptorType);
6024 QualType ASTContext::getBlockDescriptorExtendedType() const {
6025 if (BlockDescriptorExtendedType)
6026 return getTagDeclType(BlockDescriptorExtendedType);
6029 // FIXME: Needs the FlagAppleBlock bit.
6030 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6031 RD->startDefinition();
6033 QualType FieldTypes[] = {
6036 getPointerType(VoidPtrTy),
6037 getPointerType(VoidPtrTy)
6040 static const char *const FieldNames[] = {
6047 for (size_t i = 0; i < 4; ++i) {
6048 FieldDecl *Field = FieldDecl::Create(
6049 *this, RD, SourceLocation(), SourceLocation(),
6050 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6051 /*BitWidth=*/nullptr,
6052 /*Mutable=*/false, ICIS_NoInit);
6053 Field->setAccess(AS_public);
6057 RD->completeDefinition();
6059 BlockDescriptorExtendedType = RD;
6060 return getTagDeclType(BlockDescriptorExtendedType);
6063 TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
6064 const auto *BT = dyn_cast<BuiltinType>(T);
6067 if (isa<PipeType>(T))
6068 return TargetInfo::OCLTK_Pipe;
6070 return TargetInfo::OCLTK_Default;
6073 switch (BT->getKind()) {
6074 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6075 case BuiltinType::Id: \
6076 return TargetInfo::OCLTK_Image;
6077 #include "clang/Basic/OpenCLImageTypes.def"
6079 case BuiltinType::OCLClkEvent:
6080 return TargetInfo::OCLTK_ClkEvent;
6082 case BuiltinType::OCLEvent:
6083 return TargetInfo::OCLTK_Event;
6085 case BuiltinType::OCLQueue:
6086 return TargetInfo::OCLTK_Queue;
6088 case BuiltinType::OCLReserveID:
6089 return TargetInfo::OCLTK_ReserveID;
6091 case BuiltinType::OCLSampler:
6092 return TargetInfo::OCLTK_Sampler;
6095 return TargetInfo::OCLTK_Default;
6099 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6100 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6103 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6104 /// requires copy/dispose. Note that this must match the logic
6105 /// in buildByrefHelpers.
6106 bool ASTContext::BlockRequiresCopying(QualType Ty,
6108 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
6109 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
6110 if (!copyExpr && record->hasTrivialDestructor()) return false;
6115 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6117 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6120 if (!Ty->isObjCRetainableType()) return false;
6122 Qualifiers qs = Ty.getQualifiers();
6124 // If we have lifetime, that dominates.
6125 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
6127 case Qualifiers::OCL_None: llvm_unreachable("impossible");
6129 // These are just bits as far as the runtime is concerned.
6130 case Qualifiers::OCL_ExplicitNone:
6131 case Qualifiers::OCL_Autoreleasing:
6134 // These cases should have been taken care of when checking the type's
6136 case Qualifiers::OCL_Weak:
6137 case Qualifiers::OCL_Strong:
6138 llvm_unreachable("impossible");
6140 llvm_unreachable("fell out of lifetime switch!");
6142 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6143 Ty->isObjCObjectPointerType());
6146 bool ASTContext::getByrefLifetime(QualType Ty,
6147 Qualifiers::ObjCLifetime &LifeTime,
6148 bool &HasByrefExtendedLayout) const {
6149 if (!getLangOpts().ObjC ||
6150 getLangOpts().getGC() != LangOptions::NonGC)
6153 HasByrefExtendedLayout = false;
6154 if (Ty->isRecordType()) {
6155 HasByrefExtendedLayout = true;
6156 LifeTime = Qualifiers::OCL_None;
6157 } else if ((LifeTime = Ty.getObjCLifetime())) {
6158 // Honor the ARC qualifiers.
6159 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6161 LifeTime = Qualifiers::OCL_ExplicitNone;
6163 LifeTime = Qualifiers::OCL_None;
6168 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6169 if (!ObjCInstanceTypeDecl)
6170 ObjCInstanceTypeDecl =
6171 buildImplicitTypedef(getObjCIdType(), "instancetype");
6172 return ObjCInstanceTypeDecl;
6175 // This returns true if a type has been typedefed to BOOL:
6176 // typedef <type> BOOL;
6177 static bool isTypeTypedefedAsBOOL(QualType T) {
6178 if (const auto *TT = dyn_cast<TypedefType>(T))
6179 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6180 return II->isStr("BOOL");
6185 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
6187 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
6188 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6189 return CharUnits::Zero();
6191 CharUnits sz = getTypeSizeInChars(type);
6193 // Make all integer and enum types at least as large as an int
6194 if (sz.isPositive() && type->isIntegralOrEnumerationType())
6195 sz = std::max(sz, getTypeSizeInChars(IntTy));
6196 // Treat arrays as pointers, since that's how they're passed in.
6197 else if (type->isArrayType())
6198 sz = getTypeSizeInChars(VoidPtrTy);
6202 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
6203 return getTargetInfo().getCXXABI().isMicrosoft() &&
6204 VD->isStaticDataMember() &&
6205 VD->getType()->isIntegralOrEnumerationType() &&
6206 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
6209 ASTContext::InlineVariableDefinitionKind
6210 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6211 if (!VD->isInline())
6212 return InlineVariableDefinitionKind::None;
6214 // In almost all cases, it's a weak definition.
6215 auto *First = VD->getFirstDecl();
6216 if (First->isInlineSpecified() || !First->isStaticDataMember())
6217 return InlineVariableDefinitionKind::Weak;
6219 // If there's a file-context declaration in this translation unit, it's a
6220 // non-discardable definition.
6221 for (auto *D : VD->redecls())
6222 if (D->getLexicalDeclContext()->isFileContext() &&
6223 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
6224 return InlineVariableDefinitionKind::Strong;
6226 // If we've not seen one yet, we don't know.
6227 return InlineVariableDefinitionKind::WeakUnknown;
6230 static std::string charUnitsToString(const CharUnits &CU) {
6231 return llvm::itostr(CU.getQuantity());
6234 /// getObjCEncodingForBlock - Return the encoded type for this block
6236 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6239 const BlockDecl *Decl = Expr->getBlockDecl();
6241 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6242 // Encode result type.
6243 if (getLangOpts().EncodeExtendedBlockSig)
6244 getObjCEncodingForMethodParameter(
6245 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
6248 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
6249 // Compute size of all parameters.
6250 // Start with computing size of a pointer in number of bytes.
6251 // FIXME: There might(should) be a better way of doing this computation!
6252 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6253 CharUnits ParmOffset = PtrSize;
6254 for (auto PI : Decl->parameters()) {
6255 QualType PType = PI->getType();
6256 CharUnits sz = getObjCEncodingTypeSize(PType);
6259 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
6262 // Size of the argument frame
6263 S += charUnitsToString(ParmOffset);
6264 // Block pointer and offset.
6268 ParmOffset = PtrSize;
6269 for (auto PVDecl : Decl->parameters()) {
6270 QualType PType = PVDecl->getOriginalType();
6271 if (const auto *AT =
6272 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6273 // Use array's original type only if it has known number of
6275 if (!isa<ConstantArrayType>(AT))
6276 PType = PVDecl->getType();
6277 } else if (PType->isFunctionType())
6278 PType = PVDecl->getType();
6279 if (getLangOpts().EncodeExtendedBlockSig)
6280 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6281 S, true /*Extended*/);
6283 getObjCEncodingForType(PType, S);
6284 S += charUnitsToString(ParmOffset);
6285 ParmOffset += getObjCEncodingTypeSize(PType);
6292 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6294 // Encode result type.
6295 getObjCEncodingForType(Decl->getReturnType(), S);
6296 CharUnits ParmOffset;
6297 // Compute size of all parameters.
6298 for (auto PI : Decl->parameters()) {
6299 QualType PType = PI->getType();
6300 CharUnits sz = getObjCEncodingTypeSize(PType);
6304 assert(sz.isPositive() &&
6305 "getObjCEncodingForFunctionDecl - Incomplete param type");
6308 S += charUnitsToString(ParmOffset);
6309 ParmOffset = CharUnits::Zero();
6312 for (auto PVDecl : Decl->parameters()) {
6313 QualType PType = PVDecl->getOriginalType();
6314 if (const auto *AT =
6315 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6316 // Use array's original type only if it has known number of
6318 if (!isa<ConstantArrayType>(AT))
6319 PType = PVDecl->getType();
6320 } else if (PType->isFunctionType())
6321 PType = PVDecl->getType();
6322 getObjCEncodingForType(PType, S);
6323 S += charUnitsToString(ParmOffset);
6324 ParmOffset += getObjCEncodingTypeSize(PType);
6330 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
6331 /// method parameter or return type. If Extended, include class names and
6332 /// block object types.
6333 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6334 QualType T, std::string& S,
6335 bool Extended) const {
6336 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6337 getObjCEncodingForTypeQualifier(QT, S);
6338 // Encode parameter type.
6339 ObjCEncOptions Options = ObjCEncOptions()
6340 .setExpandPointedToStructures()
6341 .setExpandStructures()
6342 .setIsOutermostType();
6344 Options.setEncodeBlockParameters().setEncodeClassNames();
6345 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
6348 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
6350 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6351 bool Extended) const {
6352 // FIXME: This is not very efficient.
6353 // Encode return type.
6355 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6356 Decl->getReturnType(), S, Extended);
6357 // Compute size of all parameters.
6358 // Start with computing size of a pointer in number of bytes.
6359 // FIXME: There might(should) be a better way of doing this computation!
6360 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6361 // The first two arguments (self and _cmd) are pointers; account for
6363 CharUnits ParmOffset = 2 * PtrSize;
6364 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
6365 E = Decl->sel_param_end(); PI != E; ++PI) {
6366 QualType PType = (*PI)->getType();
6367 CharUnits sz = getObjCEncodingTypeSize(PType);
6371 assert(sz.isPositive() &&
6372 "getObjCEncodingForMethodDecl - Incomplete param type");
6375 S += charUnitsToString(ParmOffset);
6377 S += charUnitsToString(PtrSize);
6380 ParmOffset = 2 * PtrSize;
6381 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
6382 E = Decl->sel_param_end(); PI != E; ++PI) {
6383 const ParmVarDecl *PVDecl = *PI;
6384 QualType PType = PVDecl->getOriginalType();
6385 if (const auto *AT =
6386 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6387 // Use array's original type only if it has known number of
6389 if (!isa<ConstantArrayType>(AT))
6390 PType = PVDecl->getType();
6391 } else if (PType->isFunctionType())
6392 PType = PVDecl->getType();
6393 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
6394 PType, S, Extended);
6395 S += charUnitsToString(ParmOffset);
6396 ParmOffset += getObjCEncodingTypeSize(PType);
6402 ObjCPropertyImplDecl *
6403 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6404 const ObjCPropertyDecl *PD,
6405 const Decl *Container) const {
6408 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
6409 for (auto *PID : CID->property_impls())
6410 if (PID->getPropertyDecl() == PD)
6413 const auto *OID = cast<ObjCImplementationDecl>(Container);
6414 for (auto *PID : OID->property_impls())
6415 if (PID->getPropertyDecl() == PD)
6421 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
6422 /// property declaration. If non-NULL, Container must be either an
6423 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6424 /// NULL when getting encodings for protocol properties.
6425 /// Property attributes are stored as a comma-delimited C string. The simple
6426 /// attributes readonly and bycopy are encoded as single characters. The
6427 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
6428 /// encoded as single characters, followed by an identifier. Property types
6429 /// are also encoded as a parametrized attribute. The characters used to encode
6430 /// these attributes are defined by the following enumeration:
6432 /// enum PropertyAttributes {
6433 /// kPropertyReadOnly = 'R', // property is read-only.
6434 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6435 /// kPropertyByref = '&', // property is a reference to the value last assigned
6436 /// kPropertyDynamic = 'D', // property is dynamic
6437 /// kPropertyGetter = 'G', // followed by getter selector name
6438 /// kPropertySetter = 'S', // followed by setter selector name
6439 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
6440 /// kPropertyType = 'T' // followed by old-style type encoding.
6441 /// kPropertyWeak = 'W' // 'weak' property
6442 /// kPropertyStrong = 'P' // property GC'able
6443 /// kPropertyNonAtomic = 'N' // property non-atomic
6447 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6448 const Decl *Container) const {
6449 // Collect information from the property implementation decl(s).
6450 bool Dynamic = false;
6451 ObjCPropertyImplDecl *SynthesizePID = nullptr;
6453 if (ObjCPropertyImplDecl *PropertyImpDecl =
6454 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6455 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6458 SynthesizePID = PropertyImpDecl;
6461 // FIXME: This is not very efficient.
6462 std::string S = "T";
6464 // Encode result type.
6465 // GCC has some special rules regarding encoding of properties which
6466 // closely resembles encoding of ivars.
6467 getObjCEncodingForPropertyType(PD->getType(), S);
6469 if (PD->isReadOnly()) {
6471 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6473 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6475 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6478 switch (PD->getSetterKind()) {
6479 case ObjCPropertyDecl::Assign: break;
6480 case ObjCPropertyDecl::Copy: S += ",C"; break;
6481 case ObjCPropertyDecl::Retain: S += ",&"; break;
6482 case ObjCPropertyDecl::Weak: S += ",W"; break;
6486 // It really isn't clear at all what this means, since properties
6487 // are "dynamic by default".
6491 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6494 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6496 S += PD->getGetterName().getAsString();
6499 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6501 S += PD->getSetterName().getAsString();
6504 if (SynthesizePID) {
6505 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6507 S += OID->getNameAsString();
6510 // FIXME: OBJCGC: weak & strong
6514 /// getLegacyIntegralTypeEncoding -
6515 /// Another legacy compatibility encoding: 32-bit longs are encoded as
6516 /// 'l' or 'L' , but not always. For typedefs, we need to use
6517 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
6518 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
6519 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
6520 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
6521 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
6522 PointeeTy = UnsignedIntTy;
6524 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
6530 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
6531 const FieldDecl *Field,
6532 QualType *NotEncodedT) const {
6533 // We follow the behavior of gcc, expanding structures which are
6534 // directly pointed to, and expanding embedded structures. Note that
6535 // these rules are sufficient to prevent recursive encoding of the
6537 getObjCEncodingForTypeImpl(T, S,
6539 .setExpandPointedToStructures()
6540 .setExpandStructures()
6541 .setIsOutermostType(),
6542 Field, NotEncodedT);
6545 void ASTContext::getObjCEncodingForPropertyType(QualType T,
6546 std::string& S) const {
6547 // Encode result type.
6548 // GCC has some special rules regarding encoding of properties which
6549 // closely resembles encoding of ivars.
6550 getObjCEncodingForTypeImpl(T, S,
6552 .setExpandPointedToStructures()
6553 .setExpandStructures()
6554 .setIsOutermostType()
6555 .setEncodingProperty(),
6559 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6560 BuiltinType::Kind kind) {
6562 case BuiltinType::Void: return 'v';
6563 case BuiltinType::Bool: return 'B';
6564 case BuiltinType::Char8:
6565 case BuiltinType::Char_U:
6566 case BuiltinType::UChar: return 'C';
6567 case BuiltinType::Char16:
6568 case BuiltinType::UShort: return 'S';
6569 case BuiltinType::Char32:
6570 case BuiltinType::UInt: return 'I';
6571 case BuiltinType::ULong:
6572 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
6573 case BuiltinType::UInt128: return 'T';
6574 case BuiltinType::ULongLong: return 'Q';
6575 case BuiltinType::Char_S:
6576 case BuiltinType::SChar: return 'c';
6577 case BuiltinType::Short: return 's';
6578 case BuiltinType::WChar_S:
6579 case BuiltinType::WChar_U:
6580 case BuiltinType::Int: return 'i';
6581 case BuiltinType::Long:
6582 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
6583 case BuiltinType::LongLong: return 'q';
6584 case BuiltinType::Int128: return 't';
6585 case BuiltinType::Float: return 'f';
6586 case BuiltinType::Double: return 'd';
6587 case BuiltinType::LongDouble: return 'D';
6588 case BuiltinType::NullPtr: return '*'; // like char*
6590 case BuiltinType::Float16:
6591 case BuiltinType::Float128:
6592 case BuiltinType::Half:
6593 case BuiltinType::ShortAccum:
6594 case BuiltinType::Accum:
6595 case BuiltinType::LongAccum:
6596 case BuiltinType::UShortAccum:
6597 case BuiltinType::UAccum:
6598 case BuiltinType::ULongAccum:
6599 case BuiltinType::ShortFract:
6600 case BuiltinType::Fract:
6601 case BuiltinType::LongFract:
6602 case BuiltinType::UShortFract:
6603 case BuiltinType::UFract:
6604 case BuiltinType::ULongFract:
6605 case BuiltinType::SatShortAccum:
6606 case BuiltinType::SatAccum:
6607 case BuiltinType::SatLongAccum:
6608 case BuiltinType::SatUShortAccum:
6609 case BuiltinType::SatUAccum:
6610 case BuiltinType::SatULongAccum:
6611 case BuiltinType::SatShortFract:
6612 case BuiltinType::SatFract:
6613 case BuiltinType::SatLongFract:
6614 case BuiltinType::SatUShortFract:
6615 case BuiltinType::SatUFract:
6616 case BuiltinType::SatULongFract:
6617 // FIXME: potentially need @encodes for these!
6620 case BuiltinType::ObjCId:
6621 case BuiltinType::ObjCClass:
6622 case BuiltinType::ObjCSel:
6623 llvm_unreachable("@encoding ObjC primitive type");
6625 // OpenCL and placeholder types don't need @encodings.
6626 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6627 case BuiltinType::Id:
6628 #include "clang/Basic/OpenCLImageTypes.def"
6629 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6630 case BuiltinType::Id:
6631 #include "clang/Basic/OpenCLExtensionTypes.def"
6632 case BuiltinType::OCLEvent:
6633 case BuiltinType::OCLClkEvent:
6634 case BuiltinType::OCLQueue:
6635 case BuiltinType::OCLReserveID:
6636 case BuiltinType::OCLSampler:
6637 case BuiltinType::Dependent:
6638 #define BUILTIN_TYPE(KIND, ID)
6639 #define PLACEHOLDER_TYPE(KIND, ID) \
6640 case BuiltinType::KIND:
6641 #include "clang/AST/BuiltinTypes.def"
6642 llvm_unreachable("invalid builtin type for @encode");
6644 llvm_unreachable("invalid BuiltinType::Kind value");
6647 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6648 EnumDecl *Enum = ET->getDecl();
6650 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6651 if (!Enum->isFixed())
6654 // The encoding of a fixed enum type matches its fixed underlying type.
6655 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
6656 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
6659 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
6660 QualType T, const FieldDecl *FD) {
6661 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
6663 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6664 // The GNU runtime requires more information; bitfields are encoded as b,
6665 // then the offset (in bits) of the first element, then the type of the
6666 // bitfield, then the size in bits. For example, in this structure:
6673 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6674 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6675 // information is not especially sensible, but we're stuck with it for
6676 // compatibility with GCC, although providing it breaks anything that
6677 // actually uses runtime introspection and wants to work on both runtimes...
6678 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
6681 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6682 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6685 const RecordDecl *RD = FD->getParent();
6686 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6687 Offset = RL.getFieldOffset(FD->getFieldIndex());
6690 S += llvm::utostr(Offset);
6692 if (const auto *ET = T->getAs<EnumType>())
6693 S += ObjCEncodingForEnumType(Ctx, ET);
6695 const auto *BT = T->castAs<BuiltinType>();
6696 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6699 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
6702 // FIXME: Use SmallString for accumulating string.
6703 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
6704 const ObjCEncOptions Options,
6705 const FieldDecl *FD,
6706 QualType *NotEncodedT) const {
6707 CanQualType CT = getCanonicalType(T);
6708 switch (CT->getTypeClass()) {
6711 if (FD && FD->isBitField())
6712 return EncodeBitField(this, S, T, FD);
6713 if (const auto *BT = dyn_cast<BuiltinType>(CT))
6714 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6716 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
6719 case Type::Complex: {
6720 const auto *CT = T->castAs<ComplexType>();
6722 getObjCEncodingForTypeImpl(CT->getElementType(), S, ObjCEncOptions(),
6727 case Type::Atomic: {
6728 const auto *AT = T->castAs<AtomicType>();
6730 getObjCEncodingForTypeImpl(AT->getValueType(), S, ObjCEncOptions(),
6735 // encoding for pointer or reference types.
6737 case Type::LValueReference:
6738 case Type::RValueReference: {
6740 if (isa<PointerType>(CT)) {
6741 const auto *PT = T->castAs<PointerType>();
6742 if (PT->isObjCSelType()) {
6746 PointeeTy = PT->getPointeeType();
6748 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6751 bool isReadOnly = false;
6752 // For historical/compatibility reasons, the read-only qualifier of the
6753 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6754 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
6755 // Also, do not emit the 'r' for anything but the outermost type!
6756 if (isa<TypedefType>(T.getTypePtr())) {
6757 if (Options.IsOutermostType() && T.isConstQualified()) {
6761 } else if (Options.IsOutermostType()) {
6762 QualType P = PointeeTy;
6763 while (P->getAs<PointerType>())
6764 P = P->getAs<PointerType>()->getPointeeType();
6765 if (P.isConstQualified()) {
6771 // Another legacy compatibility encoding. Some ObjC qualifier and type
6772 // combinations need to be rearranged.
6773 // Rewrite "in const" from "nr" to "rn"
6774 if (StringRef(S).endswith("nr"))
6775 S.replace(S.end()-2, S.end(), "rn");
6778 if (PointeeTy->isCharType()) {
6779 // char pointer types should be encoded as '*' unless it is a
6780 // type that has been typedef'd to 'BOOL'.
6781 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
6785 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
6786 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6787 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6791 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6792 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6799 getLegacyIntegralTypeEncoding(PointeeTy);
6801 ObjCEncOptions NewOptions;
6802 if (Options.ExpandPointedToStructures())
6803 NewOptions.setExpandStructures();
6804 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
6805 /*Field=*/nullptr, NotEncodedT);
6809 case Type::ConstantArray:
6810 case Type::IncompleteArray:
6811 case Type::VariableArray: {
6812 const auto *AT = cast<ArrayType>(CT);
6814 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
6815 // Incomplete arrays are encoded as a pointer to the array element.
6818 getObjCEncodingForTypeImpl(
6819 AT->getElementType(), S,
6820 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
6824 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
6825 S += llvm::utostr(CAT->getSize().getZExtValue());
6827 //Variable length arrays are encoded as a regular array with 0 elements.
6828 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6829 "Unknown array type!");
6833 getObjCEncodingForTypeImpl(
6834 AT->getElementType(), S,
6835 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
6842 case Type::FunctionNoProto:
6843 case Type::FunctionProto:
6847 case Type::Record: {
6848 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
6849 S += RDecl->isUnion() ? '(' : '{';
6850 // Anonymous structures print as '?'
6851 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6853 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6854 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
6855 llvm::raw_string_ostream OS(S);
6856 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6857 getPrintingPolicy());
6862 if (Options.ExpandStructures()) {
6864 if (!RDecl->isUnion()) {
6865 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
6867 for (const auto *Field : RDecl->fields()) {
6870 S += Field->getNameAsString();
6874 // Special case bit-fields.
6875 if (Field->isBitField()) {
6876 getObjCEncodingForTypeImpl(Field->getType(), S,
6877 ObjCEncOptions().setExpandStructures(),
6880 QualType qt = Field->getType();
6881 getLegacyIntegralTypeEncoding(qt);
6882 getObjCEncodingForTypeImpl(
6884 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
6890 S += RDecl->isUnion() ? ')' : '}';
6894 case Type::BlockPointer: {
6895 const auto *BT = T->castAs<BlockPointerType>();
6896 S += "@?"; // Unlike a pointer-to-function, which is "^?".
6897 if (Options.EncodeBlockParameters()) {
6898 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
6901 // Block return type
6902 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
6903 Options.forComponentType(), FD, NotEncodedT);
6907 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
6908 for (const auto &I : FPT->param_types())
6909 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
6917 case Type::ObjCObject: {
6918 // hack to match legacy encoding of *id and *Class
6919 QualType Ty = getObjCObjectPointerType(CT);
6920 if (Ty->isObjCIdType()) {
6921 S += "{objc_object=}";
6924 else if (Ty->isObjCClassType()) {
6925 S += "{objc_class=}";
6928 // TODO: Double check to make sure this intentionally falls through.
6932 case Type::ObjCInterface: {
6933 // Ignore protocol qualifiers when mangling at this level.
6934 // @encode(class_name)
6935 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
6937 S += OI->getObjCRuntimeNameAsString();
6938 if (Options.ExpandStructures()) {
6940 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6941 DeepCollectObjCIvars(OI, true, Ivars);
6942 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6943 const FieldDecl *Field = Ivars[i];
6944 if (Field->isBitField())
6945 getObjCEncodingForTypeImpl(Field->getType(), S,
6946 ObjCEncOptions().setExpandStructures(),
6949 getObjCEncodingForTypeImpl(Field->getType(), S,
6950 ObjCEncOptions().setExpandStructures(), FD,
6958 case Type::ObjCObjectPointer: {
6959 const auto *OPT = T->castAs<ObjCObjectPointerType>();
6960 if (OPT->isObjCIdType()) {
6965 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6966 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6967 // Since this is a binary compatibility issue, need to consult with
6968 // runtime folks. Fortunately, this is a *very* obscure construct.
6973 if (OPT->isObjCQualifiedIdType()) {
6974 getObjCEncodingForTypeImpl(
6976 Options.keepingOnly(ObjCEncOptions()
6977 .setExpandPointedToStructures()
6978 .setExpandStructures()),
6980 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
6981 // Note that we do extended encoding of protocol qualifer list
6982 // Only when doing ivar or property encoding.
6984 for (const auto *I : OPT->quals()) {
6986 S += I->getObjCRuntimeNameAsString();
6995 if (OPT->getInterfaceDecl() &&
6996 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
6998 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
6999 for (const auto *I : OPT->quals()) {
7001 S += I->getObjCRuntimeNameAsString();
7009 // gcc just blithely ignores member pointers.
7010 // FIXME: we should do better than that. 'M' is available.
7011 case Type::MemberPointer:
7012 // This matches gcc's encoding, even though technically it is insufficient.
7013 //FIXME. We should do a better job than gcc.
7015 case Type::ExtVector:
7016 // Until we have a coherent encoding of these three types, issue warning.
7021 // We could see an undeduced auto type here during error recovery.
7024 case Type::DeducedTemplateSpecialization:
7028 #define ABSTRACT_TYPE(KIND, BASE)
7029 #define TYPE(KIND, BASE)
7030 #define DEPENDENT_TYPE(KIND, BASE) \
7032 #define NON_CANONICAL_TYPE(KIND, BASE) \
7034 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7036 #include "clang/AST/TypeNodes.def"
7037 llvm_unreachable("@encode for dependent type!");
7039 llvm_unreachable("bad type kind!");
7042 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7044 const FieldDecl *FD,
7046 QualType *NotEncodedT) const {
7047 assert(RDecl && "Expected non-null RecordDecl");
7048 assert(!RDecl->isUnion() && "Should not be called for unions");
7049 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
7052 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
7053 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7054 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7057 for (const auto &BI : CXXRec->bases()) {
7058 if (!BI.isVirtual()) {
7059 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7060 if (base->isEmpty())
7062 uint64_t offs = toBits(layout.getBaseClassOffset(base));
7063 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7064 std::make_pair(offs, base));
7070 for (auto *Field : RDecl->fields()) {
7071 uint64_t offs = layout.getFieldOffset(i);
7072 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7073 std::make_pair(offs, Field));
7077 if (CXXRec && includeVBases) {
7078 for (const auto &BI : CXXRec->vbases()) {
7079 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7080 if (base->isEmpty())
7082 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
7083 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7084 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
7085 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7086 std::make_pair(offs, base));
7092 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7094 size = layout.getSize();
7098 uint64_t CurOffs = 0;
7100 std::multimap<uint64_t, NamedDecl *>::iterator
7101 CurLayObj = FieldOrBaseOffsets.begin();
7103 if (CXXRec && CXXRec->isDynamicClass() &&
7104 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
7107 std::string recname = CXXRec->getNameAsString();
7108 if (recname.empty()) recname = "?";
7114 CurOffs += getTypeSize(VoidPtrTy);
7118 if (!RDecl->hasFlexibleArrayMember()) {
7119 // Mark the end of the structure.
7120 uint64_t offs = toBits(size);
7121 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7122 std::make_pair(offs, nullptr));
7125 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
7127 assert(CurOffs <= CurLayObj->first);
7128 if (CurOffs < CurLayObj->first) {
7129 uint64_t padding = CurLayObj->first - CurOffs;
7130 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7131 // packing/alignment of members is different that normal, in which case
7132 // the encoding will be out-of-sync with the real layout.
7133 // If the runtime switches to just consider the size of types without
7134 // taking into account alignment, we could make padding explicit in the
7135 // encoding (e.g. using arrays of chars). The encoding strings would be
7136 // longer then though.
7141 NamedDecl *dcl = CurLayObj->second;
7143 break; // reached end of structure.
7145 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
7146 // We expand the bases without their virtual bases since those are going
7147 // in the initial structure. Note that this differs from gcc which
7148 // expands virtual bases each time one is encountered in the hierarchy,
7149 // making the encoding type bigger than it really is.
7150 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7152 assert(!base->isEmpty());
7154 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
7157 const auto *field = cast<FieldDecl>(dcl);
7160 S += field->getNameAsString();
7164 if (field->isBitField()) {
7165 EncodeBitField(this, S, field->getType(), field);
7167 CurOffs += field->getBitWidthValue(*this);
7170 QualType qt = field->getType();
7171 getLegacyIntegralTypeEncoding(qt);
7172 getObjCEncodingForTypeImpl(
7173 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7176 CurOffs += getTypeSize(field->getType());
7183 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
7184 std::string& S) const {
7185 if (QT & Decl::OBJC_TQ_In)
7187 if (QT & Decl::OBJC_TQ_Inout)
7189 if (QT & Decl::OBJC_TQ_Out)
7191 if (QT & Decl::OBJC_TQ_Bycopy)
7193 if (QT & Decl::OBJC_TQ_Byref)
7195 if (QT & Decl::OBJC_TQ_Oneway)
7199 TypedefDecl *ASTContext::getObjCIdDecl() const {
7201 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
7202 T = getObjCObjectPointerType(T);
7203 ObjCIdDecl = buildImplicitTypedef(T, "id");
7208 TypedefDecl *ASTContext::getObjCSelDecl() const {
7210 QualType T = getPointerType(ObjCBuiltinSelTy);
7211 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
7216 TypedefDecl *ASTContext::getObjCClassDecl() const {
7217 if (!ObjCClassDecl) {
7218 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
7219 T = getObjCObjectPointerType(T);
7220 ObjCClassDecl = buildImplicitTypedef(T, "Class");
7222 return ObjCClassDecl;
7225 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7226 if (!ObjCProtocolClassDecl) {
7227 ObjCProtocolClassDecl
7228 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
7230 &Idents.get("Protocol"),
7231 /*typeParamList=*/nullptr,
7232 /*PrevDecl=*/nullptr,
7233 SourceLocation(), true);
7236 return ObjCProtocolClassDecl;
7239 //===----------------------------------------------------------------------===//
7240 // __builtin_va_list Construction Functions
7241 //===----------------------------------------------------------------------===//
7243 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7245 // typedef char* __builtin[_ms]_va_list;
7246 QualType T = Context->getPointerType(Context->CharTy);
7247 return Context->buildImplicitTypedef(T, Name);
7250 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7251 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7254 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7255 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
7258 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7259 // typedef void* __builtin_va_list;
7260 QualType T = Context->getPointerType(Context->VoidTy);
7261 return Context->buildImplicitTypedef(T, "__builtin_va_list");
7264 static TypedefDecl *
7265 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
7267 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
7268 if (Context->getLangOpts().CPlusPlus) {
7269 // namespace std { struct __va_list {
7271 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7272 Context->getTranslationUnitDecl(),
7273 /*Inline*/ false, SourceLocation(),
7274 SourceLocation(), &Context->Idents.get("std"),
7275 /*PrevDecl*/ nullptr);
7277 VaListTagDecl->setDeclContext(NS);
7280 VaListTagDecl->startDefinition();
7282 const size_t NumFields = 5;
7283 QualType FieldTypes[NumFields];
7284 const char *FieldNames[NumFields];
7287 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7288 FieldNames[0] = "__stack";
7291 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7292 FieldNames[1] = "__gr_top";
7295 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7296 FieldNames[2] = "__vr_top";
7299 FieldTypes[3] = Context->IntTy;
7300 FieldNames[3] = "__gr_offs";
7303 FieldTypes[4] = Context->IntTy;
7304 FieldNames[4] = "__vr_offs";
7307 for (unsigned i = 0; i < NumFields; ++i) {
7308 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7312 &Context->Idents.get(FieldNames[i]),
7313 FieldTypes[i], /*TInfo=*/nullptr,
7314 /*BitWidth=*/nullptr,
7317 Field->setAccess(AS_public);
7318 VaListTagDecl->addDecl(Field);
7320 VaListTagDecl->completeDefinition();
7321 Context->VaListTagDecl = VaListTagDecl;
7322 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7324 // } __builtin_va_list;
7325 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
7328 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7329 // typedef struct __va_list_tag {
7330 RecordDecl *VaListTagDecl;
7332 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7333 VaListTagDecl->startDefinition();
7335 const size_t NumFields = 5;
7336 QualType FieldTypes[NumFields];
7337 const char *FieldNames[NumFields];
7339 // unsigned char gpr;
7340 FieldTypes[0] = Context->UnsignedCharTy;
7341 FieldNames[0] = "gpr";
7343 // unsigned char fpr;
7344 FieldTypes[1] = Context->UnsignedCharTy;
7345 FieldNames[1] = "fpr";
7347 // unsigned short reserved;
7348 FieldTypes[2] = Context->UnsignedShortTy;
7349 FieldNames[2] = "reserved";
7351 // void* overflow_arg_area;
7352 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7353 FieldNames[3] = "overflow_arg_area";
7355 // void* reg_save_area;
7356 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7357 FieldNames[4] = "reg_save_area";
7360 for (unsigned i = 0; i < NumFields; ++i) {
7361 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7364 &Context->Idents.get(FieldNames[i]),
7365 FieldTypes[i], /*TInfo=*/nullptr,
7366 /*BitWidth=*/nullptr,
7369 Field->setAccess(AS_public);
7370 VaListTagDecl->addDecl(Field);
7372 VaListTagDecl->completeDefinition();
7373 Context->VaListTagDecl = VaListTagDecl;
7374 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7377 TypedefDecl *VaListTagTypedefDecl =
7378 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7380 QualType VaListTagTypedefType =
7381 Context->getTypedefType(VaListTagTypedefDecl);
7383 // typedef __va_list_tag __builtin_va_list[1];
7384 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7385 QualType VaListTagArrayType
7386 = Context->getConstantArrayType(VaListTagTypedefType,
7387 Size, ArrayType::Normal, 0);
7388 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7391 static TypedefDecl *
7392 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
7393 // struct __va_list_tag {
7394 RecordDecl *VaListTagDecl;
7395 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7396 VaListTagDecl->startDefinition();
7398 const size_t NumFields = 4;
7399 QualType FieldTypes[NumFields];
7400 const char *FieldNames[NumFields];
7402 // unsigned gp_offset;
7403 FieldTypes[0] = Context->UnsignedIntTy;
7404 FieldNames[0] = "gp_offset";
7406 // unsigned fp_offset;
7407 FieldTypes[1] = Context->UnsignedIntTy;
7408 FieldNames[1] = "fp_offset";
7410 // void* overflow_arg_area;
7411 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7412 FieldNames[2] = "overflow_arg_area";
7414 // void* reg_save_area;
7415 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7416 FieldNames[3] = "reg_save_area";
7419 for (unsigned i = 0; i < NumFields; ++i) {
7420 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7424 &Context->Idents.get(FieldNames[i]),
7425 FieldTypes[i], /*TInfo=*/nullptr,
7426 /*BitWidth=*/nullptr,
7429 Field->setAccess(AS_public);
7430 VaListTagDecl->addDecl(Field);
7432 VaListTagDecl->completeDefinition();
7433 Context->VaListTagDecl = VaListTagDecl;
7434 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7438 // typedef struct __va_list_tag __builtin_va_list[1];
7439 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7440 QualType VaListTagArrayType =
7441 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
7442 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7445 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7446 // typedef int __builtin_va_list[4];
7447 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
7448 QualType IntArrayType =
7449 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
7450 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
7453 static TypedefDecl *
7454 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
7456 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
7457 if (Context->getLangOpts().CPlusPlus) {
7458 // namespace std { struct __va_list {
7460 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7461 Context->getTranslationUnitDecl(),
7462 /*Inline*/false, SourceLocation(),
7463 SourceLocation(), &Context->Idents.get("std"),
7464 /*PrevDecl*/ nullptr);
7466 VaListDecl->setDeclContext(NS);
7469 VaListDecl->startDefinition();
7472 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7476 &Context->Idents.get("__ap"),
7477 Context->getPointerType(Context->VoidTy),
7479 /*BitWidth=*/nullptr,
7482 Field->setAccess(AS_public);
7483 VaListDecl->addDecl(Field);
7486 VaListDecl->completeDefinition();
7487 Context->VaListTagDecl = VaListDecl;
7489 // typedef struct __va_list __builtin_va_list;
7490 QualType T = Context->getRecordType(VaListDecl);
7491 return Context->buildImplicitTypedef(T, "__builtin_va_list");
7494 static TypedefDecl *
7495 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
7496 // struct __va_list_tag {
7497 RecordDecl *VaListTagDecl;
7498 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7499 VaListTagDecl->startDefinition();
7501 const size_t NumFields = 4;
7502 QualType FieldTypes[NumFields];
7503 const char *FieldNames[NumFields];
7506 FieldTypes[0] = Context->LongTy;
7507 FieldNames[0] = "__gpr";
7510 FieldTypes[1] = Context->LongTy;
7511 FieldNames[1] = "__fpr";
7513 // void *__overflow_arg_area;
7514 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7515 FieldNames[2] = "__overflow_arg_area";
7517 // void *__reg_save_area;
7518 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7519 FieldNames[3] = "__reg_save_area";
7522 for (unsigned i = 0; i < NumFields; ++i) {
7523 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7527 &Context->Idents.get(FieldNames[i]),
7528 FieldTypes[i], /*TInfo=*/nullptr,
7529 /*BitWidth=*/nullptr,
7532 Field->setAccess(AS_public);
7533 VaListTagDecl->addDecl(Field);
7535 VaListTagDecl->completeDefinition();
7536 Context->VaListTagDecl = VaListTagDecl;
7537 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7541 // typedef __va_list_tag __builtin_va_list[1];
7542 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7543 QualType VaListTagArrayType =
7544 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
7546 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7549 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7550 TargetInfo::BuiltinVaListKind Kind) {
7552 case TargetInfo::CharPtrBuiltinVaList:
7553 return CreateCharPtrBuiltinVaListDecl(Context);
7554 case TargetInfo::VoidPtrBuiltinVaList:
7555 return CreateVoidPtrBuiltinVaListDecl(Context);
7556 case TargetInfo::AArch64ABIBuiltinVaList:
7557 return CreateAArch64ABIBuiltinVaListDecl(Context);
7558 case TargetInfo::PowerABIBuiltinVaList:
7559 return CreatePowerABIBuiltinVaListDecl(Context);
7560 case TargetInfo::X86_64ABIBuiltinVaList:
7561 return CreateX86_64ABIBuiltinVaListDecl(Context);
7562 case TargetInfo::PNaClABIBuiltinVaList:
7563 return CreatePNaClABIBuiltinVaListDecl(Context);
7564 case TargetInfo::AAPCSABIBuiltinVaList:
7565 return CreateAAPCSABIBuiltinVaListDecl(Context);
7566 case TargetInfo::SystemZBuiltinVaList:
7567 return CreateSystemZBuiltinVaListDecl(Context);
7570 llvm_unreachable("Unhandled __builtin_va_list type kind");
7573 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
7574 if (!BuiltinVaListDecl) {
7575 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
7576 assert(BuiltinVaListDecl->isImplicit());
7579 return BuiltinVaListDecl;
7582 Decl *ASTContext::getVaListTagDecl() const {
7583 // Force the creation of VaListTagDecl by building the __builtin_va_list
7586 (void)getBuiltinVaListDecl();
7588 return VaListTagDecl;
7591 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7592 if (!BuiltinMSVaListDecl)
7593 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7595 return BuiltinMSVaListDecl;
7598 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7599 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7602 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
7603 assert(ObjCConstantStringType.isNull() &&
7604 "'NSConstantString' type already set!");
7606 ObjCConstantStringType = getObjCInterfaceType(Decl);
7609 /// Retrieve the template name that corresponds to a non-empty
7612 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7613 UnresolvedSetIterator End) const {
7614 unsigned size = End - Begin;
7615 assert(size > 1 && "set is not overloaded!");
7617 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7618 size * sizeof(FunctionTemplateDecl*));
7619 auto *OT = new (memory) OverloadedTemplateStorage(size);
7621 NamedDecl **Storage = OT->getStorage();
7622 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
7624 assert(isa<FunctionTemplateDecl>(D) ||
7625 isa<UnresolvedUsingValueDecl>(D) ||
7626 (isa<UsingShadowDecl>(D) &&
7627 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7631 return TemplateName(OT);
7634 /// Retrieve a template name representing an unqualified-id that has been
7635 /// assumed to name a template for ADL purposes.
7636 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
7637 auto *OT = new (*this) AssumedTemplateStorage(Name);
7638 return TemplateName(OT);
7641 /// Retrieve the template name that represents a qualified
7642 /// template name such as \c std::vector.
7644 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7645 bool TemplateKeyword,
7646 TemplateDecl *Template) const {
7647 assert(NNS && "Missing nested-name-specifier in qualified template name");
7649 // FIXME: Canonicalization?
7650 llvm::FoldingSetNodeID ID;
7651 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7653 void *InsertPos = nullptr;
7654 QualifiedTemplateName *QTN =
7655 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7657 QTN = new (*this, alignof(QualifiedTemplateName))
7658 QualifiedTemplateName(NNS, TemplateKeyword, Template);
7659 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7662 return TemplateName(QTN);
7665 /// Retrieve the template name that represents a dependent
7666 /// template name such as \c MetaFun::template apply.
7668 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7669 const IdentifierInfo *Name) const {
7670 assert((!NNS || NNS->isDependent()) &&
7671 "Nested name specifier must be dependent");
7673 llvm::FoldingSetNodeID ID;
7674 DependentTemplateName::Profile(ID, NNS, Name);
7676 void *InsertPos = nullptr;
7677 DependentTemplateName *QTN =
7678 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7681 return TemplateName(QTN);
7683 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7684 if (CanonNNS == NNS) {
7685 QTN = new (*this, alignof(DependentTemplateName))
7686 DependentTemplateName(NNS, Name);
7688 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
7689 QTN = new (*this, alignof(DependentTemplateName))
7690 DependentTemplateName(NNS, Name, Canon);
7691 DependentTemplateName *CheckQTN =
7692 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7693 assert(!CheckQTN && "Dependent type name canonicalization broken");
7697 DependentTemplateNames.InsertNode(QTN, InsertPos);
7698 return TemplateName(QTN);
7701 /// Retrieve the template name that represents a dependent
7702 /// template name such as \c MetaFun::template operator+.
7704 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7705 OverloadedOperatorKind Operator) const {
7706 assert((!NNS || NNS->isDependent()) &&
7707 "Nested name specifier must be dependent");
7709 llvm::FoldingSetNodeID ID;
7710 DependentTemplateName::Profile(ID, NNS, Operator);
7712 void *InsertPos = nullptr;
7713 DependentTemplateName *QTN
7714 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7717 return TemplateName(QTN);
7719 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7720 if (CanonNNS == NNS) {
7721 QTN = new (*this, alignof(DependentTemplateName))
7722 DependentTemplateName(NNS, Operator);
7724 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
7725 QTN = new (*this, alignof(DependentTemplateName))
7726 DependentTemplateName(NNS, Operator, Canon);
7728 DependentTemplateName *CheckQTN
7729 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7730 assert(!CheckQTN && "Dependent template name canonicalization broken");
7734 DependentTemplateNames.InsertNode(QTN, InsertPos);
7735 return TemplateName(QTN);
7739 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7740 TemplateName replacement) const {
7741 llvm::FoldingSetNodeID ID;
7742 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
7744 void *insertPos = nullptr;
7745 SubstTemplateTemplateParmStorage *subst
7746 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7749 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7750 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7753 return TemplateName(subst);
7757 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7758 const TemplateArgument &ArgPack) const {
7759 auto &Self = const_cast<ASTContext &>(*this);
7760 llvm::FoldingSetNodeID ID;
7761 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
7763 void *InsertPos = nullptr;
7764 SubstTemplateTemplateParmPackStorage *Subst
7765 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7768 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
7769 ArgPack.pack_size(),
7770 ArgPack.pack_begin());
7771 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7774 return TemplateName(Subst);
7777 /// getFromTargetType - Given one of the integer types provided by
7778 /// TargetInfo, produce the corresponding type. The unsigned @p Type
7779 /// is actually a value of type @c TargetInfo::IntType.
7780 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
7782 case TargetInfo::NoInt: return {};
7783 case TargetInfo::SignedChar: return SignedCharTy;
7784 case TargetInfo::UnsignedChar: return UnsignedCharTy;
7785 case TargetInfo::SignedShort: return ShortTy;
7786 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7787 case TargetInfo::SignedInt: return IntTy;
7788 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7789 case TargetInfo::SignedLong: return LongTy;
7790 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7791 case TargetInfo::SignedLongLong: return LongLongTy;
7792 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7795 llvm_unreachable("Unhandled TargetInfo::IntType value");
7798 //===----------------------------------------------------------------------===//
7800 //===----------------------------------------------------------------------===//
7802 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7803 /// garbage collection attribute.
7805 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
7806 if (getLangOpts().getGC() == LangOptions::NonGC)
7807 return Qualifiers::GCNone;
7809 assert(getLangOpts().ObjC);
7810 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7812 // Default behaviour under objective-C's gc is for ObjC pointers
7813 // (or pointers to them) be treated as though they were declared
7815 if (GCAttrs == Qualifiers::GCNone) {
7816 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7817 return Qualifiers::Strong;
7818 else if (Ty->isPointerType())
7819 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7821 // It's not valid to set GC attributes on anything that isn't a
7824 QualType CT = Ty->getCanonicalTypeInternal();
7825 while (const auto *AT = dyn_cast<ArrayType>(CT))
7826 CT = AT->getElementType();
7827 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7833 //===----------------------------------------------------------------------===//
7834 // Type Compatibility Testing
7835 //===----------------------------------------------------------------------===//
7837 /// areCompatVectorTypes - Return true if the two specified vector types are
7839 static bool areCompatVectorTypes(const VectorType *LHS,
7840 const VectorType *RHS) {
7841 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
7842 return LHS->getElementType() == RHS->getElementType() &&
7843 LHS->getNumElements() == RHS->getNumElements();
7846 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7847 QualType SecondVec) {
7848 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7849 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7851 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7854 // Treat Neon vector types and most AltiVec vector types as if they are the
7855 // equivalent GCC vector types.
7856 const auto *First = FirstVec->getAs<VectorType>();
7857 const auto *Second = SecondVec->getAs<VectorType>();
7858 if (First->getNumElements() == Second->getNumElements() &&
7859 hasSameType(First->getElementType(), Second->getElementType()) &&
7860 First->getVectorKind() != VectorType::AltiVecPixel &&
7861 First->getVectorKind() != VectorType::AltiVecBool &&
7862 Second->getVectorKind() != VectorType::AltiVecPixel &&
7863 Second->getVectorKind() != VectorType::AltiVecBool)
7869 //===----------------------------------------------------------------------===//
7870 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7871 //===----------------------------------------------------------------------===//
7873 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7874 /// inheritance hierarchy of 'rProto'.
7876 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7877 ObjCProtocolDecl *rProto) const {
7878 if (declaresSameEntity(lProto, rProto))
7880 for (auto *PI : rProto->protocols())
7881 if (ProtocolCompatibleWithProtocol(lProto, PI))
7886 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7887 /// Class<pr1, ...>.
7888 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7890 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7891 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7892 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7894 for (auto *lhsProto : lhsQID->quals()) {
7896 for (auto *rhsProto : rhsOPT->quals()) {
7897 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7908 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7909 /// ObjCQualifiedIDType.
7910 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7912 // Allow id<P..> and an 'id' or void* type in all cases.
7913 if (lhs->isVoidPointerType() ||
7914 lhs->isObjCIdType() || lhs->isObjCClassType())
7916 else if (rhs->isVoidPointerType() ||
7917 rhs->isObjCIdType() || rhs->isObjCClassType())
7920 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
7921 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7923 if (!rhsOPT) return false;
7925 if (rhsOPT->qual_empty()) {
7926 // If the RHS is a unqualified interface pointer "NSString*",
7927 // make sure we check the class hierarchy.
7928 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7929 for (auto *I : lhsQID->quals()) {
7930 // when comparing an id<P> on lhs with a static type on rhs,
7931 // see if static class implements all of id's protocols, directly or
7932 // through its super class and categories.
7933 if (!rhsID->ClassImplementsProtocol(I, true))
7937 // If there are no qualifiers and no interface, we have an 'id'.
7940 // Both the right and left sides have qualifiers.
7941 for (auto *lhsProto : lhsQID->quals()) {
7944 // when comparing an id<P> on lhs with a static type on rhs,
7945 // see if static class implements all of id's protocols, directly or
7946 // through its super class and categories.
7947 for (auto *rhsProto : rhsOPT->quals()) {
7948 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7949 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7954 // If the RHS is a qualified interface pointer "NSString<P>*",
7955 // make sure we check the class hierarchy.
7956 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7957 for (auto *I : lhsQID->quals()) {
7958 // when comparing an id<P> on lhs with a static type on rhs,
7959 // see if static class implements all of id's protocols, directly or
7960 // through its super class and categories.
7961 if (rhsID->ClassImplementsProtocol(I, true)) {
7974 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7975 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7977 if (const ObjCObjectPointerType *lhsOPT =
7978 lhs->getAsObjCInterfacePointerType()) {
7979 // If both the right and left sides have qualifiers.
7980 for (auto *lhsProto : lhsOPT->quals()) {
7983 // when comparing an id<P> on rhs with a static type on lhs,
7984 // see if static class implements all of id's protocols, directly or
7985 // through its super class and categories.
7986 // First, lhs protocols in the qualifier list must be found, direct
7987 // or indirect in rhs's qualifier list or it is a mismatch.
7988 for (auto *rhsProto : rhsQID->quals()) {
7989 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7990 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7999 // Static class's protocols, or its super class or category protocols
8000 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8001 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
8002 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8003 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8004 // This is rather dubious but matches gcc's behavior. If lhs has
8005 // no type qualifier and its class has no static protocol(s)
8006 // assume that it is mismatch.
8007 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
8009 for (auto *lhsProto : LHSInheritedProtocols) {
8011 for (auto *rhsProto : rhsQID->quals()) {
8012 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8013 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8027 /// canAssignObjCInterfaces - Return true if the two interface types are
8028 /// compatible for assignment from RHS to LHS. This handles validation of any
8029 /// protocol qualifiers on the LHS or RHS.
8030 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8031 const ObjCObjectPointerType *RHSOPT) {
8032 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8033 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8035 // If either type represents the built-in 'id' or 'Class' types, return true.
8036 if (LHS->isObjCUnqualifiedIdOrClass() ||
8037 RHS->isObjCUnqualifiedIdOrClass())
8040 // Function object that propagates a successful result or handles
8042 auto finish = [&](bool succeeded) -> bool {
8046 if (!RHS->isKindOfType())
8049 // Strip off __kindof and protocol qualifiers, then check whether
8050 // we can assign the other way.
8051 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8052 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8055 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8056 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8061 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8062 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
8063 QualType(RHSOPT,0)));
8066 // If we have 2 user-defined types, fall into that path.
8067 if (LHS->getInterface() && RHS->getInterface()) {
8068 return finish(canAssignObjCInterfaces(LHS, RHS));
8074 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
8075 /// for providing type-safety for objective-c pointers used to pass/return
8076 /// arguments in block literals. When passed as arguments, passing 'A*' where
8077 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8078 /// not OK. For the return type, the opposite is not OK.
8079 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8080 const ObjCObjectPointerType *LHSOPT,
8081 const ObjCObjectPointerType *RHSOPT,
8082 bool BlockReturnType) {
8084 // Function object that propagates a successful result or handles
8086 auto finish = [&](bool succeeded) -> bool {
8090 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8091 if (!Expected->isKindOfType())
8094 // Strip off __kindof and protocol qualifiers, then check whether
8095 // we can assign the other way.
8096 return canAssignObjCInterfacesInBlockPointer(
8097 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8098 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8102 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
8105 if (LHSOPT->isObjCBuiltinType()) {
8106 return finish(RHSOPT->isObjCBuiltinType() ||
8107 RHSOPT->isObjCQualifiedIdType());
8110 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
8111 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8115 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8116 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8117 if (LHS && RHS) { // We have 2 user-defined types.
8119 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
8120 return finish(BlockReturnType);
8121 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
8122 return finish(!BlockReturnType);
8130 /// Comparison routine for Objective-C protocols to be used with
8131 /// llvm::array_pod_sort.
8132 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8133 ObjCProtocolDecl * const *rhs) {
8134 return (*lhs)->getName().compare((*rhs)->getName());
8137 /// getIntersectionOfProtocols - This routine finds the intersection of set
8138 /// of protocols inherited from two distinct objective-c pointer objects with
8139 /// the given common base.
8140 /// It is used to build composite qualifier list of the composite type of
8141 /// the conditional expression involving two objective-c pointer objects.
8143 void getIntersectionOfProtocols(ASTContext &Context,
8144 const ObjCInterfaceDecl *CommonBase,
8145 const ObjCObjectPointerType *LHSOPT,
8146 const ObjCObjectPointerType *RHSOPT,
8147 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
8149 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8150 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8151 assert(LHS->getInterface() && "LHS must have an interface base");
8152 assert(RHS->getInterface() && "RHS must have an interface base");
8154 // Add all of the protocols for the LHS.
8155 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8157 // Start with the protocol qualifiers.
8158 for (auto proto : LHS->quals()) {
8159 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
8162 // Also add the protocols associated with the LHS interface.
8163 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8165 // Add all of the protocols for the RHS.
8166 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8168 // Start with the protocol qualifiers.
8169 for (auto proto : RHS->quals()) {
8170 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
8173 // Also add the protocols associated with the RHS interface.
8174 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8176 // Compute the intersection of the collected protocol sets.
8177 for (auto proto : LHSProtocolSet) {
8178 if (RHSProtocolSet.count(proto))
8179 IntersectionSet.push_back(proto);
8182 // Compute the set of protocols that is implied by either the common type or
8183 // the protocols within the intersection.
8184 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8185 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8187 // Remove any implied protocols from the list of inherited protocols.
8188 if (!ImpliedProtocols.empty()) {
8189 IntersectionSet.erase(
8190 std::remove_if(IntersectionSet.begin(),
8191 IntersectionSet.end(),
8192 [&](ObjCProtocolDecl *proto) -> bool {
8193 return ImpliedProtocols.count(proto) > 0;
8195 IntersectionSet.end());
8198 // Sort the remaining protocols by name.
8199 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8200 compareObjCProtocolsByName);
8203 /// Determine whether the first type is a subtype of the second.
8204 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8206 // Common case: two object pointers.
8207 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8208 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
8209 if (lhsOPT && rhsOPT)
8210 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8212 // Two block pointers.
8213 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8214 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
8215 if (lhsBlock && rhsBlock)
8216 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8218 // If either is an unqualified 'id' and the other is a block, it's
8220 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8221 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8227 // Check that the given Objective-C type argument lists are equivalent.
8228 static bool sameObjCTypeArgs(ASTContext &ctx,
8229 const ObjCInterfaceDecl *iface,
8230 ArrayRef<QualType> lhsArgs,
8231 ArrayRef<QualType> rhsArgs,
8233 if (lhsArgs.size() != rhsArgs.size())
8236 ObjCTypeParamList *typeParams = iface->getTypeParamList();
8237 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
8238 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8241 switch (typeParams->begin()[i]->getVariance()) {
8242 case ObjCTypeParamVariance::Invariant:
8244 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8245 rhsArgs[i].stripObjCKindOfType(ctx))) {
8250 case ObjCTypeParamVariance::Covariant:
8251 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8255 case ObjCTypeParamVariance::Contravariant:
8256 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8265 QualType ASTContext::areCommonBaseCompatible(
8266 const ObjCObjectPointerType *Lptr,
8267 const ObjCObjectPointerType *Rptr) {
8268 const ObjCObjectType *LHS = Lptr->getObjectType();
8269 const ObjCObjectType *RHS = Rptr->getObjectType();
8270 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8271 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
8273 if (!LDecl || !RDecl)
8276 // When either LHS or RHS is a kindof type, we should return a kindof type.
8277 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8279 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8281 // Follow the left-hand side up the class hierarchy until we either hit a
8282 // root or find the RHS. Record the ancestors in case we don't find it.
8283 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8286 // Record this ancestor. We'll need this if the common type isn't in the
8287 // path from the LHS to the root.
8288 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
8290 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8291 // Get the type arguments.
8292 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8293 bool anyChanges = false;
8294 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8295 // Both have type arguments, compare them.
8296 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8297 LHS->getTypeArgs(), RHS->getTypeArgs(),
8298 /*stripKindOf=*/true))
8300 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8301 // If only one has type arguments, the result will not have type
8307 // Compute the intersection of protocols.
8308 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8309 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8311 if (!Protocols.empty())
8314 // If anything in the LHS will have changed, build a new result type.
8315 // If we need to return a kindof type but LHS is not a kindof type, we
8316 // build a new result type.
8317 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
8318 QualType Result = getObjCInterfaceType(LHS->getInterface());
8319 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
8320 anyKindOf || LHS->isKindOfType());
8321 return getObjCObjectPointerType(Result);
8324 return getObjCObjectPointerType(QualType(LHS, 0));
8327 // Find the superclass.
8328 QualType LHSSuperType = LHS->getSuperClassType();
8329 if (LHSSuperType.isNull())
8332 LHS = LHSSuperType->castAs<ObjCObjectType>();
8335 // We didn't find anything by following the LHS to its root; now check
8336 // the RHS against the cached set of ancestors.
8338 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8339 if (KnownLHS != LHSAncestors.end()) {
8340 LHS = KnownLHS->second;
8342 // Get the type arguments.
8343 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8344 bool anyChanges = false;
8345 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8346 // Both have type arguments, compare them.
8347 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8348 LHS->getTypeArgs(), RHS->getTypeArgs(),
8349 /*stripKindOf=*/true))
8351 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8352 // If only one has type arguments, the result will not have type
8358 // Compute the intersection of protocols.
8359 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8360 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8362 if (!Protocols.empty())
8365 // If we need to return a kindof type but RHS is not a kindof type, we
8366 // build a new result type.
8367 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
8368 QualType Result = getObjCInterfaceType(RHS->getInterface());
8369 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
8370 anyKindOf || RHS->isKindOfType());
8371 return getObjCObjectPointerType(Result);
8374 return getObjCObjectPointerType(QualType(RHS, 0));
8377 // Find the superclass of the RHS.
8378 QualType RHSSuperType = RHS->getSuperClassType();
8379 if (RHSSuperType.isNull())
8382 RHS = RHSSuperType->castAs<ObjCObjectType>();
8388 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8389 const ObjCObjectType *RHS) {
8390 assert(LHS->getInterface() && "LHS is not an interface type");
8391 assert(RHS->getInterface() && "RHS is not an interface type");
8393 // Verify that the base decls are compatible: the RHS must be a subclass of
8395 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8396 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8400 // If the LHS has protocol qualifiers, determine whether all of them are
8401 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8403 if (LHS->getNumProtocols() > 0) {
8404 // OK if conversion of LHS to SuperClass results in narrowing of types
8405 // ; i.e., SuperClass may implement at least one of the protocols
8406 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8407 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8408 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8409 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8410 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8412 for (auto *RHSPI : RHS->quals())
8413 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
8414 // If there is no protocols associated with RHS, it is not a match.
8415 if (SuperClassInheritedProtocols.empty())
8418 for (const auto *LHSProto : LHS->quals()) {
8419 bool SuperImplementsProtocol = false;
8420 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8421 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8422 SuperImplementsProtocol = true;
8425 if (!SuperImplementsProtocol)
8430 // If the LHS is specialized, we may need to check type arguments.
8431 if (LHS->isSpecialized()) {
8432 // Follow the superclass chain until we've matched the LHS class in the
8433 // hierarchy. This substitutes type arguments through.
8434 const ObjCObjectType *RHSSuper = RHS;
8435 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8436 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8438 // If the RHS is specializd, compare type arguments.
8439 if (RHSSuper->isSpecialized() &&
8440 !sameObjCTypeArgs(*this, LHS->getInterface(),
8441 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
8442 /*stripKindOf=*/true)) {
8450 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8451 // get the "pointed to" types
8452 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8453 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
8455 if (!LHSOPT || !RHSOPT)
8458 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8459 canAssignObjCInterfaces(RHSOPT, LHSOPT);
8462 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8463 return canAssignObjCInterfaces(
8464 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8465 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8468 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
8469 /// both shall have the identically qualified version of a compatible type.
8470 /// C99 6.2.7p1: Two types have compatible types if their types are the
8471 /// same. See 6.7.[2,3,5] for additional rules.
8472 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8473 bool CompareUnqualified) {
8474 if (getLangOpts().CPlusPlus)
8475 return hasSameType(LHS, RHS);
8477 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
8480 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
8481 return typesAreCompatible(LHS, RHS);
8484 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8485 return !mergeTypes(LHS, RHS, true).isNull();
8488 /// mergeTransparentUnionType - if T is a transparent union type and a member
8489 /// of T is compatible with SubType, return the merged type, else return
8491 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8492 bool OfBlockPointer,
8494 if (const RecordType *UT = T->getAsUnionType()) {
8495 RecordDecl *UD = UT->getDecl();
8496 if (UD->hasAttr<TransparentUnionAttr>()) {
8497 for (const auto *I : UD->fields()) {
8498 QualType ET = I->getType().getUnqualifiedType();
8499 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8509 /// mergeFunctionParameterTypes - merge two types which appear as function
8511 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8512 bool OfBlockPointer,
8514 // GNU extension: two types are compatible if they appear as a function
8515 // argument, one of the types is a transparent union type and the other
8516 // type is compatible with a union member
8517 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8519 if (!lmerge.isNull())
8522 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8524 if (!rmerge.isNull())
8527 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8530 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
8531 bool OfBlockPointer,
8533 const auto *lbase = lhs->getAs<FunctionType>();
8534 const auto *rbase = rhs->getAs<FunctionType>();
8535 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8536 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
8537 bool allLTypes = true;
8538 bool allRTypes = true;
8540 // Check return type
8542 if (OfBlockPointer) {
8543 QualType RHS = rbase->getReturnType();
8544 QualType LHS = lbase->getReturnType();
8545 bool UnqualifiedResult = Unqualified;
8546 if (!UnqualifiedResult)
8547 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
8548 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
8551 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
8553 if (retType.isNull())
8557 retType = retType.getUnqualifiedType();
8559 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8560 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
8562 LRetType = LRetType.getUnqualifiedType();
8563 RRetType = RRetType.getUnqualifiedType();
8566 if (getCanonicalType(retType) != LRetType)
8568 if (getCanonicalType(retType) != RRetType)
8571 // FIXME: double check this
8572 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8573 // rbase->getRegParmAttr() != 0 &&
8574 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
8575 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8576 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
8578 // Compatible functions must have compatible calling conventions
8579 if (lbaseInfo.getCC() != rbaseInfo.getCC())
8582 // Regparm is part of the calling convention.
8583 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
8585 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
8588 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
8590 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
8592 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
8595 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8596 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
8598 if (lbaseInfo.getNoReturn() != NoReturn)
8600 if (rbaseInfo.getNoReturn() != NoReturn)
8603 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
8605 if (lproto && rproto) { // two C99 style function prototypes
8606 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8607 "C++ shouldn't be here");
8608 // Compatible functions must have the same number of parameters
8609 if (lproto->getNumParams() != rproto->getNumParams())
8612 // Variadic and non-variadic functions aren't compatible
8613 if (lproto->isVariadic() != rproto->isVariadic())
8616 if (lproto->getMethodQuals() != rproto->getMethodQuals())
8619 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8620 bool canUseLeft, canUseRight;
8621 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8630 // Check parameter type compatibility
8631 SmallVector<QualType, 10> types;
8632 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8633 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8634 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8635 QualType paramType = mergeFunctionParameterTypes(
8636 lParamType, rParamType, OfBlockPointer, Unqualified);
8637 if (paramType.isNull())
8641 paramType = paramType.getUnqualifiedType();
8643 types.push_back(paramType);
8645 lParamType = lParamType.getUnqualifiedType();
8646 rParamType = rParamType.getUnqualifiedType();
8649 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
8651 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
8655 if (allLTypes) return lhs;
8656 if (allRTypes) return rhs;
8658 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8659 EPI.ExtInfo = einfo;
8660 EPI.ExtParameterInfos =
8661 newParamInfos.empty() ? nullptr : newParamInfos.data();
8662 return getFunctionType(retType, types, EPI);
8665 if (lproto) allRTypes = false;
8666 if (rproto) allLTypes = false;
8668 const FunctionProtoType *proto = lproto ? lproto : rproto;
8670 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
8671 if (proto->isVariadic())
8673 // Check that the types are compatible with the types that
8674 // would result from default argument promotions (C99 6.7.5.3p15).
8675 // The only types actually affected are promotable integer
8676 // types and floats, which would be passed as a different
8677 // type depending on whether the prototype is visible.
8678 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8679 QualType paramTy = proto->getParamType(i);
8681 // Look at the converted type of enum types, since that is the type used
8682 // to pass enum values.
8683 if (const auto *Enum = paramTy->getAs<EnumType>()) {
8684 paramTy = Enum->getDecl()->getIntegerType();
8685 if (paramTy.isNull())
8689 if (paramTy->isPromotableIntegerType() ||
8690 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
8694 if (allLTypes) return lhs;
8695 if (allRTypes) return rhs;
8697 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8698 EPI.ExtInfo = einfo;
8699 return getFunctionType(retType, proto->getParamTypes(), EPI);
8702 if (allLTypes) return lhs;
8703 if (allRTypes) return rhs;
8704 return getFunctionNoProtoType(retType, einfo);
8707 /// Given that we have an enum type and a non-enum type, try to merge them.
8708 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8709 QualType other, bool isBlockReturnType) {
8710 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8711 // a signed integer type, or an unsigned integer type.
8712 // Compatibility is based on the underlying type, not the promotion
8714 QualType underlyingType = ET->getDecl()->getIntegerType();
8715 if (underlyingType.isNull())
8717 if (Context.hasSameType(underlyingType, other))
8720 // In block return types, we're more permissive and accept any
8721 // integral type of the same size.
8722 if (isBlockReturnType && other->isIntegerType() &&
8723 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8729 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
8730 bool OfBlockPointer,
8731 bool Unqualified, bool BlockReturnType) {
8732 // C++ [expr]: If an expression initially has the type "reference to T", the
8733 // type is adjusted to "T" prior to any further analysis, the expression
8734 // designates the object or function denoted by the reference, and the
8735 // expression is an lvalue unless the reference is an rvalue reference and
8736 // the expression is a function call (possibly inside parentheses).
8737 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8738 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
8741 LHS = LHS.getUnqualifiedType();
8742 RHS = RHS.getUnqualifiedType();
8745 QualType LHSCan = getCanonicalType(LHS),
8746 RHSCan = getCanonicalType(RHS);
8748 // If two types are identical, they are compatible.
8749 if (LHSCan == RHSCan)
8752 // If the qualifiers are different, the types aren't compatible... mostly.
8753 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8754 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8755 if (LQuals != RQuals) {
8756 // If any of these qualifiers are different, we have a type
8758 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8759 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
8760 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8761 LQuals.hasUnaligned() != RQuals.hasUnaligned())
8764 // Exactly one GC qualifier difference is allowed: __strong is
8765 // okay if the other type has no GC qualifier but is an Objective
8766 // C object pointer (i.e. implicitly strong by default). We fix
8767 // this by pretending that the unqualified type was actually
8768 // qualified __strong.
8769 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8770 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8771 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8773 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8776 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8777 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8779 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8780 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8785 // Okay, qualifiers are equal.
8787 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8788 Type::TypeClass RHSClass = RHSCan->getTypeClass();
8790 // We want to consider the two function types to be the same for these
8791 // comparisons, just force one to the other.
8792 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8793 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
8795 // Same as above for arrays
8796 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8797 LHSClass = Type::ConstantArray;
8798 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8799 RHSClass = Type::ConstantArray;
8801 // ObjCInterfaces are just specialized ObjCObjects.
8802 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8803 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8805 // Canonicalize ExtVector -> Vector.
8806 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8807 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
8809 // If the canonical type classes don't match.
8810 if (LHSClass != RHSClass) {
8811 // Note that we only have special rules for turning block enum
8812 // returns into block int returns, not vice-versa.
8813 if (const auto *ETy = LHS->getAs<EnumType>()) {
8814 return mergeEnumWithInteger(*this, ETy, RHS, false);
8816 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
8817 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
8819 // allow block pointer type to match an 'id' type.
8820 if (OfBlockPointer && !BlockReturnType) {
8821 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8823 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8830 // The canonical type classes match.
8832 #define TYPE(Class, Base)
8833 #define ABSTRACT_TYPE(Class, Base)
8834 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
8835 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8836 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
8837 #include "clang/AST/TypeNodes.def"
8838 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
8841 case Type::DeducedTemplateSpecialization:
8842 case Type::LValueReference:
8843 case Type::RValueReference:
8844 case Type::MemberPointer:
8845 llvm_unreachable("C++ should never be in mergeTypes");
8847 case Type::ObjCInterface:
8848 case Type::IncompleteArray:
8849 case Type::VariableArray:
8850 case Type::FunctionProto:
8851 case Type::ExtVector:
8852 llvm_unreachable("Types are eliminated above");
8856 // Merge two pointer types, while trying to preserve typedef info
8857 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8858 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
8860 LHSPointee = LHSPointee.getUnqualifiedType();
8861 RHSPointee = RHSPointee.getUnqualifiedType();
8863 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8865 if (ResultType.isNull())
8867 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8869 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8871 return getPointerType(ResultType);
8873 case Type::BlockPointer:
8875 // Merge two block pointer types, while trying to preserve typedef info
8876 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8877 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
8879 LHSPointee = LHSPointee.getUnqualifiedType();
8880 RHSPointee = RHSPointee.getUnqualifiedType();
8882 if (getLangOpts().OpenCL) {
8883 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8884 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8885 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8886 // 6.12.5) thus the following check is asymmetric.
8887 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
8889 LHSPteeQual.removeAddressSpace();
8890 RHSPteeQual.removeAddressSpace();
8892 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8894 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8896 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8898 if (ResultType.isNull())
8900 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8902 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8904 return getBlockPointerType(ResultType);
8908 // Merge two pointer types, while trying to preserve typedef info
8909 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8910 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8912 LHSValue = LHSValue.getUnqualifiedType();
8913 RHSValue = RHSValue.getUnqualifiedType();
8915 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8917 if (ResultType.isNull())
8919 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8921 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8923 return getAtomicType(ResultType);
8925 case Type::ConstantArray:
8927 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8928 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8929 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8932 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8933 QualType RHSElem = getAsArrayType(RHS)->getElementType();
8935 LHSElem = LHSElem.getUnqualifiedType();
8936 RHSElem = RHSElem.getUnqualifiedType();
8939 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
8940 if (ResultType.isNull())
8943 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8944 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8946 // If either side is a variable array, and both are complete, check whether
8947 // the current dimension is definite.
8949 auto SizeFetch = [this](const VariableArrayType* VAT,
8950 const ConstantArrayType* CAT)
8951 -> std::pair<bool,llvm::APInt> {
8953 llvm::APSInt TheInt;
8954 Expr *E = VAT->getSizeExpr();
8955 if (E && E->isIntegerConstantExpr(TheInt, *this))
8956 return std::make_pair(true, TheInt);
8958 return std::make_pair(false, TheInt);
8960 return std::make_pair(true, CAT->getSize());
8962 return std::make_pair(false, llvm::APInt());
8966 bool HaveLSize, HaveRSize;
8967 llvm::APInt LSize, RSize;
8968 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
8969 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
8970 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
8971 return {}; // Definite, but unequal, array dimension
8974 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8976 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8978 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8979 ArrayType::ArraySizeModifier(), 0);
8980 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8981 ArrayType::ArraySizeModifier(), 0);
8982 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8984 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8987 // FIXME: This isn't correct! But tricky to implement because
8988 // the array's size has to be the size of LHS, but the type
8989 // has to be different.
8993 // FIXME: This isn't correct! But tricky to implement because
8994 // the array's size has to be the size of RHS, but the type
8995 // has to be different.
8998 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8999 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
9000 return getIncompleteArrayType(ResultType,
9001 ArrayType::ArraySizeModifier(), 0);
9003 case Type::FunctionNoProto:
9004 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
9009 // Only exactly equal builtin types are compatible, which is tested above.
9012 // Distinct complex types are incompatible.
9015 // FIXME: The merged type should be an ExtVector!
9016 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
9017 RHSCan->getAs<VectorType>()))
9020 case Type::ObjCObject: {
9021 // Check if the types are assignment compatible.
9022 // FIXME: This should be type compatibility, e.g. whether
9023 // "LHS x; RHS x;" at global scope is legal.
9024 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
9025 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
9026 if (canAssignObjCInterfaces(LHSIface, RHSIface))
9031 case Type::ObjCObjectPointer:
9032 if (OfBlockPointer) {
9033 if (canAssignObjCInterfacesInBlockPointer(
9034 LHS->getAs<ObjCObjectPointerType>(),
9035 RHS->getAs<ObjCObjectPointerType>(),
9040 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
9041 RHS->getAs<ObjCObjectPointerType>()))
9046 assert(LHS != RHS &&
9047 "Equivalent pipe types should have already been handled!");
9051 llvm_unreachable("Invalid Type::Class!");
9054 bool ASTContext::mergeExtParameterInfo(
9055 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9056 bool &CanUseFirst, bool &CanUseSecond,
9057 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9058 assert(NewParamInfos.empty() && "param info list not empty");
9059 CanUseFirst = CanUseSecond = true;
9060 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9061 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9063 // Fast path: if the first type doesn't have ext parameter infos,
9064 // we match if and only if the second type also doesn't have them.
9065 if (!FirstHasInfo && !SecondHasInfo)
9068 bool NeedParamInfo = false;
9069 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9070 : SecondFnType->getExtParameterInfos().size();
9072 for (size_t I = 0; I < E; ++I) {
9073 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9075 FirstParam = FirstFnType->getExtParameterInfo(I);
9077 SecondParam = SecondFnType->getExtParameterInfo(I);
9079 // Cannot merge unless everything except the noescape flag matches.
9080 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
9083 bool FirstNoEscape = FirstParam.isNoEscape();
9084 bool SecondNoEscape = SecondParam.isNoEscape();
9085 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9086 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9087 if (NewParamInfos.back().getOpaqueValue())
9088 NeedParamInfo = true;
9089 if (FirstNoEscape != IsNoEscape)
9090 CanUseFirst = false;
9091 if (SecondNoEscape != IsNoEscape)
9092 CanUseSecond = false;
9096 NewParamInfos.clear();
9101 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9102 ObjCLayouts[CD] = nullptr;
9105 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9106 /// 'RHS' attributes and returns the merged version; including for function
9108 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9109 QualType LHSCan = getCanonicalType(LHS),
9110 RHSCan = getCanonicalType(RHS);
9111 // If two types are identical, they are compatible.
9112 if (LHSCan == RHSCan)
9114 if (RHSCan->isFunctionType()) {
9115 if (!LHSCan->isFunctionType())
9117 QualType OldReturnType =
9118 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
9119 QualType NewReturnType =
9120 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
9121 QualType ResReturnType =
9122 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9123 if (ResReturnType.isNull())
9125 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9126 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9127 // In either case, use OldReturnType to build the new function type.
9128 const auto *F = LHS->getAs<FunctionType>();
9129 if (const auto *FPT = cast<FunctionProtoType>(F)) {
9130 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9131 EPI.ExtInfo = getFunctionExtInfo(LHS);
9132 QualType ResultType =
9133 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
9140 // If the qualifiers are different, the types can still be merged.
9141 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9142 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9143 if (LQuals != RQuals) {
9144 // If any of these qualifiers are different, we have a type mismatch.
9145 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9146 LQuals.getAddressSpace() != RQuals.getAddressSpace())
9149 // Exactly one GC qualifier difference is allowed: __strong is
9150 // okay if the other type has no GC qualifier but is an Objective
9151 // C object pointer (i.e. implicitly strong by default). We fix
9152 // this by pretending that the unqualified type was actually
9153 // qualified __strong.
9154 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9155 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9156 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9158 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9161 if (GC_L == Qualifiers::Strong)
9163 if (GC_R == Qualifiers::Strong)
9168 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9169 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9170 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9171 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9172 if (ResQT == LHSBaseQT)
9174 if (ResQT == RHSBaseQT)
9180 //===----------------------------------------------------------------------===//
9181 // Integer Predicates
9182 //===----------------------------------------------------------------------===//
9184 unsigned ASTContext::getIntWidth(QualType T) const {
9185 if (const auto *ET = T->getAs<EnumType>())
9186 T = ET->getDecl()->getIntegerType();
9187 if (T->isBooleanType())
9189 // For builtin types, just use the standard type sizing method
9190 return (unsigned)getTypeSize(T);
9193 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
9194 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9197 // Turn <4 x signed int> -> <4 x unsigned int>
9198 if (const auto *VTy = T->getAs<VectorType>())
9199 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
9200 VTy->getNumElements(), VTy->getVectorKind());
9202 // For enums, we return the unsigned version of the base type.
9203 if (const auto *ETy = T->getAs<EnumType>())
9204 T = ETy->getDecl()->getIntegerType();
9206 const auto *BTy = T->getAs<BuiltinType>();
9207 assert(BTy && "Unexpected signed integer or fixed point type");
9208 switch (BTy->getKind()) {
9209 case BuiltinType::Char_S:
9210 case BuiltinType::SChar:
9211 return UnsignedCharTy;
9212 case BuiltinType::Short:
9213 return UnsignedShortTy;
9214 case BuiltinType::Int:
9215 return UnsignedIntTy;
9216 case BuiltinType::Long:
9217 return UnsignedLongTy;
9218 case BuiltinType::LongLong:
9219 return UnsignedLongLongTy;
9220 case BuiltinType::Int128:
9221 return UnsignedInt128Ty;
9223 case BuiltinType::ShortAccum:
9224 return UnsignedShortAccumTy;
9225 case BuiltinType::Accum:
9226 return UnsignedAccumTy;
9227 case BuiltinType::LongAccum:
9228 return UnsignedLongAccumTy;
9229 case BuiltinType::SatShortAccum:
9230 return SatUnsignedShortAccumTy;
9231 case BuiltinType::SatAccum:
9232 return SatUnsignedAccumTy;
9233 case BuiltinType::SatLongAccum:
9234 return SatUnsignedLongAccumTy;
9235 case BuiltinType::ShortFract:
9236 return UnsignedShortFractTy;
9237 case BuiltinType::Fract:
9238 return UnsignedFractTy;
9239 case BuiltinType::LongFract:
9240 return UnsignedLongFractTy;
9241 case BuiltinType::SatShortFract:
9242 return SatUnsignedShortFractTy;
9243 case BuiltinType::SatFract:
9244 return SatUnsignedFractTy;
9245 case BuiltinType::SatLongFract:
9246 return SatUnsignedLongFractTy;
9248 llvm_unreachable("Unexpected signed integer or fixed point type");
9252 ASTMutationListener::~ASTMutationListener() = default;
9254 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9255 QualType ReturnType) {}
9257 //===----------------------------------------------------------------------===//
9258 // Builtin Type Computation
9259 //===----------------------------------------------------------------------===//
9261 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
9262 /// pointer over the consumed characters. This returns the resultant type. If
9263 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9264 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9265 /// a vector of "i*".
9267 /// RequiresICE is filled in on return to indicate whether the value is required
9268 /// to be an Integer Constant Expression.
9269 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
9270 ASTContext::GetBuiltinTypeError &Error,
9272 bool AllowTypeModifiers) {
9275 bool Signed = false, Unsigned = false;
9276 RequiresICE = false;
9278 // Read the prefixed modifiers first.
9281 bool IsSpecial = false;
9285 default: Done = true; --Str; break;
9290 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9291 assert(!Signed && "Can't use 'S' modifier multiple times!");
9295 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
9296 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
9300 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
9301 assert(HowLong <= 2 && "Can't have LLLL modifier");
9305 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9306 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9307 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
9311 if (Context.getTargetInfo().getLongWidth() == 32)
9315 // This modifier represents int64 type.
9316 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9317 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
9321 switch (Context.getTargetInfo().getInt64Type()) {
9323 llvm_unreachable("Unexpected integer type");
9324 case TargetInfo::SignedLong:
9327 case TargetInfo::SignedLongLong:
9333 // This modifier represents int32 type.
9334 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9335 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9339 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9341 llvm_unreachable("Unexpected integer type");
9342 case TargetInfo::SignedInt:
9345 case TargetInfo::SignedLong:
9348 case TargetInfo::SignedLongLong:
9354 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9355 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
9359 if (Context.getLangOpts().OpenCL)
9369 // Read the base type.
9371 default: llvm_unreachable("Unknown builtin type letter!");
9373 assert(HowLong == 0 && !Signed && !Unsigned &&
9374 "Bad modifiers used with 'v'!");
9375 Type = Context.VoidTy;
9378 assert(HowLong == 0 && !Signed && !Unsigned &&
9379 "Bad modifiers used with 'h'!");
9380 Type = Context.HalfTy;
9383 assert(HowLong == 0 && !Signed && !Unsigned &&
9384 "Bad modifiers used with 'f'!");
9385 Type = Context.FloatTy;
9388 assert(HowLong < 3 && !Signed && !Unsigned &&
9389 "Bad modifiers used with 'd'!");
9391 Type = Context.LongDoubleTy;
9392 else if (HowLong == 2)
9393 Type = Context.Float128Ty;
9395 Type = Context.DoubleTy;
9398 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9400 Type = Context.UnsignedShortTy;
9402 Type = Context.ShortTy;
9406 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9407 else if (HowLong == 2)
9408 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9409 else if (HowLong == 1)
9410 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9412 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9415 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9417 Type = Context.SignedCharTy;
9419 Type = Context.UnsignedCharTy;
9421 Type = Context.CharTy;
9423 case 'b': // boolean
9424 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9425 Type = Context.BoolTy;
9427 case 'z': // size_t.
9428 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9429 Type = Context.getSizeType();
9431 case 'w': // wchar_t.
9432 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9433 Type = Context.getWideCharType();
9436 Type = Context.getCFConstantStringType();
9439 Type = Context.getObjCIdType();
9442 Type = Context.getObjCSelType();
9445 Type = Context.getObjCSuperType();
9448 Type = Context.getBuiltinVaListType();
9449 assert(!Type.isNull() && "builtin va list type not initialized!");
9452 // This is a "reference" to a va_list; however, what exactly
9453 // this means depends on how va_list is defined. There are two
9454 // different kinds of va_list: ones passed by value, and ones
9455 // passed by reference. An example of a by-value va_list is
9456 // x86, where va_list is a char*. An example of by-ref va_list
9457 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9458 // we want this argument to be a char*&; for x86-64, we want
9459 // it to be a __va_list_tag*.
9460 Type = Context.getBuiltinVaListType();
9461 assert(!Type.isNull() && "builtin va list type not initialized!");
9462 if (Type->isArrayType())
9463 Type = Context.getArrayDecayedType(Type);
9465 Type = Context.getLValueReferenceType(Type);
9469 unsigned NumElements = strtoul(Str, &End, 10);
9470 assert(End != Str && "Missing vector size");
9473 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
9474 RequiresICE, false);
9475 assert(!RequiresICE && "Can't require vector ICE");
9477 // TODO: No way to make AltiVec vectors in builtins yet.
9478 Type = Context.getVectorType(ElementType, NumElements,
9479 VectorType::GenericVector);
9485 unsigned NumElements = strtoul(Str, &End, 10);
9486 assert(End != Str && "Missing vector size");
9490 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
9492 Type = Context.getExtVectorType(ElementType, NumElements);
9496 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
9498 assert(!RequiresICE && "Can't require complex ICE");
9499 Type = Context.getComplexType(ElementType);
9503 Type = Context.getPointerDiffType();
9506 Type = Context.getFILEType();
9507 if (Type.isNull()) {
9508 Error = ASTContext::GE_Missing_stdio;
9514 Type = Context.getsigjmp_bufType();
9516 Type = Context.getjmp_bufType();
9518 if (Type.isNull()) {
9519 Error = ASTContext::GE_Missing_setjmp;
9524 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9525 Type = Context.getucontext_tType();
9527 if (Type.isNull()) {
9528 Error = ASTContext::GE_Missing_ucontext;
9533 Type = Context.getProcessIDType();
9537 // If there are modifiers and if we're allowed to parse them, go for it.
9538 Done = !AllowTypeModifiers;
9540 switch (char c = *Str++) {
9541 default: Done = true; --Str; break;
9544 // Both pointers and references can have their pointee types
9545 // qualified with an address space.
9547 unsigned AddrSpace = strtoul(Str, &End, 10);
9549 // Note AddrSpace == 0 is not the same as an unspecified address space.
9550 Type = Context.getAddrSpaceQualType(
9552 Context.getLangASForBuiltinAddressSpace(AddrSpace));
9556 Type = Context.getPointerType(Type);
9558 Type = Context.getLValueReferenceType(Type);
9561 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9563 Type = Type.withConst();
9566 Type = Context.getVolatileType(Type);
9569 Type = Type.withRestrict();
9574 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
9575 "Integer constant 'I' type must be an integer");
9580 /// GetBuiltinType - Return the type for the specified builtin.
9581 QualType ASTContext::GetBuiltinType(unsigned Id,
9582 GetBuiltinTypeError &Error,
9583 unsigned *IntegerConstantArgs) const {
9584 const char *TypeStr = BuiltinInfo.getTypeString(Id);
9585 if (TypeStr[0] == '\0') {
9586 Error = GE_Missing_type;
9590 SmallVector<QualType, 8> ArgTypes;
9592 bool RequiresICE = false;
9594 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9596 if (Error != GE_None)
9599 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
9601 while (TypeStr[0] && TypeStr[0] != '.') {
9602 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
9603 if (Error != GE_None)
9606 // If this argument is required to be an IntegerConstantExpression and the
9607 // caller cares, fill in the bitmask we return.
9608 if (RequiresICE && IntegerConstantArgs)
9609 *IntegerConstantArgs |= 1 << ArgTypes.size();
9611 // Do array -> pointer decay. The builtin should use the decayed type.
9612 if (Ty->isArrayType())
9613 Ty = getArrayDecayedType(Ty);
9615 ArgTypes.push_back(Ty);
9618 if (Id == Builtin::BI__GetExceptionInfo)
9621 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9622 "'.' should only occur at end of builtin type list!");
9624 bool Variadic = (TypeStr[0] == '.');
9626 FunctionType::ExtInfo EI(getDefaultCallingConvention(
9627 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
9628 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9631 // We really shouldn't be making a no-proto type here.
9632 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
9633 return getFunctionNoProtoType(ResType, EI);
9635 FunctionProtoType::ExtProtoInfo EPI;
9637 EPI.Variadic = Variadic;
9638 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9639 EPI.ExceptionSpec.Type =
9640 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
9642 return getFunctionType(ResType, ArgTypes, EPI);
9645 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9646 const FunctionDecl *FD) {
9647 if (!FD->isExternallyVisible())
9648 return GVA_Internal;
9650 // Non-user-provided functions get emitted as weak definitions with every
9651 // use, no matter whether they've been explicitly instantiated etc.
9652 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
9653 if (!MD->isUserProvided())
9654 return GVA_DiscardableODR;
9656 GVALinkage External;
9657 switch (FD->getTemplateSpecializationKind()) {
9658 case TSK_Undeclared:
9659 case TSK_ExplicitSpecialization:
9660 External = GVA_StrongExternal;
9663 case TSK_ExplicitInstantiationDefinition:
9664 return GVA_StrongODR;
9666 // C++11 [temp.explicit]p10:
9667 // [ Note: The intent is that an inline function that is the subject of
9668 // an explicit instantiation declaration will still be implicitly
9669 // instantiated when used so that the body can be considered for
9670 // inlining, but that no out-of-line copy of the inline function would be
9671 // generated in the translation unit. -- end note ]
9672 case TSK_ExplicitInstantiationDeclaration:
9673 return GVA_AvailableExternally;
9675 case TSK_ImplicitInstantiation:
9676 External = GVA_DiscardableODR;
9680 if (!FD->isInlined())
9683 if ((!Context.getLangOpts().CPlusPlus &&
9684 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9685 !FD->hasAttr<DLLExportAttr>()) ||
9686 FD->hasAttr<GNUInlineAttr>()) {
9687 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9689 // GNU or C99 inline semantics. Determine whether this symbol should be
9690 // externally visible.
9691 if (FD->isInlineDefinitionExternallyVisible())
9694 // C99 inline semantics, where the symbol is not externally visible.
9695 return GVA_AvailableExternally;
9698 // Functions specified with extern and inline in -fms-compatibility mode
9699 // forcibly get emitted. While the body of the function cannot be later
9700 // replaced, the function definition cannot be discarded.
9701 if (FD->isMSExternInline())
9702 return GVA_StrongODR;
9704 return GVA_DiscardableODR;
9707 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
9708 const Decl *D, GVALinkage L) {
9709 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9710 // dllexport/dllimport on inline functions.
9711 if (D->hasAttr<DLLImportAttr>()) {
9712 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9713 return GVA_AvailableExternally;
9714 } else if (D->hasAttr<DLLExportAttr>()) {
9715 if (L == GVA_DiscardableODR)
9716 return GVA_StrongODR;
9717 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9718 D->hasAttr<CUDAGlobalAttr>()) {
9719 // Device-side functions with __global__ attribute must always be
9720 // visible externally so they can be launched from host.
9721 if (L == GVA_DiscardableODR || L == GVA_Internal)
9722 return GVA_StrongODR;
9727 /// Adjust the GVALinkage for a declaration based on what an external AST source
9728 /// knows about whether there can be other definitions of this declaration.
9730 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9732 ExternalASTSource *Source = Ctx.getExternalSource();
9736 switch (Source->hasExternalDefinitions(D)) {
9737 case ExternalASTSource::EK_Never:
9738 // Other translation units rely on us to provide the definition.
9739 if (L == GVA_DiscardableODR)
9740 return GVA_StrongODR;
9743 case ExternalASTSource::EK_Always:
9744 return GVA_AvailableExternally;
9746 case ExternalASTSource::EK_ReplyHazy:
9752 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9753 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9754 adjustGVALinkageForAttributes(*this, FD,
9755 basicGVALinkageForFunction(*this, FD)));
9758 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9759 const VarDecl *VD) {
9760 if (!VD->isExternallyVisible())
9761 return GVA_Internal;
9763 if (VD->isStaticLocal()) {
9764 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9765 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9766 LexicalContext = LexicalContext->getLexicalParent();
9768 // ObjC Blocks can create local variables that don't have a FunctionDecl
9770 if (!LexicalContext)
9771 return GVA_DiscardableODR;
9773 // Otherwise, let the static local variable inherit its linkage from the
9774 // nearest enclosing function.
9775 auto StaticLocalLinkage =
9776 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9778 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9779 // be emitted in any object with references to the symbol for the object it
9780 // contains, whether inline or out-of-line."
9781 // Similar behavior is observed with MSVC. An alternative ABI could use
9782 // StrongODR/AvailableExternally to match the function, but none are
9783 // known/supported currently.
9784 if (StaticLocalLinkage == GVA_StrongODR ||
9785 StaticLocalLinkage == GVA_AvailableExternally)
9786 return GVA_DiscardableODR;
9787 return StaticLocalLinkage;
9790 // MSVC treats in-class initialized static data members as definitions.
9791 // By giving them non-strong linkage, out-of-line definitions won't
9792 // cause link errors.
9793 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9794 return GVA_DiscardableODR;
9796 // Most non-template variables have strong linkage; inline variables are
9797 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9798 GVALinkage StrongLinkage;
9799 switch (Context.getInlineVariableDefinitionKind(VD)) {
9800 case ASTContext::InlineVariableDefinitionKind::None:
9801 StrongLinkage = GVA_StrongExternal;
9803 case ASTContext::InlineVariableDefinitionKind::Weak:
9804 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
9805 StrongLinkage = GVA_DiscardableODR;
9807 case ASTContext::InlineVariableDefinitionKind::Strong:
9808 StrongLinkage = GVA_StrongODR;
9812 switch (VD->getTemplateSpecializationKind()) {
9813 case TSK_Undeclared:
9814 return StrongLinkage;
9816 case TSK_ExplicitSpecialization:
9817 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9818 // If this is a fully specialized constexpr variable template, pretend it
9819 // was marked inline. MSVC 14.21.27702 headers define _Is_integral in a
9820 // header this way, and we don't want to emit non-discardable definitions
9821 // of these variables in every TU that includes <type_traits>. This
9822 // behavior is non-conforming, since another TU could use an extern
9823 // template declaration for this variable, but for constexpr variables,
9824 // it's unlikely for a user to want to do that. This behavior can be
9825 // removed if the headers change to explicitly mark such variable template
9826 // specializations inline.
9827 if (isa<VarTemplateSpecializationDecl>(VD) && VD->isConstexpr())
9828 return GVA_DiscardableODR;
9830 // Use ODR linkage for static data members of fully specialized templates
9831 // to prevent duplicate definition errors with MSVC.
9832 if (VD->isStaticDataMember())
9833 return GVA_StrongODR;
9835 return StrongLinkage;
9837 case TSK_ExplicitInstantiationDefinition:
9838 return GVA_StrongODR;
9840 case TSK_ExplicitInstantiationDeclaration:
9841 return GVA_AvailableExternally;
9843 case TSK_ImplicitInstantiation:
9844 return GVA_DiscardableODR;
9847 llvm_unreachable("Invalid Linkage!");
9850 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
9851 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9852 adjustGVALinkageForAttributes(*this, VD,
9853 basicGVALinkageForVariable(*this, VD)));
9856 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
9857 if (const auto *VD = dyn_cast<VarDecl>(D)) {
9858 if (!VD->isFileVarDecl())
9860 // Global named register variables (GNU extension) are never emitted.
9861 if (VD->getStorageClass() == SC_Register)
9863 if (VD->getDescribedVarTemplate() ||
9864 isa<VarTemplatePartialSpecializationDecl>(VD))
9866 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
9867 // We never need to emit an uninstantiated function template.
9868 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9870 } else if (isa<PragmaCommentDecl>(D))
9872 else if (isa<PragmaDetectMismatchDecl>(D))
9874 else if (isa<OMPThreadPrivateDecl>(D))
9875 return !D->getDeclContext()->isDependentContext();
9876 else if (isa<OMPAllocateDecl>(D))
9877 return !D->getDeclContext()->isDependentContext();
9878 else if (isa<OMPDeclareReductionDecl>(D))
9879 return !D->getDeclContext()->isDependentContext();
9880 else if (isa<ImportDecl>(D))
9885 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9886 assert(getExternalSource() && "It's from an AST file; must have a source.");
9887 // On Windows, PCH files are built together with an object file. If this
9888 // declaration comes from such a PCH and DeclMustBeEmitted would return
9889 // true, it would have returned true and the decl would have been emitted
9890 // into that object file, so it doesn't need to be emitted here.
9891 // Note that decls are still emitted if they're referenced, as usual;
9892 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9893 // if it's not referenced.
9895 // Explicit template instantiation definitions are tricky. If there was an
9896 // explicit template instantiation decl in the PCH before, it will look like
9897 // the definition comes from there, even if that was just the declaration.
9898 // (Explicit instantiation defs of variable templates always get emitted.)
9900 isa<FunctionDecl>(D) &&
9901 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9902 TSK_ExplicitInstantiationDefinition;
9904 // Implicit member function definitions, such as operator= might not be
9905 // marked as template specializations, since they're not coming from a
9906 // template but synthesized directly on the class.
9908 isa<CXXMethodDecl>(D) &&
9909 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
9910 TSK_ExplicitInstantiationDefinition;
9912 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9916 // If this is a member of a class template, we do not need to emit it.
9917 if (D->getDeclContext()->isDependentContext())
9920 // Weak references don't produce any output by themselves.
9921 if (D->hasAttr<WeakRefAttr>())
9924 // Aliases and used decls are required.
9925 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9928 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
9929 // Forward declarations aren't required.
9930 if (!FD->doesThisDeclarationHaveABody())
9931 return FD->doesDeclarationForceExternallyVisibleDefinition();
9933 // Constructors and destructors are required.
9934 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9937 // The key function for a class is required. This rule only comes
9938 // into play when inline functions can be key functions, though.
9939 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9940 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
9941 const CXXRecordDecl *RD = MD->getParent();
9942 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9943 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9944 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9950 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9952 // static, static inline, always_inline, and extern inline functions can
9953 // always be deferred. Normal inline functions can be deferred in C99/C++.
9954 // Implicit template instantiations can also be deferred in C++.
9955 return !isDiscardableGVALinkage(Linkage);
9958 const auto *VD = cast<VarDecl>(D);
9959 assert(VD->isFileVarDecl() && "Expected file scoped var");
9961 // If the decl is marked as `declare target to`, it should be emitted for the
9962 // host and for the device.
9963 if (LangOpts.OpenMP &&
9964 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
9967 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9968 !isMSStaticDataMemberInlineDefinition(VD))
9971 // Variables that can be needed in other TUs are required.
9972 auto Linkage = GetGVALinkageForVariable(VD);
9973 if (!isDiscardableGVALinkage(Linkage))
9976 // We never need to emit a variable that is available in another TU.
9977 if (Linkage == GVA_AvailableExternally)
9980 // Variables that have destruction with side-effects are required.
9981 if (VD->getType().isDestructedType())
9984 // Variables that have initialization with side-effects are required.
9985 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
9986 // We can get a value-dependent initializer during error recovery.
9987 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
9990 // Likewise, variables with tuple-like bindings are required if their
9991 // bindings have side-effects.
9992 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9993 for (const auto *BD : DD->bindings())
9994 if (const auto *BindingVD = BD->getHoldingVar())
9995 if (DeclMustBeEmitted(BindingVD))
10001 void ASTContext::forEachMultiversionedFunctionVersion(
10002 const FunctionDecl *FD,
10003 llvm::function_ref<void(FunctionDecl *)> Pred) const {
10004 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10005 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
10006 FD = FD->getMostRecentDecl();
10007 for (auto *CurDecl :
10008 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
10009 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
10010 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10011 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10012 SeenDecls.insert(CurFD);
10018 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
10020 bool IsBuiltin) const {
10021 // Pass through to the C++ ABI object
10023 return ABI->getDefaultMethodCallConv(IsVariadic);
10025 // Builtins ignore user-specified default calling convention and remain the
10026 // Target's default calling convention.
10028 switch (LangOpts.getDefaultCallingConv()) {
10029 case LangOptions::DCC_None:
10031 case LangOptions::DCC_CDecl:
10033 case LangOptions::DCC_FastCall:
10034 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10035 return CC_X86FastCall;
10037 case LangOptions::DCC_StdCall:
10039 return CC_X86StdCall;
10041 case LangOptions::DCC_VectorCall:
10042 // __vectorcall cannot be applied to variadic functions.
10044 return CC_X86VectorCall;
10046 case LangOptions::DCC_RegCall:
10047 // __regcall cannot be applied to variadic functions.
10049 return CC_X86RegCall;
10053 return Target->getDefaultCallingConv();
10056 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
10057 // Pass through to the C++ ABI object
10058 return ABI->isNearlyEmpty(RD);
10061 VTableContextBase *ASTContext::getVTableContext() {
10062 if (!VTContext.get()) {
10063 if (Target->getCXXABI().isMicrosoft())
10064 VTContext.reset(new MicrosoftVTableContext(*this));
10066 VTContext.reset(new ItaniumVTableContext(*this));
10068 return VTContext.get();
10071 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10074 switch (T->getCXXABI().getKind()) {
10075 case TargetCXXABI::GenericAArch64:
10076 case TargetCXXABI::GenericItanium:
10077 case TargetCXXABI::GenericARM:
10078 case TargetCXXABI::GenericMIPS:
10079 case TargetCXXABI::iOS:
10080 case TargetCXXABI::iOS64:
10081 case TargetCXXABI::WebAssembly:
10082 case TargetCXXABI::WatchOS:
10083 return ItaniumMangleContext::create(*this, getDiagnostics());
10084 case TargetCXXABI::Microsoft:
10085 return MicrosoftMangleContext::create(*this, getDiagnostics());
10087 llvm_unreachable("Unsupported ABI");
10090 CXXABI::~CXXABI() = default;
10092 size_t ASTContext::getSideTableAllocatedMemory() const {
10093 return ASTRecordLayouts.getMemorySize() +
10094 llvm::capacity_in_bytes(ObjCLayouts) +
10095 llvm::capacity_in_bytes(KeyFunctions) +
10096 llvm::capacity_in_bytes(ObjCImpls) +
10097 llvm::capacity_in_bytes(BlockVarCopyInits) +
10098 llvm::capacity_in_bytes(DeclAttrs) +
10099 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10100 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10101 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10102 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10103 llvm::capacity_in_bytes(OverriddenMethods) +
10104 llvm::capacity_in_bytes(Types) +
10105 llvm::capacity_in_bytes(VariableArrayTypes);
10108 /// getIntTypeForBitwidth -
10109 /// sets integer QualTy according to specified details:
10110 /// bitwidth, signed/unsigned.
10111 /// Returns empty type if there is no appropriate target types.
10112 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10113 unsigned Signed) const {
10114 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10115 CanQualType QualTy = getFromTargetType(Ty);
10116 if (!QualTy && DestWidth == 128)
10117 return Signed ? Int128Ty : UnsignedInt128Ty;
10121 /// getRealTypeForBitwidth -
10122 /// sets floating point QualTy according to specified bitwidth.
10123 /// Returns empty type if there is no appropriate target types.
10124 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10125 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10127 case TargetInfo::Float:
10129 case TargetInfo::Double:
10131 case TargetInfo::LongDouble:
10132 return LongDoubleTy;
10133 case TargetInfo::Float128:
10135 case TargetInfo::NoFloat:
10139 llvm_unreachable("Unhandled TargetInfo::RealType value");
10142 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10144 MangleNumbers[ND] = Number;
10147 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
10148 auto I = MangleNumbers.find(ND);
10149 return I != MangleNumbers.end() ? I->second : 1;
10152 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10154 StaticLocalNumbers[VD] = Number;
10157 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
10158 auto I = StaticLocalNumbers.find(VD);
10159 return I != StaticLocalNumbers.end() ? I->second : 1;
10162 MangleNumberingContext &
10163 ASTContext::getManglingNumberContext(const DeclContext *DC) {
10164 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10165 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
10167 MCtx = createMangleNumberingContext();
10171 std::unique_ptr<MangleNumberingContext>
10172 ASTContext::createMangleNumberingContext() const {
10173 return ABI->createMangleNumberingContext();
10176 const CXXConstructorDecl *
10177 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10178 return ABI->getCopyConstructorForExceptionObject(
10179 cast<CXXRecordDecl>(RD->getFirstDecl()));
10182 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10183 CXXConstructorDecl *CD) {
10184 return ABI->addCopyConstructorForExceptionObject(
10185 cast<CXXRecordDecl>(RD->getFirstDecl()),
10186 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10189 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10190 TypedefNameDecl *DD) {
10191 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10195 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10196 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10199 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10200 DeclaratorDecl *DD) {
10201 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10204 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10205 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10208 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10209 ParamIndices[D] = index;
10212 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10213 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
10214 assert(I != ParamIndices.end() &&
10215 "ParmIndices lacks entry set by ParmVarDecl");
10220 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
10222 assert(E && E->getStorageDuration() == SD_Static &&
10223 "don't need to cache the computed value for this temporary");
10225 APValue *&MTVI = MaterializedTemporaryValues[E];
10227 MTVI = new (*this) APValue;
10231 return MaterializedTemporaryValues.lookup(E);
10234 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
10235 unsigned Length) const {
10236 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10237 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10238 EltTy = EltTy.withConst();
10240 EltTy = adjustStringLiteralBaseType(EltTy);
10242 // Get an array type for the string, according to C99 6.4.5. This includes
10243 // the null terminator character.
10244 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1),
10245 ArrayType::Normal, /*IndexTypeQuals*/ 0);
10249 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
10250 StringLiteral *&Result = StringLiteralCache[Key];
10252 Result = StringLiteral::Create(
10253 *this, Key, StringLiteral::Ascii,
10254 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10259 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10260 const llvm::Triple &T = getTargetInfo().getTriple();
10261 if (!T.isOSDarwin())
10264 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10265 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10268 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10269 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10270 uint64_t Size = sizeChars.getQuantity();
10271 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10272 unsigned Align = alignChars.getQuantity();
10273 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10274 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10277 /// Template specializations to abstract away from pointers and TypeLocs.
10279 template <typename T>
10280 static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
10281 return ast_type_traits::DynTypedNode::create(*Node);
10284 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10285 return ast_type_traits::DynTypedNode::create(Node);
10288 ast_type_traits::DynTypedNode
10289 createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10290 return ast_type_traits::DynTypedNode::create(Node);
10294 /// A \c RecursiveASTVisitor that builds a map from nodes to their
10295 /// parents as defined by the \c RecursiveASTVisitor.
10297 /// Note that the relationship described here is purely in terms of AST
10298 /// traversal - there are other relationships (for example declaration context)
10299 /// in the AST that are better modeled by special matchers.
10301 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10302 class ASTContext::ParentMap::ASTVisitor
10303 : public RecursiveASTVisitor<ASTVisitor> {
10305 ASTVisitor(ParentMap &Map) : Map(Map) {}
10308 friend class RecursiveASTVisitor<ASTVisitor>;
10310 using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
10312 bool shouldVisitTemplateInstantiations() const { return true; }
10314 bool shouldVisitImplicitCode() const { return true; }
10316 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10318 bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10322 if (ParentStack.size() > 0) {
10323 // FIXME: Currently we add the same parent multiple times, but only
10324 // when no memoization data is available for the type.
10325 // For example when we visit all subexpressions of template
10326 // instantiations; this is suboptimal, but benign: the only way to
10327 // visit those is with hasAncestor / hasParent, and those do not create
10329 // The plan is to enable DynTypedNode to be storable in a map or hash
10330 // map. The main problem there is to implement hash functions /
10331 // comparison operators for all types that DynTypedNode supports that
10332 // do not have pointer identity.
10333 auto &NodeOrVector = (*Parents)[MapNode];
10334 if (NodeOrVector.isNull()) {
10335 if (const auto *D = ParentStack.back().get<Decl>())
10337 else if (const auto *S = ParentStack.back().get<Stmt>())
10340 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10342 if (!NodeOrVector.template is<ParentVector *>()) {
10343 auto *Vector = new ParentVector(
10344 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10345 delete NodeOrVector
10346 .template dyn_cast<ast_type_traits::DynTypedNode *>();
10347 NodeOrVector = Vector;
10350 auto *Vector = NodeOrVector.template get<ParentVector *>();
10351 // Skip duplicates for types that have memoization data.
10352 // We must check that the type has memoization data before calling
10353 // std::find() because DynTypedNode::operator== can't compare all
10355 bool Found = ParentStack.back().getMemoizationData() &&
10356 std::find(Vector->begin(), Vector->end(),
10357 ParentStack.back()) != Vector->end();
10359 Vector->push_back(ParentStack.back());
10362 ParentStack.push_back(createDynTypedNode(Node));
10363 bool Result = BaseTraverse();
10364 ParentStack.pop_back();
10368 bool TraverseDecl(Decl *DeclNode) {
10369 return TraverseNode(
10370 DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10371 &Map.PointerParents);
10374 bool TraverseStmt(Stmt *StmtNode) {
10375 return TraverseNode(
10376 StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
10377 &Map.PointerParents);
10380 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10381 return TraverseNode(
10382 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10383 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10384 &Map.OtherParents);
10387 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10388 return TraverseNode(
10389 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10390 [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10391 &Map.OtherParents);
10395 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
10398 ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
10399 ASTVisitor(*this).TraverseAST(Ctx);
10402 ASTContext::DynTypedNodeList
10403 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
10405 // We build the parent map for the traversal scope (usually whole TU), as
10406 // hasAncestor can escape any subtree.
10407 Parents = llvm::make_unique<ParentMap>(*this);
10408 return Parents->getParents(Node);
10412 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10413 const ObjCMethodDecl *MethodImpl) {
10414 // No point trying to match an unavailable/deprecated mothod.
10415 if (MethodDecl->hasAttr<UnavailableAttr>()
10416 || MethodDecl->hasAttr<DeprecatedAttr>())
10418 if (MethodDecl->getObjCDeclQualifier() !=
10419 MethodImpl->getObjCDeclQualifier())
10421 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
10424 if (MethodDecl->param_size() != MethodImpl->param_size())
10427 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10428 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10429 EF = MethodDecl->param_end();
10430 IM != EM && IF != EF; ++IM, ++IF) {
10431 const ParmVarDecl *DeclVar = (*IF);
10432 const ParmVarDecl *ImplVar = (*IM);
10433 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10435 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10439 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
10442 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
10444 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
10445 AS = LangAS::Default;
10447 AS = QT->getPointeeType().getAddressSpace();
10449 return getTargetInfo().getNullPointerValue(AS);
10452 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10453 if (isTargetAddressSpace(AS))
10454 return toTargetAddressSpace(AS);
10456 return (*AddrSpaceMap)[(unsigned)AS];
10459 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10460 assert(Ty->isFixedPointType());
10462 if (Ty->isSaturatedFixedPointType()) return Ty;
10464 const auto &BT = Ty->getAs<BuiltinType>();
10465 switch (BT->getKind()) {
10467 llvm_unreachable("Not a fixed point type!");
10468 case BuiltinType::ShortAccum:
10469 return SatShortAccumTy;
10470 case BuiltinType::Accum:
10472 case BuiltinType::LongAccum:
10473 return SatLongAccumTy;
10474 case BuiltinType::UShortAccum:
10475 return SatUnsignedShortAccumTy;
10476 case BuiltinType::UAccum:
10477 return SatUnsignedAccumTy;
10478 case BuiltinType::ULongAccum:
10479 return SatUnsignedLongAccumTy;
10480 case BuiltinType::ShortFract:
10481 return SatShortFractTy;
10482 case BuiltinType::Fract:
10484 case BuiltinType::LongFract:
10485 return SatLongFractTy;
10486 case BuiltinType::UShortFract:
10487 return SatUnsignedShortFractTy;
10488 case BuiltinType::UFract:
10489 return SatUnsignedFractTy;
10490 case BuiltinType::ULongFract:
10491 return SatUnsignedLongFractTy;
10495 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10496 if (LangOpts.OpenCL)
10497 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10500 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10502 return getLangASFromTargetAS(AS);
10505 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10506 // doesn't include ASTContext.h
10508 clang::LazyGenerationalUpdatePtr<
10509 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10510 clang::LazyGenerationalUpdatePtr<
10511 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10512 const clang::ASTContext &Ctx, Decl *Value);
10514 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10515 assert(Ty->isFixedPointType());
10517 const auto *BT = Ty->getAs<BuiltinType>();
10518 const TargetInfo &Target = getTargetInfo();
10519 switch (BT->getKind()) {
10521 llvm_unreachable("Not a fixed point type!");
10522 case BuiltinType::ShortAccum:
10523 case BuiltinType::SatShortAccum:
10524 return Target.getShortAccumScale();
10525 case BuiltinType::Accum:
10526 case BuiltinType::SatAccum:
10527 return Target.getAccumScale();
10528 case BuiltinType::LongAccum:
10529 case BuiltinType::SatLongAccum:
10530 return Target.getLongAccumScale();
10531 case BuiltinType::UShortAccum:
10532 case BuiltinType::SatUShortAccum:
10533 return Target.getUnsignedShortAccumScale();
10534 case BuiltinType::UAccum:
10535 case BuiltinType::SatUAccum:
10536 return Target.getUnsignedAccumScale();
10537 case BuiltinType::ULongAccum:
10538 case BuiltinType::SatULongAccum:
10539 return Target.getUnsignedLongAccumScale();
10540 case BuiltinType::ShortFract:
10541 case BuiltinType::SatShortFract:
10542 return Target.getShortFractScale();
10543 case BuiltinType::Fract:
10544 case BuiltinType::SatFract:
10545 return Target.getFractScale();
10546 case BuiltinType::LongFract:
10547 case BuiltinType::SatLongFract:
10548 return Target.getLongFractScale();
10549 case BuiltinType::UShortFract:
10550 case BuiltinType::SatUShortFract:
10551 return Target.getUnsignedShortFractScale();
10552 case BuiltinType::UFract:
10553 case BuiltinType::SatUFract:
10554 return Target.getUnsignedFractScale();
10555 case BuiltinType::ULongFract:
10556 case BuiltinType::SatULongFract:
10557 return Target.getUnsignedLongFractScale();
10561 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10562 assert(Ty->isFixedPointType());
10564 const auto *BT = Ty->getAs<BuiltinType>();
10565 const TargetInfo &Target = getTargetInfo();
10566 switch (BT->getKind()) {
10568 llvm_unreachable("Not a fixed point type!");
10569 case BuiltinType::ShortAccum:
10570 case BuiltinType::SatShortAccum:
10571 return Target.getShortAccumIBits();
10572 case BuiltinType::Accum:
10573 case BuiltinType::SatAccum:
10574 return Target.getAccumIBits();
10575 case BuiltinType::LongAccum:
10576 case BuiltinType::SatLongAccum:
10577 return Target.getLongAccumIBits();
10578 case BuiltinType::UShortAccum:
10579 case BuiltinType::SatUShortAccum:
10580 return Target.getUnsignedShortAccumIBits();
10581 case BuiltinType::UAccum:
10582 case BuiltinType::SatUAccum:
10583 return Target.getUnsignedAccumIBits();
10584 case BuiltinType::ULongAccum:
10585 case BuiltinType::SatULongAccum:
10586 return Target.getUnsignedLongAccumIBits();
10587 case BuiltinType::ShortFract:
10588 case BuiltinType::SatShortFract:
10589 case BuiltinType::Fract:
10590 case BuiltinType::SatFract:
10591 case BuiltinType::LongFract:
10592 case BuiltinType::SatLongFract:
10593 case BuiltinType::UShortFract:
10594 case BuiltinType::SatUShortFract:
10595 case BuiltinType::UFract:
10596 case BuiltinType::SatUFract:
10597 case BuiltinType::ULongFract:
10598 case BuiltinType::SatULongFract:
10603 FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
10604 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10605 "Can only get the fixed point semantics for a "
10606 "fixed point or integer type.");
10607 if (Ty->isIntegerType())
10608 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
10609 Ty->isSignedIntegerType());
10611 bool isSigned = Ty->isSignedFixedPointType();
10612 return FixedPointSemantics(
10613 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10614 Ty->isSaturatedFixedPointType(),
10615 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10618 APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10619 assert(Ty->isFixedPointType());
10620 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10623 APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10624 assert(Ty->isFixedPointType());
10625 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10628 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
10629 assert(Ty->isUnsignedFixedPointType() &&
10630 "Expected unsigned fixed point type");
10631 const auto *BTy = Ty->getAs<BuiltinType>();
10633 switch (BTy->getKind()) {
10634 case BuiltinType::UShortAccum:
10635 return ShortAccumTy;
10636 case BuiltinType::UAccum:
10638 case BuiltinType::ULongAccum:
10639 return LongAccumTy;
10640 case BuiltinType::SatUShortAccum:
10641 return SatShortAccumTy;
10642 case BuiltinType::SatUAccum:
10644 case BuiltinType::SatULongAccum:
10645 return SatLongAccumTy;
10646 case BuiltinType::UShortFract:
10647 return ShortFractTy;
10648 case BuiltinType::UFract:
10650 case BuiltinType::ULongFract:
10651 return LongFractTy;
10652 case BuiltinType::SatUShortFract:
10653 return SatShortFractTy;
10654 case BuiltinType::SatUFract:
10656 case BuiltinType::SatULongFract:
10657 return SatLongFractTy;
10659 llvm_unreachable("Unexpected unsigned fixed point type");