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 "Interp/Context.h"
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTConcept.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/ASTTypeTraits.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/AttrIterator.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/Comment.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclBase.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclContextInternals.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/DeclOpenMP.h"
30 #include "clang/AST/DeclTemplate.h"
31 #include "clang/AST/DeclarationName.h"
32 #include "clang/AST/DependenceFlags.h"
33 #include "clang/AST/Expr.h"
34 #include "clang/AST/ExprCXX.h"
35 #include "clang/AST/ExprConcepts.h"
36 #include "clang/AST/ExternalASTSource.h"
37 #include "clang/AST/Mangle.h"
38 #include "clang/AST/MangleNumberingContext.h"
39 #include "clang/AST/NestedNameSpecifier.h"
40 #include "clang/AST/ParentMapContext.h"
41 #include "clang/AST/RawCommentList.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/Stmt.h"
44 #include "clang/AST/TemplateBase.h"
45 #include "clang/AST/TemplateName.h"
46 #include "clang/AST/Type.h"
47 #include "clang/AST/TypeLoc.h"
48 #include "clang/AST/UnresolvedSet.h"
49 #include "clang/AST/VTableBuilder.h"
50 #include "clang/Basic/AddressSpaces.h"
51 #include "clang/Basic/Builtins.h"
52 #include "clang/Basic/CommentOptions.h"
53 #include "clang/Basic/ExceptionSpecificationType.h"
54 #include "clang/Basic/FixedPoint.h"
55 #include "clang/Basic/IdentifierTable.h"
56 #include "clang/Basic/LLVM.h"
57 #include "clang/Basic/LangOptions.h"
58 #include "clang/Basic/Linkage.h"
59 #include "clang/Basic/Module.h"
60 #include "clang/Basic/ObjCRuntime.h"
61 #include "clang/Basic/SanitizerBlacklist.h"
62 #include "clang/Basic/SourceLocation.h"
63 #include "clang/Basic/SourceManager.h"
64 #include "clang/Basic/Specifiers.h"
65 #include "clang/Basic/TargetCXXABI.h"
66 #include "clang/Basic/TargetInfo.h"
67 #include "clang/Basic/XRayLists.h"
68 #include "llvm/ADT/APInt.h"
69 #include "llvm/ADT/APSInt.h"
70 #include "llvm/ADT/ArrayRef.h"
71 #include "llvm/ADT/DenseMap.h"
72 #include "llvm/ADT/DenseSet.h"
73 #include "llvm/ADT/FoldingSet.h"
74 #include "llvm/ADT/None.h"
75 #include "llvm/ADT/Optional.h"
76 #include "llvm/ADT/PointerUnion.h"
77 #include "llvm/ADT/STLExtras.h"
78 #include "llvm/ADT/SmallPtrSet.h"
79 #include "llvm/ADT/SmallVector.h"
80 #include "llvm/ADT/StringExtras.h"
81 #include "llvm/ADT/StringRef.h"
82 #include "llvm/ADT/Triple.h"
83 #include "llvm/Support/Capacity.h"
84 #include "llvm/Support/Casting.h"
85 #include "llvm/Support/Compiler.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
100 using namespace clang;
103 BFloat16Rank, Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
106 /// \returns location that is relevant when searching for Doc comments related
108 static SourceLocation getDeclLocForCommentSearch(const Decl *D,
109 SourceManager &SourceMgr) {
112 // User can not attach documentation to implicit declarations.
116 // User can not attach documentation to implicit instantiations.
117 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
118 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
122 if (const auto *VD = dyn_cast<VarDecl>(D)) {
123 if (VD->isStaticDataMember() &&
124 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
128 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
129 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
133 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
134 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
135 if (TSK == TSK_ImplicitInstantiation ||
136 TSK == TSK_Undeclared)
140 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
141 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
144 if (const auto *TD = dyn_cast<TagDecl>(D)) {
145 // When tag declaration (but not definition!) is part of the
146 // decl-specifier-seq of some other declaration, it doesn't get comment
147 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
150 // TODO: handle comments for function parameters properly.
151 if (isa<ParmVarDecl>(D))
154 // TODO: we could look up template parameter documentation in the template
156 if (isa<TemplateTypeParmDecl>(D) ||
157 isa<NonTypeTemplateParmDecl>(D) ||
158 isa<TemplateTemplateParmDecl>(D))
161 // Find declaration location.
162 // For Objective-C declarations we generally don't expect to have multiple
163 // declarators, thus use declaration starting location as the "declaration
165 // For all other declarations multiple declarators are used quite frequently,
166 // so we use the location of the identifier as the "declaration location".
167 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
168 isa<ObjCPropertyDecl>(D) ||
169 isa<RedeclarableTemplateDecl>(D) ||
170 isa<ClassTemplateSpecializationDecl>(D) ||
171 // Allow association with Y across {} in `typedef struct X {} Y`.
173 return D->getBeginLoc();
175 const SourceLocation DeclLoc = D->getLocation();
176 if (DeclLoc.isMacroID()) {
177 if (isa<TypedefDecl>(D)) {
178 // If location of the typedef name is in a macro, it is because being
179 // declared via a macro. Try using declaration's starting location as
180 // the "declaration location".
181 return D->getBeginLoc();
182 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
183 // If location of the tag decl is inside a macro, but the spelling of
184 // the tag name comes from a macro argument, it looks like a special
185 // macro like NS_ENUM is being used to define the tag decl. In that
186 // case, adjust the source location to the expansion loc so that we can
187 // attach the comment to the tag decl.
188 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
189 TD->isCompleteDefinition())
190 return SourceMgr.getExpansionLoc(DeclLoc);
199 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
200 const Decl *D, const SourceLocation RepresentativeLocForDecl,
201 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
202 // If the declaration doesn't map directly to a location in a file, we
203 // can't find the comment.
204 if (RepresentativeLocForDecl.isInvalid() ||
205 !RepresentativeLocForDecl.isFileID())
208 // If there are no comments anywhere, we won't find anything.
209 if (CommentsInTheFile.empty())
212 // Decompose the location for the declaration and find the beginning of the
214 const std::pair<FileID, unsigned> DeclLocDecomp =
215 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
218 auto OffsetCommentBehindDecl =
219 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
221 // First check whether we have a trailing comment.
222 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
223 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
224 if ((CommentBehindDecl->isDocumentation() ||
225 LangOpts.CommentOpts.ParseAllComments) &&
226 CommentBehindDecl->isTrailingComment() &&
227 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
228 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
230 // Check that Doxygen trailing comment comes after the declaration, starts
231 // on the same line and in the same file as the declaration.
232 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
233 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
234 OffsetCommentBehindDecl->first)) {
235 return CommentBehindDecl;
240 // The comment just after the declaration was not a trailing comment.
241 // Let's look at the previous comment.
242 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
245 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
246 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
248 // Check that we actually have a non-member Doxygen comment.
249 if (!(CommentBeforeDecl->isDocumentation() ||
250 LangOpts.CommentOpts.ParseAllComments) ||
251 CommentBeforeDecl->isTrailingComment())
254 // Decompose the end of the comment.
255 const unsigned CommentEndOffset =
256 Comments.getCommentEndOffset(CommentBeforeDecl);
258 // Get the corresponding buffer.
259 bool Invalid = false;
260 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
265 // Extract text between the comment and declaration.
266 StringRef Text(Buffer + CommentEndOffset,
267 DeclLocDecomp.second - CommentEndOffset);
269 // There should be no other declarations or preprocessor directives between
270 // comment and declaration.
271 if (Text.find_first_of(";{}#@") != StringRef::npos)
274 return CommentBeforeDecl;
277 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
278 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
280 // If the declaration doesn't map directly to a location in a file, we
281 // can't find the comment.
282 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
285 if (ExternalSource && !CommentsLoaded) {
286 ExternalSource->ReadComments();
287 CommentsLoaded = true;
290 if (Comments.empty())
293 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
294 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
295 if (!CommentsInThisFile || CommentsInThisFile->empty())
298 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
301 void ASTContext::addComment(const RawComment &RC) {
302 assert(LangOpts.RetainCommentsFromSystemHeaders ||
303 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
304 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
307 /// If we have a 'templated' declaration for a template, adjust 'D' to
308 /// refer to the actual template.
309 /// If we have an implicit instantiation, adjust 'D' to refer to template.
310 static const Decl &adjustDeclToTemplate(const Decl &D) {
311 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
312 // Is this function declaration part of a function template?
313 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
316 // Nothing to do if function is not an implicit instantiation.
317 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
320 // Function is an implicit instantiation of a function template?
321 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
324 // Function is instantiated from a member definition of a class template?
325 if (const FunctionDecl *MemberDecl =
326 FD->getInstantiatedFromMemberFunction())
331 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
332 // Static data member is instantiated from a member definition of a class
334 if (VD->isStaticDataMember())
335 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
340 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
341 // Is this class declaration part of a class template?
342 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
345 // Class is an implicit instantiation of a class template or partial
347 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
348 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
350 llvm::PointerUnion<ClassTemplateDecl *,
351 ClassTemplatePartialSpecializationDecl *>
352 PU = CTSD->getSpecializedTemplateOrPartial();
353 return PU.is<ClassTemplateDecl *>()
354 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
355 : *static_cast<const Decl *>(
356 PU.get<ClassTemplatePartialSpecializationDecl *>());
359 // Class is instantiated from a member definition of a class template?
360 if (const MemberSpecializationInfo *Info =
361 CRD->getMemberSpecializationInfo())
362 return *Info->getInstantiatedFrom();
366 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
367 // Enum is instantiated from a member definition of a class template?
368 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
373 // FIXME: Adjust alias templates?
377 const RawComment *ASTContext::getRawCommentForAnyRedecl(
379 const Decl **OriginalDecl) const {
382 OriginalDecl = nullptr;
386 D = &adjustDeclToTemplate(*D);
388 // Any comment directly attached to D?
390 auto DeclComment = DeclRawComments.find(D);
391 if (DeclComment != DeclRawComments.end()) {
394 return DeclComment->second;
398 // Any comment attached to any redeclaration of D?
399 const Decl *CanonicalD = D->getCanonicalDecl();
404 auto RedeclComment = RedeclChainComments.find(CanonicalD);
405 if (RedeclComment != RedeclChainComments.end()) {
407 *OriginalDecl = RedeclComment->second;
408 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
409 assert(CommentAtRedecl != DeclRawComments.end() &&
410 "This decl is supposed to have comment attached.");
411 return CommentAtRedecl->second;
415 // Any redeclarations of D that we haven't checked for comments yet?
416 // We can't use DenseMap::iterator directly since it'd get invalid.
417 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
418 auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
419 if (LookupRes != CommentlessRedeclChains.end())
420 return LookupRes->second;
424 for (const auto Redecl : D->redecls()) {
426 // Skip all redeclarations that have been checked previously.
427 if (LastCheckedRedecl) {
428 if (LastCheckedRedecl == Redecl) {
429 LastCheckedRedecl = nullptr;
433 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
435 cacheRawCommentForDecl(*Redecl, *RedeclComment);
437 *OriginalDecl = Redecl;
438 return RedeclComment;
440 CommentlessRedeclChains[CanonicalD] = Redecl;
444 *OriginalDecl = nullptr;
448 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
449 const RawComment &Comment) const {
450 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
451 DeclRawComments.try_emplace(&OriginalD, &Comment);
452 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
453 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
454 CommentlessRedeclChains.erase(CanonicalDecl);
457 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
458 SmallVectorImpl<const NamedDecl *> &Redeclared) {
459 const DeclContext *DC = ObjCMethod->getDeclContext();
460 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
461 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
464 // Add redeclared method here.
465 for (const auto *Ext : ID->known_extensions()) {
466 if (ObjCMethodDecl *RedeclaredMethod =
467 Ext->getMethod(ObjCMethod->getSelector(),
468 ObjCMethod->isInstanceMethod()))
469 Redeclared.push_back(RedeclaredMethod);
474 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
475 const Preprocessor *PP) {
476 if (Comments.empty() || Decls.empty())
480 for (Decl *D : Decls) {
481 SourceLocation Loc = D->getLocation();
483 // See if there are any new comments that are not attached to a decl.
484 // The location doesn't have to be precise - we care only about the file.
485 File = SourceMgr.getDecomposedLoc(Loc).first;
490 if (File.isInvalid())
493 auto CommentsInThisFile = Comments.getCommentsInFile(File);
494 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
495 CommentsInThisFile->rbegin()->second->isAttached())
498 // There is at least one comment not attached to a decl.
499 // Maybe it should be attached to one of Decls?
501 // Note that this way we pick up not only comments that precede the
502 // declaration, but also comments that *follow* the declaration -- thanks to
503 // the lookahead in the lexer: we've consumed the semicolon and looked
504 // ahead through comments.
506 for (const Decl *D : Decls) {
508 if (D->isInvalidDecl())
511 D = &adjustDeclToTemplate(*D);
513 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
515 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
518 if (DeclRawComments.count(D) > 0)
521 if (RawComment *const DocComment =
522 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
523 cacheRawCommentForDecl(*D, *DocComment);
524 comments::FullComment *FC = DocComment->parse(*this, PP, D);
525 ParsedComments[D->getCanonicalDecl()] = FC;
530 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
531 const Decl *D) const {
532 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
533 ThisDeclInfo->CommentDecl = D;
534 ThisDeclInfo->IsFilled = false;
535 ThisDeclInfo->fill();
536 ThisDeclInfo->CommentDecl = FC->getDecl();
537 if (!ThisDeclInfo->TemplateParameters)
538 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
539 comments::FullComment *CFC =
540 new (*this) comments::FullComment(FC->getBlocks(),
545 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
546 const RawComment *RC = getRawCommentForDeclNoCache(D);
547 return RC ? RC->parse(*this, nullptr, D) : nullptr;
550 comments::FullComment *ASTContext::getCommentForDecl(
552 const Preprocessor *PP) const {
553 if (!D || D->isInvalidDecl())
555 D = &adjustDeclToTemplate(*D);
557 const Decl *Canonical = D->getCanonicalDecl();
558 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
559 ParsedComments.find(Canonical);
561 if (Pos != ParsedComments.end()) {
562 if (Canonical != D) {
563 comments::FullComment *FC = Pos->second;
564 comments::FullComment *CFC = cloneFullComment(FC, D);
570 const Decl *OriginalDecl = nullptr;
572 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
574 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
575 SmallVector<const NamedDecl*, 8> Overridden;
576 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
577 if (OMD && OMD->isPropertyAccessor())
578 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
579 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
580 return cloneFullComment(FC, D);
582 addRedeclaredMethods(OMD, Overridden);
583 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
584 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
585 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
586 return cloneFullComment(FC, D);
588 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
589 // Attach any tag type's documentation to its typedef if latter
590 // does not have one of its own.
591 QualType QT = TD->getUnderlyingType();
592 if (const auto *TT = QT->getAs<TagType>())
593 if (const Decl *TD = TT->getDecl())
594 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
595 return cloneFullComment(FC, D);
597 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
598 while (IC->getSuperClass()) {
599 IC = IC->getSuperClass();
600 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
601 return cloneFullComment(FC, D);
604 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
605 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
606 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
607 return cloneFullComment(FC, D);
609 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
610 if (!(RD = RD->getDefinition()))
612 // Check non-virtual bases.
613 for (const auto &I : RD->bases()) {
614 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
616 QualType Ty = I.getType();
619 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
620 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
623 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
624 return cloneFullComment(FC, D);
627 // Check virtual bases.
628 for (const auto &I : RD->vbases()) {
629 if (I.getAccessSpecifier() != AS_public)
631 QualType Ty = I.getType();
634 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
635 if (!(VirtualBase= VirtualBase->getDefinition()))
637 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
638 return cloneFullComment(FC, D);
645 // If the RawComment was attached to other redeclaration of this Decl, we
646 // should parse the comment in context of that other Decl. This is important
647 // because comments can contain references to parameter names which can be
648 // different across redeclarations.
649 if (D != OriginalDecl && OriginalDecl)
650 return getCommentForDecl(OriginalDecl, PP);
652 comments::FullComment *FC = RC->parse(*this, PP, D);
653 ParsedComments[Canonical] = FC;
658 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
660 TemplateTemplateParmDecl *Parm) {
661 ID.AddInteger(Parm->getDepth());
662 ID.AddInteger(Parm->getPosition());
663 ID.AddBoolean(Parm->isParameterPack());
665 TemplateParameterList *Params = Parm->getTemplateParameters();
666 ID.AddInteger(Params->size());
667 for (TemplateParameterList::const_iterator P = Params->begin(),
668 PEnd = Params->end();
670 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
672 ID.AddBoolean(TTP->isParameterPack());
673 const TypeConstraint *TC = TTP->getTypeConstraint();
674 ID.AddBoolean(TC != nullptr);
676 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
678 if (TTP->isExpandedParameterPack()) {
680 ID.AddInteger(TTP->getNumExpansionParameters());
682 ID.AddBoolean(false);
686 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
688 ID.AddBoolean(NTTP->isParameterPack());
689 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
690 if (NTTP->isExpandedParameterPack()) {
692 ID.AddInteger(NTTP->getNumExpansionTypes());
693 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
694 QualType T = NTTP->getExpansionType(I);
695 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
698 ID.AddBoolean(false);
702 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
706 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
707 ID.AddBoolean(RequiresClause != nullptr);
709 RequiresClause->Profile(ID, C, /*Canonical=*/true);
713 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
714 QualType ConstrainedType) {
715 // This is a bit ugly - we need to form a new immediately-declared
716 // constraint that references the new parameter; this would ideally
717 // require semantic analysis (e.g. template<C T> struct S {}; - the
718 // converted arguments of C<T> could be an argument pack if C is
719 // declared as template<typename... T> concept C = ...).
720 // We don't have semantic analysis here so we dig deep into the
721 // ready-made constraint expr and change the thing manually.
722 ConceptSpecializationExpr *CSE;
723 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
724 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
726 CSE = cast<ConceptSpecializationExpr>(IDC);
727 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
728 SmallVector<TemplateArgument, 3> NewConverted;
729 NewConverted.reserve(OldConverted.size());
730 if (OldConverted.front().getKind() == TemplateArgument::Pack) {
732 // template<typename... T> concept C = true;
733 // template<C<int> T> struct S; -> constraint is C<{T, int}>
734 NewConverted.push_back(ConstrainedType);
735 for (auto &Arg : OldConverted.front().pack_elements().drop_front(1))
736 NewConverted.push_back(Arg);
737 TemplateArgument NewPack(NewConverted);
739 NewConverted.clear();
740 NewConverted.push_back(NewPack);
741 assert(OldConverted.size() == 1 &&
742 "Template parameter pack should be the last parameter");
744 assert(OldConverted.front().getKind() == TemplateArgument::Type &&
745 "Unexpected first argument kind for immediately-declared "
747 NewConverted.push_back(ConstrainedType);
748 for (auto &Arg : OldConverted.drop_front(1))
749 NewConverted.push_back(Arg);
751 Expr *NewIDC = ConceptSpecializationExpr::Create(
752 C, CSE->getNamedConcept(), NewConverted, nullptr,
753 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
755 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
756 NewIDC = new (C) CXXFoldExpr(OrigFold->getType(), SourceLocation(), NewIDC,
757 BinaryOperatorKind::BO_LAnd,
758 SourceLocation(), /*RHS=*/nullptr,
759 SourceLocation(), /*NumExpansions=*/None);
763 TemplateTemplateParmDecl *
764 ASTContext::getCanonicalTemplateTemplateParmDecl(
765 TemplateTemplateParmDecl *TTP) const {
766 // Check if we already have a canonical template template parameter.
767 llvm::FoldingSetNodeID ID;
768 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
769 void *InsertPos = nullptr;
770 CanonicalTemplateTemplateParm *Canonical
771 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
773 return Canonical->getParam();
775 // Build a canonical template parameter list.
776 TemplateParameterList *Params = TTP->getTemplateParameters();
777 SmallVector<NamedDecl *, 4> CanonParams;
778 CanonParams.reserve(Params->size());
779 for (TemplateParameterList::const_iterator P = Params->begin(),
780 PEnd = Params->end();
782 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
783 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
784 getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
785 TTP->getDepth(), TTP->getIndex(), nullptr, false,
786 TTP->isParameterPack(), TTP->hasTypeConstraint(),
787 TTP->isExpandedParameterPack() ?
788 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
789 if (const auto *TC = TTP->getTypeConstraint()) {
790 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
791 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
792 *this, TC->getImmediatelyDeclaredConstraint(),
794 TemplateArgumentListInfo CanonArgsAsWritten;
795 if (auto *Args = TC->getTemplateArgsAsWritten())
796 for (const auto &ArgLoc : Args->arguments())
797 CanonArgsAsWritten.addArgument(
798 TemplateArgumentLoc(ArgLoc.getArgument(),
799 TemplateArgumentLocInfo()));
800 NewTTP->setTypeConstraint(
801 NestedNameSpecifierLoc(),
802 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
803 SourceLocation()), /*FoundDecl=*/nullptr,
804 // Actually canonicalizing a TemplateArgumentLoc is difficult so we
805 // simply omit the ArgsAsWritten
806 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
808 CanonParams.push_back(NewTTP);
809 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
810 QualType T = getCanonicalType(NTTP->getType());
811 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
812 NonTypeTemplateParmDecl *Param;
813 if (NTTP->isExpandedParameterPack()) {
814 SmallVector<QualType, 2> ExpandedTypes;
815 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
816 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
817 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
818 ExpandedTInfos.push_back(
819 getTrivialTypeSourceInfo(ExpandedTypes.back()));
822 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
826 NTTP->getPosition(), nullptr,
832 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
836 NTTP->getPosition(), nullptr,
838 NTTP->isParameterPack(),
841 if (AutoType *AT = T->getContainedAutoType()) {
842 if (AT->isConstrained()) {
843 Param->setPlaceholderTypeConstraint(
844 canonicalizeImmediatelyDeclaredConstraint(
845 *this, NTTP->getPlaceholderTypeConstraint(), T));
848 CanonParams.push_back(Param);
851 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
852 cast<TemplateTemplateParmDecl>(*P)));
855 Expr *CanonRequiresClause = nullptr;
856 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
857 CanonRequiresClause = RequiresClause;
859 TemplateTemplateParmDecl *CanonTTP
860 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
861 SourceLocation(), TTP->getDepth(),
863 TTP->isParameterPack(),
865 TemplateParameterList::Create(*this, SourceLocation(),
869 CanonRequiresClause));
871 // Get the new insert position for the node we care about.
872 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
873 assert(!Canonical && "Shouldn't be in the map!");
876 // Create the canonical template template parameter entry.
877 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
878 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
882 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
883 if (!LangOpts.CPlusPlus) return nullptr;
885 switch (T.getCXXABI().getKind()) {
886 case TargetCXXABI::Fuchsia:
887 case TargetCXXABI::GenericARM: // Same as Itanium at this level
888 case TargetCXXABI::iOS:
889 case TargetCXXABI::iOS64:
890 case TargetCXXABI::WatchOS:
891 case TargetCXXABI::GenericAArch64:
892 case TargetCXXABI::GenericMIPS:
893 case TargetCXXABI::GenericItanium:
894 case TargetCXXABI::WebAssembly:
895 case TargetCXXABI::XL:
896 return CreateItaniumCXXABI(*this);
897 case TargetCXXABI::Microsoft:
898 return CreateMicrosoftCXXABI(*this);
900 llvm_unreachable("Invalid CXXABI type!");
903 interp::Context &ASTContext::getInterpContext() {
904 if (!InterpContext) {
905 InterpContext.reset(new interp::Context(*this));
907 return *InterpContext.get();
910 ParentMapContext &ASTContext::getParentMapContext() {
912 ParentMapCtx.reset(new ParentMapContext(*this));
913 return *ParentMapCtx.get();
916 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
917 const LangOptions &LOpts) {
918 if (LOpts.FakeAddressSpaceMap) {
919 // The fake address space map must have a distinct entry for each
920 // language-specific address space.
921 static const unsigned FakeAddrSpaceMap[] = {
925 2, // opencl_constant
935 return &FakeAddrSpaceMap;
937 return &T.getAddressSpaceMap();
941 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
942 const LangOptions &LangOpts) {
943 switch (LangOpts.getAddressSpaceMapMangling()) {
944 case LangOptions::ASMM_Target:
945 return TI.useAddressSpaceMapMangling();
946 case LangOptions::ASMM_On:
948 case LangOptions::ASMM_Off:
951 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
954 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
955 IdentifierTable &idents, SelectorTable &sels,
956 Builtin::Context &builtins)
957 : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
958 TemplateSpecializationTypes(this_()),
959 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
960 SubstTemplateTemplateParmPacks(this_()),
961 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
962 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
963 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
964 LangOpts.XRayNeverInstrumentFiles,
965 LangOpts.XRayAttrListFiles, SM)),
966 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
967 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
968 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
969 CompCategories(this_()), LastSDM(nullptr, 0) {
970 TUDecl = TranslationUnitDecl::Create(*this);
971 TraversalScope = {TUDecl};
974 ASTContext::~ASTContext() {
975 // Release the DenseMaps associated with DeclContext objects.
976 // FIXME: Is this the ideal solution?
977 ReleaseDeclContextMaps();
979 // Call all of the deallocation functions on all of their targets.
980 for (auto &Pair : Deallocations)
981 (Pair.first)(Pair.second);
983 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
984 // because they can contain DenseMaps.
985 for (llvm::DenseMap<const ObjCContainerDecl*,
986 const ASTRecordLayout*>::iterator
987 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
988 // Increment in loop to prevent using deallocated memory.
989 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
992 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
993 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
994 // Increment in loop to prevent using deallocated memory.
995 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
999 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1000 AEnd = DeclAttrs.end();
1002 A->second->~AttrVec();
1004 for (const auto &Value : ModuleInitializers)
1005 Value.second->~PerModuleInitializers();
1007 for (APValue *Value : APValueCleanups)
1011 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1012 TraversalScope = TopLevelDecls;
1013 getParentMapContext().clear();
1016 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1017 Deallocations.push_back({Callback, Data});
1021 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1022 ExternalSource = std::move(Source);
1025 void ASTContext::PrintStats() const {
1026 llvm::errs() << "\n*** AST Context Stats:\n";
1027 llvm::errs() << " " << Types.size() << " types total.\n";
1029 unsigned counts[] = {
1030 #define TYPE(Name, Parent) 0,
1031 #define ABSTRACT_TYPE(Name, Parent)
1032 #include "clang/AST/TypeNodes.inc"
1036 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1038 counts[(unsigned)T->getTypeClass()]++;
1042 unsigned TotalBytes = 0;
1043 #define TYPE(Name, Parent) \
1045 llvm::errs() << " " << counts[Idx] << " " << #Name \
1046 << " types, " << sizeof(Name##Type) << " each " \
1047 << "(" << counts[Idx] * sizeof(Name##Type) \
1049 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1051 #define ABSTRACT_TYPE(Name, Parent)
1052 #include "clang/AST/TypeNodes.inc"
1054 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1056 // Implicit special member functions.
1057 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1058 << NumImplicitDefaultConstructors
1059 << " implicit default constructors created\n";
1060 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1061 << NumImplicitCopyConstructors
1062 << " implicit copy constructors created\n";
1063 if (getLangOpts().CPlusPlus)
1064 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1065 << NumImplicitMoveConstructors
1066 << " implicit move constructors created\n";
1067 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1068 << NumImplicitCopyAssignmentOperators
1069 << " implicit copy assignment operators created\n";
1070 if (getLangOpts().CPlusPlus)
1071 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1072 << NumImplicitMoveAssignmentOperators
1073 << " implicit move assignment operators created\n";
1074 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1075 << NumImplicitDestructors
1076 << " implicit destructors created\n";
1078 if (ExternalSource) {
1079 llvm::errs() << "\n";
1080 ExternalSource->PrintStats();
1083 BumpAlloc.PrintStats();
1086 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1087 bool NotifyListeners) {
1088 if (NotifyListeners)
1089 if (auto *Listener = getASTMutationListener())
1090 Listener->RedefinedHiddenDefinition(ND, M);
1092 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1095 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1096 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1097 if (It == MergedDefModules.end())
1100 auto &Merged = It->second;
1101 llvm::DenseSet<Module*> Found;
1102 for (Module *&M : Merged)
1103 if (!Found.insert(M).second)
1105 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1109 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1111 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1112 if (MergedIt == MergedDefModules.end())
1114 return MergedIt->second;
1117 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1118 if (LazyInitializers.empty())
1121 auto *Source = Ctx.getExternalSource();
1122 assert(Source && "lazy initializers but no external source");
1124 auto LazyInits = std::move(LazyInitializers);
1125 LazyInitializers.clear();
1127 for (auto ID : LazyInits)
1128 Initializers.push_back(Source->GetExternalDecl(ID));
1130 assert(LazyInitializers.empty() &&
1131 "GetExternalDecl for lazy module initializer added more inits");
1134 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1135 // One special case: if we add a module initializer that imports another
1136 // module, and that module's only initializer is an ImportDecl, simplify.
1137 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1138 auto It = ModuleInitializers.find(ID->getImportedModule());
1140 // Maybe the ImportDecl does nothing at all. (Common case.)
1141 if (It == ModuleInitializers.end())
1144 // Maybe the ImportDecl only imports another ImportDecl.
1145 auto &Imported = *It->second;
1146 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1147 Imported.resolve(*this);
1148 auto *OnlyDecl = Imported.Initializers.front();
1149 if (isa<ImportDecl>(OnlyDecl))
1154 auto *&Inits = ModuleInitializers[M];
1156 Inits = new (*this) PerModuleInitializers;
1157 Inits->Initializers.push_back(D);
1160 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1161 auto *&Inits = ModuleInitializers[M];
1163 Inits = new (*this) PerModuleInitializers;
1164 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1165 IDs.begin(), IDs.end());
1168 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1169 auto It = ModuleInitializers.find(M);
1170 if (It == ModuleInitializers.end())
1173 auto *Inits = It->second;
1174 Inits->resolve(*this);
1175 return Inits->Initializers;
1178 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1179 if (!ExternCContext)
1180 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1182 return ExternCContext;
1185 BuiltinTemplateDecl *
1186 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1187 const IdentifierInfo *II) const {
1188 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1189 BuiltinTemplate->setImplicit();
1190 TUDecl->addDecl(BuiltinTemplate);
1192 return BuiltinTemplate;
1195 BuiltinTemplateDecl *
1196 ASTContext::getMakeIntegerSeqDecl() const {
1197 if (!MakeIntegerSeqDecl)
1198 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1199 getMakeIntegerSeqName());
1200 return MakeIntegerSeqDecl;
1203 BuiltinTemplateDecl *
1204 ASTContext::getTypePackElementDecl() const {
1205 if (!TypePackElementDecl)
1206 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1207 getTypePackElementName());
1208 return TypePackElementDecl;
1211 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1212 RecordDecl::TagKind TK) const {
1214 RecordDecl *NewDecl;
1215 if (getLangOpts().CPlusPlus)
1216 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1217 Loc, &Idents.get(Name));
1219 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1221 NewDecl->setImplicit();
1222 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1223 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1227 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1228 StringRef Name) const {
1229 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1230 TypedefDecl *NewDecl = TypedefDecl::Create(
1231 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1232 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1233 NewDecl->setImplicit();
1237 TypedefDecl *ASTContext::getInt128Decl() const {
1239 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1243 TypedefDecl *ASTContext::getUInt128Decl() const {
1245 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1249 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1250 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1251 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1252 Types.push_back(Ty);
1255 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1256 const TargetInfo *AuxTarget) {
1257 assert((!this->Target || this->Target == &Target) &&
1258 "Incorrect target reinitialization");
1259 assert(VoidTy.isNull() && "Context reinitialized?");
1261 this->Target = &Target;
1262 this->AuxTarget = AuxTarget;
1264 ABI.reset(createCXXABI(Target));
1265 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1266 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1269 InitBuiltinType(VoidTy, BuiltinType::Void);
1272 InitBuiltinType(BoolTy, BuiltinType::Bool);
1274 if (LangOpts.CharIsSigned)
1275 InitBuiltinType(CharTy, BuiltinType::Char_S);
1277 InitBuiltinType(CharTy, BuiltinType::Char_U);
1279 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1280 InitBuiltinType(ShortTy, BuiltinType::Short);
1281 InitBuiltinType(IntTy, BuiltinType::Int);
1282 InitBuiltinType(LongTy, BuiltinType::Long);
1283 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1286 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1287 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1288 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1289 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1290 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1293 InitBuiltinType(FloatTy, BuiltinType::Float);
1294 InitBuiltinType(DoubleTy, BuiltinType::Double);
1295 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1297 // GNU extension, __float128 for IEEE quadruple precision
1298 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1300 // C11 extension ISO/IEC TS 18661-3
1301 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1303 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1304 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1305 InitBuiltinType(AccumTy, BuiltinType::Accum);
1306 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1307 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1308 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1309 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1310 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1311 InitBuiltinType(FractTy, BuiltinType::Fract);
1312 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1313 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1314 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1315 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1316 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1317 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1318 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1319 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1320 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1321 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1322 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1323 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1324 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1325 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1326 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1327 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1329 // GNU extension, 128-bit integers.
1330 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1331 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1334 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1335 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1336 else // -fshort-wchar makes wchar_t be unsigned.
1337 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1338 if (LangOpts.CPlusPlus && LangOpts.WChar)
1339 WideCharTy = WCharTy;
1341 // C99 (or C++ using -fno-wchar).
1342 WideCharTy = getFromTargetType(Target.getWCharType());
1345 WIntTy = getFromTargetType(Target.getWIntType());
1348 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1350 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1351 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1353 Char16Ty = getFromTargetType(Target.getChar16Type());
1355 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1356 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1358 Char32Ty = getFromTargetType(Target.getChar32Type());
1360 // Placeholder type for type-dependent expressions whose type is
1361 // completely unknown. No code should ever check a type against
1362 // DependentTy and users should never see it; however, it is here to
1363 // help diagnose failures to properly check for type-dependent
1365 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1367 // Placeholder type for functions.
1368 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1370 // Placeholder type for bound members.
1371 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1373 // Placeholder type for pseudo-objects.
1374 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1376 // "any" type; useful for debugger-like clients.
1377 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1379 // Placeholder type for unbridged ARC casts.
1380 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1382 // Placeholder type for builtin functions.
1383 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1385 // Placeholder type for OMP array sections.
1386 if (LangOpts.OpenMP) {
1387 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1388 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1389 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1391 if (LangOpts.MatrixTypes)
1392 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1395 FloatComplexTy = getComplexType(FloatTy);
1396 DoubleComplexTy = getComplexType(DoubleTy);
1397 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1398 Float128ComplexTy = getComplexType(Float128Ty);
1400 // Builtin types for 'id', 'Class', and 'SEL'.
1401 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1402 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1403 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1405 if (LangOpts.OpenCL) {
1406 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1407 InitBuiltinType(SingletonId, BuiltinType::Id);
1408 #include "clang/Basic/OpenCLImageTypes.def"
1410 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1411 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1412 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1413 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1414 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1416 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1417 InitBuiltinType(Id##Ty, BuiltinType::Id);
1418 #include "clang/Basic/OpenCLExtensionTypes.def"
1421 if (Target.hasAArch64SVETypes()) {
1422 #define SVE_TYPE(Name, Id, SingletonId) \
1423 InitBuiltinType(SingletonId, BuiltinType::Id);
1424 #include "clang/Basic/AArch64SVEACLETypes.def"
1427 // Builtin type for __objc_yes and __objc_no
1428 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1429 SignedCharTy : BoolTy);
1431 ObjCConstantStringType = QualType();
1433 ObjCSuperType = QualType();
1436 if (LangOpts.OpenCLVersion >= 200) {
1437 auto Q = VoidTy.getQualifiers();
1438 Q.setAddressSpace(LangAS::opencl_generic);
1439 VoidPtrTy = getPointerType(getCanonicalType(
1440 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1442 VoidPtrTy = getPointerType(VoidTy);
1445 // nullptr type (C++0x 2.14.7)
1446 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1448 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1449 InitBuiltinType(HalfTy, BuiltinType::Half);
1451 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1453 // Builtin type used to help define __builtin_va_list.
1454 VaListTagDecl = nullptr;
1456 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1457 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1458 MSGuidTagDecl = buildImplicitRecord("_GUID");
1459 TUDecl->addDecl(MSGuidTagDecl);
1463 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1464 return SourceMgr.getDiagnostics();
1467 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1468 AttrVec *&Result = DeclAttrs[D];
1470 void *Mem = Allocate(sizeof(AttrVec));
1471 Result = new (Mem) AttrVec;
1477 /// Erase the attributes corresponding to the given declaration.
1478 void ASTContext::eraseDeclAttrs(const Decl *D) {
1479 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1480 if (Pos != DeclAttrs.end()) {
1481 Pos->second->~AttrVec();
1482 DeclAttrs.erase(Pos);
1487 MemberSpecializationInfo *
1488 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1489 assert(Var->isStaticDataMember() && "Not a static data member");
1490 return getTemplateOrSpecializationInfo(Var)
1491 .dyn_cast<MemberSpecializationInfo *>();
1494 ASTContext::TemplateOrSpecializationInfo
1495 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1496 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1497 TemplateOrInstantiation.find(Var);
1498 if (Pos == TemplateOrInstantiation.end())
1505 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1506 TemplateSpecializationKind TSK,
1507 SourceLocation PointOfInstantiation) {
1508 assert(Inst->isStaticDataMember() && "Not a static data member");
1509 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1510 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1511 Tmpl, TSK, PointOfInstantiation));
1515 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1516 TemplateOrSpecializationInfo TSI) {
1517 assert(!TemplateOrInstantiation[Inst] &&
1518 "Already noted what the variable was instantiated from");
1519 TemplateOrInstantiation[Inst] = TSI;
1523 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1524 auto Pos = InstantiatedFromUsingDecl.find(UUD);
1525 if (Pos == InstantiatedFromUsingDecl.end())
1532 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1533 assert((isa<UsingDecl>(Pattern) ||
1534 isa<UnresolvedUsingValueDecl>(Pattern) ||
1535 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1536 "pattern decl is not a using decl");
1537 assert((isa<UsingDecl>(Inst) ||
1538 isa<UnresolvedUsingValueDecl>(Inst) ||
1539 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1540 "instantiation did not produce a using decl");
1541 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1542 InstantiatedFromUsingDecl[Inst] = Pattern;
1546 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1547 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1548 = InstantiatedFromUsingShadowDecl.find(Inst);
1549 if (Pos == InstantiatedFromUsingShadowDecl.end())
1556 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1557 UsingShadowDecl *Pattern) {
1558 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1559 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1562 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1563 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1564 = InstantiatedFromUnnamedFieldDecl.find(Field);
1565 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1571 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1573 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1574 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1575 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1576 "Already noted what unnamed field was instantiated from");
1578 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1581 ASTContext::overridden_cxx_method_iterator
1582 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1583 return overridden_methods(Method).begin();
1586 ASTContext::overridden_cxx_method_iterator
1587 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1588 return overridden_methods(Method).end();
1592 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1593 auto Range = overridden_methods(Method);
1594 return Range.end() - Range.begin();
1597 ASTContext::overridden_method_range
1598 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1599 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1600 OverriddenMethods.find(Method->getCanonicalDecl());
1601 if (Pos == OverriddenMethods.end())
1602 return overridden_method_range(nullptr, nullptr);
1603 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1606 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1607 const CXXMethodDecl *Overridden) {
1608 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1609 OverriddenMethods[Method].push_back(Overridden);
1612 void ASTContext::getOverriddenMethods(
1614 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1617 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1618 Overridden.append(overridden_methods_begin(CXXMethod),
1619 overridden_methods_end(CXXMethod));
1623 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1627 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1628 Method->getOverriddenMethods(OverDecls);
1629 Overridden.append(OverDecls.begin(), OverDecls.end());
1632 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1633 assert(!Import->getNextLocalImport() &&
1634 "Import declaration already in the chain");
1635 assert(!Import->isFromASTFile() && "Non-local import declaration");
1636 if (!FirstLocalImport) {
1637 FirstLocalImport = Import;
1638 LastLocalImport = Import;
1642 LastLocalImport->setNextLocalImport(Import);
1643 LastLocalImport = Import;
1646 //===----------------------------------------------------------------------===//
1647 // Type Sizing and Analysis
1648 //===----------------------------------------------------------------------===//
1650 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1651 /// scalar floating point type.
1652 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1653 switch (T->castAs<BuiltinType>()->getKind()) {
1655 llvm_unreachable("Not a floating point type!");
1656 case BuiltinType::BFloat16:
1657 return Target->getBFloat16Format();
1658 case BuiltinType::Float16:
1659 case BuiltinType::Half:
1660 return Target->getHalfFormat();
1661 case BuiltinType::Float: return Target->getFloatFormat();
1662 case BuiltinType::Double: return Target->getDoubleFormat();
1663 case BuiltinType::LongDouble:
1664 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1665 return AuxTarget->getLongDoubleFormat();
1666 return Target->getLongDoubleFormat();
1667 case BuiltinType::Float128:
1668 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1669 return AuxTarget->getFloat128Format();
1670 return Target->getFloat128Format();
1674 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1675 unsigned Align = Target->getCharWidth();
1677 bool UseAlignAttrOnly = false;
1678 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1679 Align = AlignFromAttr;
1681 // __attribute__((aligned)) can increase or decrease alignment
1682 // *except* on a struct or struct member, where it only increases
1683 // alignment unless 'packed' is also specified.
1685 // It is an error for alignas to decrease alignment, so we can
1686 // ignore that possibility; Sema should diagnose it.
1687 if (isa<FieldDecl>(D)) {
1688 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1689 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1691 UseAlignAttrOnly = true;
1694 else if (isa<FieldDecl>(D))
1696 D->hasAttr<PackedAttr>() ||
1697 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1699 // If we're using the align attribute only, just ignore everything
1700 // else about the declaration and its type.
1701 if (UseAlignAttrOnly) {
1703 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1704 QualType T = VD->getType();
1705 if (const auto *RT = T->getAs<ReferenceType>()) {
1707 T = RT->getPointeeType();
1709 T = getPointerType(RT->getPointeeType());
1711 QualType BaseT = getBaseElementType(T);
1712 if (T->isFunctionType())
1713 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1714 else if (!BaseT->isIncompleteType()) {
1715 // Adjust alignments of declarations with array type by the
1716 // large-array alignment on the target.
1717 if (const ArrayType *arrayType = getAsArrayType(T)) {
1718 unsigned MinWidth = Target->getLargeArrayMinWidth();
1719 if (!ForAlignof && MinWidth) {
1720 if (isa<VariableArrayType>(arrayType))
1721 Align = std::max(Align, Target->getLargeArrayAlign());
1722 else if (isa<ConstantArrayType>(arrayType) &&
1723 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1724 Align = std::max(Align, Target->getLargeArrayAlign());
1727 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1728 if (BaseT.getQualifiers().hasUnaligned())
1729 Align = Target->getCharWidth();
1730 if (const auto *VD = dyn_cast<VarDecl>(D)) {
1731 if (VD->hasGlobalStorage() && !ForAlignof) {
1732 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1733 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1738 // Fields can be subject to extra alignment constraints, like if
1739 // the field is packed, the struct is packed, or the struct has a
1740 // a max-field-alignment constraint (#pragma pack). So calculate
1741 // the actual alignment of the field within the struct, and then
1742 // (as we're expected to) constrain that by the alignment of the type.
1743 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1744 const RecordDecl *Parent = Field->getParent();
1745 // We can only produce a sensible answer if the record is valid.
1746 if (!Parent->isInvalidDecl()) {
1747 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1749 // Start with the record's overall alignment.
1750 unsigned FieldAlign = toBits(Layout.getAlignment());
1752 // Use the GCD of that and the offset within the record.
1753 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1755 // Alignment is always a power of 2, so the GCD will be a power of 2,
1756 // which means we get to do this crazy thing instead of Euclid's.
1757 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1758 if (LowBitOfOffset < FieldAlign)
1759 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1762 Align = std::min(Align, FieldAlign);
1767 return toCharUnitsFromBits(Align);
1770 CharUnits ASTContext::getExnObjectAlignment() const {
1771 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1774 // getTypeInfoDataSizeInChars - Return the size of a type, in
1775 // chars. If the type is a record, its data size is returned. This is
1776 // the size of the memcpy that's performed when assigning this type
1777 // using a trivial copy/move assignment operator.
1778 std::pair<CharUnits, CharUnits>
1779 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1780 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1782 // In C++, objects can sometimes be allocated into the tail padding
1783 // of a base-class subobject. We decide whether that's possible
1784 // during class layout, so here we can just trust the layout results.
1785 if (getLangOpts().CPlusPlus) {
1786 if (const auto *RT = T->getAs<RecordType>()) {
1787 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1788 sizeAndAlign.first = layout.getDataSize();
1792 return sizeAndAlign;
1795 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1796 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1797 std::pair<CharUnits, CharUnits>
1798 static getConstantArrayInfoInChars(const ASTContext &Context,
1799 const ConstantArrayType *CAT) {
1800 std::pair<CharUnits, CharUnits> EltInfo =
1801 Context.getTypeInfoInChars(CAT->getElementType());
1802 uint64_t Size = CAT->getSize().getZExtValue();
1803 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1804 (uint64_t)(-1)/Size) &&
1805 "Overflow in array type char size evaluation");
1806 uint64_t Width = EltInfo.first.getQuantity() * Size;
1807 unsigned Align = EltInfo.second.getQuantity();
1808 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1809 Context.getTargetInfo().getPointerWidth(0) == 64)
1810 Width = llvm::alignTo(Width, Align);
1811 return std::make_pair(CharUnits::fromQuantity(Width),
1812 CharUnits::fromQuantity(Align));
1815 std::pair<CharUnits, CharUnits>
1816 ASTContext::getTypeInfoInChars(const Type *T) const {
1817 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1818 return getConstantArrayInfoInChars(*this, CAT);
1819 TypeInfo Info = getTypeInfo(T);
1820 return std::make_pair(toCharUnitsFromBits(Info.Width),
1821 toCharUnitsFromBits(Info.Align));
1824 std::pair<CharUnits, CharUnits>
1825 ASTContext::getTypeInfoInChars(QualType T) const {
1826 return getTypeInfoInChars(T.getTypePtr());
1829 bool ASTContext::isAlignmentRequired(const Type *T) const {
1830 return getTypeInfo(T).AlignIsRequired;
1833 bool ASTContext::isAlignmentRequired(QualType T) const {
1834 return isAlignmentRequired(T.getTypePtr());
1837 unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1838 // An alignment on a typedef overrides anything else.
1839 if (const auto *TT = T->getAs<TypedefType>())
1840 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1843 // If we have an (array of) complete type, we're done.
1844 T = getBaseElementType(T);
1845 if (!T->isIncompleteType())
1846 return getTypeAlign(T);
1848 // If we had an array type, its element type might be a typedef
1849 // type with an alignment attribute.
1850 if (const auto *TT = T->getAs<TypedefType>())
1851 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1854 // Otherwise, see if the declaration of the type had an attribute.
1855 if (const auto *TT = T->getAs<TagType>())
1856 return TT->getDecl()->getMaxAlignment();
1861 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1862 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1863 if (I != MemoizedTypeInfo.end())
1866 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1867 TypeInfo TI = getTypeInfoImpl(T);
1868 MemoizedTypeInfo[T] = TI;
1872 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1873 /// method does not work on incomplete types.
1875 /// FIXME: Pointers into different addr spaces could have different sizes and
1876 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1877 /// should take a QualType, &c.
1878 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1881 bool AlignIsRequired = false;
1883 switch (T->getTypeClass()) {
1884 #define TYPE(Class, Base)
1885 #define ABSTRACT_TYPE(Class, Base)
1886 #define NON_CANONICAL_TYPE(Class, Base)
1887 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1888 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1890 assert(!T->isDependentType() && "should not see dependent types here"); \
1891 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1892 #include "clang/AST/TypeNodes.inc"
1893 llvm_unreachable("Should not see dependent types");
1895 case Type::FunctionNoProto:
1896 case Type::FunctionProto:
1897 // GCC extension: alignof(function) = 32 bits
1902 case Type::IncompleteArray:
1903 case Type::VariableArray:
1904 case Type::ConstantArray: {
1905 // Model non-constant sized arrays as size zero, but track the alignment.
1907 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1908 Size = CAT->getSize().getZExtValue();
1910 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1911 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1912 "Overflow in array type bit size evaluation");
1913 Width = EltInfo.Width * Size;
1914 Align = EltInfo.Align;
1915 AlignIsRequired = EltInfo.AlignIsRequired;
1916 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1917 getTargetInfo().getPointerWidth(0) == 64)
1918 Width = llvm::alignTo(Width, Align);
1922 case Type::ExtVector:
1923 case Type::Vector: {
1924 const auto *VT = cast<VectorType>(T);
1925 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1926 Width = EltInfo.Width * VT->getNumElements();
1928 // If the alignment is not a power of 2, round up to the next power of 2.
1929 // This happens for non-power-of-2 length vectors.
1930 if (Align & (Align-1)) {
1931 Align = llvm::NextPowerOf2(Align);
1932 Width = llvm::alignTo(Width, Align);
1934 // Adjust the alignment based on the target max.
1935 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1936 if (TargetVectorAlign && TargetVectorAlign < Align)
1937 Align = TargetVectorAlign;
1941 case Type::ConstantMatrix: {
1942 const auto *MT = cast<ConstantMatrixType>(T);
1943 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1944 // The internal layout of a matrix value is implementation defined.
1945 // Initially be ABI compatible with arrays with respect to alignment and
1947 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1948 Align = ElementInfo.Align;
1953 switch (cast<BuiltinType>(T)->getKind()) {
1954 default: llvm_unreachable("Unknown builtin type!");
1955 case BuiltinType::Void:
1956 // GCC extension: alignof(void) = 8 bits.
1960 case BuiltinType::Bool:
1961 Width = Target->getBoolWidth();
1962 Align = Target->getBoolAlign();
1964 case BuiltinType::Char_S:
1965 case BuiltinType::Char_U:
1966 case BuiltinType::UChar:
1967 case BuiltinType::SChar:
1968 case BuiltinType::Char8:
1969 Width = Target->getCharWidth();
1970 Align = Target->getCharAlign();
1972 case BuiltinType::WChar_S:
1973 case BuiltinType::WChar_U:
1974 Width = Target->getWCharWidth();
1975 Align = Target->getWCharAlign();
1977 case BuiltinType::Char16:
1978 Width = Target->getChar16Width();
1979 Align = Target->getChar16Align();
1981 case BuiltinType::Char32:
1982 Width = Target->getChar32Width();
1983 Align = Target->getChar32Align();
1985 case BuiltinType::UShort:
1986 case BuiltinType::Short:
1987 Width = Target->getShortWidth();
1988 Align = Target->getShortAlign();
1990 case BuiltinType::UInt:
1991 case BuiltinType::Int:
1992 Width = Target->getIntWidth();
1993 Align = Target->getIntAlign();
1995 case BuiltinType::ULong:
1996 case BuiltinType::Long:
1997 Width = Target->getLongWidth();
1998 Align = Target->getLongAlign();
2000 case BuiltinType::ULongLong:
2001 case BuiltinType::LongLong:
2002 Width = Target->getLongLongWidth();
2003 Align = Target->getLongLongAlign();
2005 case BuiltinType::Int128:
2006 case BuiltinType::UInt128:
2008 Align = 128; // int128_t is 128-bit aligned on all targets.
2010 case BuiltinType::ShortAccum:
2011 case BuiltinType::UShortAccum:
2012 case BuiltinType::SatShortAccum:
2013 case BuiltinType::SatUShortAccum:
2014 Width = Target->getShortAccumWidth();
2015 Align = Target->getShortAccumAlign();
2017 case BuiltinType::Accum:
2018 case BuiltinType::UAccum:
2019 case BuiltinType::SatAccum:
2020 case BuiltinType::SatUAccum:
2021 Width = Target->getAccumWidth();
2022 Align = Target->getAccumAlign();
2024 case BuiltinType::LongAccum:
2025 case BuiltinType::ULongAccum:
2026 case BuiltinType::SatLongAccum:
2027 case BuiltinType::SatULongAccum:
2028 Width = Target->getLongAccumWidth();
2029 Align = Target->getLongAccumAlign();
2031 case BuiltinType::ShortFract:
2032 case BuiltinType::UShortFract:
2033 case BuiltinType::SatShortFract:
2034 case BuiltinType::SatUShortFract:
2035 Width = Target->getShortFractWidth();
2036 Align = Target->getShortFractAlign();
2038 case BuiltinType::Fract:
2039 case BuiltinType::UFract:
2040 case BuiltinType::SatFract:
2041 case BuiltinType::SatUFract:
2042 Width = Target->getFractWidth();
2043 Align = Target->getFractAlign();
2045 case BuiltinType::LongFract:
2046 case BuiltinType::ULongFract:
2047 case BuiltinType::SatLongFract:
2048 case BuiltinType::SatULongFract:
2049 Width = Target->getLongFractWidth();
2050 Align = Target->getLongFractAlign();
2052 case BuiltinType::BFloat16:
2053 Width = Target->getBFloat16Width();
2054 Align = Target->getBFloat16Align();
2056 case BuiltinType::Float16:
2057 case BuiltinType::Half:
2058 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2059 !getLangOpts().OpenMPIsDevice) {
2060 Width = Target->getHalfWidth();
2061 Align = Target->getHalfAlign();
2063 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2064 "Expected OpenMP device compilation.");
2065 Width = AuxTarget->getHalfWidth();
2066 Align = AuxTarget->getHalfAlign();
2069 case BuiltinType::Float:
2070 Width = Target->getFloatWidth();
2071 Align = Target->getFloatAlign();
2073 case BuiltinType::Double:
2074 Width = Target->getDoubleWidth();
2075 Align = Target->getDoubleAlign();
2077 case BuiltinType::LongDouble:
2078 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2079 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2080 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2081 Width = AuxTarget->getLongDoubleWidth();
2082 Align = AuxTarget->getLongDoubleAlign();
2084 Width = Target->getLongDoubleWidth();
2085 Align = Target->getLongDoubleAlign();
2088 case BuiltinType::Float128:
2089 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2090 !getLangOpts().OpenMPIsDevice) {
2091 Width = Target->getFloat128Width();
2092 Align = Target->getFloat128Align();
2094 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2095 "Expected OpenMP device compilation.");
2096 Width = AuxTarget->getFloat128Width();
2097 Align = AuxTarget->getFloat128Align();
2100 case BuiltinType::NullPtr:
2101 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2102 Align = Target->getPointerAlign(0); // == sizeof(void*)
2104 case BuiltinType::ObjCId:
2105 case BuiltinType::ObjCClass:
2106 case BuiltinType::ObjCSel:
2107 Width = Target->getPointerWidth(0);
2108 Align = Target->getPointerAlign(0);
2110 case BuiltinType::OCLSampler:
2111 case BuiltinType::OCLEvent:
2112 case BuiltinType::OCLClkEvent:
2113 case BuiltinType::OCLQueue:
2114 case BuiltinType::OCLReserveID:
2115 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2116 case BuiltinType::Id:
2117 #include "clang/Basic/OpenCLImageTypes.def"
2118 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2119 case BuiltinType::Id:
2120 #include "clang/Basic/OpenCLExtensionTypes.def"
2121 AS = getTargetAddressSpace(
2122 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2123 Width = Target->getPointerWidth(AS);
2124 Align = Target->getPointerAlign(AS);
2126 // The SVE types are effectively target-specific. The length of an
2127 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2128 // of 128 bits. There is one predicate bit for each vector byte, so the
2129 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2131 // Because the length is only known at runtime, we use a dummy value
2132 // of 0 for the static length. The alignment values are those defined
2133 // by the Procedure Call Standard for the Arm Architecture.
2134 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
2135 IsSigned, IsFP, IsBF) \
2136 case BuiltinType::Id: \
2140 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
2141 case BuiltinType::Id: \
2145 #include "clang/Basic/AArch64SVEACLETypes.def"
2148 case Type::ObjCObjectPointer:
2149 Width = Target->getPointerWidth(0);
2150 Align = Target->getPointerAlign(0);
2152 case Type::BlockPointer:
2153 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
2154 Width = Target->getPointerWidth(AS);
2155 Align = Target->getPointerAlign(AS);
2157 case Type::LValueReference:
2158 case Type::RValueReference:
2159 // alignof and sizeof should never enter this code path here, so we go
2160 // the pointer route.
2161 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
2162 Width = Target->getPointerWidth(AS);
2163 Align = Target->getPointerAlign(AS);
2166 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
2167 Width = Target->getPointerWidth(AS);
2168 Align = Target->getPointerAlign(AS);
2170 case Type::MemberPointer: {
2171 const auto *MPT = cast<MemberPointerType>(T);
2172 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2177 case Type::Complex: {
2178 // Complex types have the same alignment as their elements, but twice the
2180 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2181 Width = EltInfo.Width * 2;
2182 Align = EltInfo.Align;
2185 case Type::ObjCObject:
2186 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2187 case Type::Adjusted:
2189 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2190 case Type::ObjCInterface: {
2191 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2192 if (ObjCI->getDecl()->isInvalidDecl()) {
2197 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2198 Width = toBits(Layout.getSize());
2199 Align = toBits(Layout.getAlignment());
2202 case Type::ExtInt: {
2203 const auto *EIT = cast<ExtIntType>(T);
2205 std::min(static_cast<unsigned>(std::max(
2206 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
2207 Target->getLongLongAlign());
2208 Width = llvm::alignTo(EIT->getNumBits(), Align);
2213 const auto *TT = cast<TagType>(T);
2215 if (TT->getDecl()->isInvalidDecl()) {
2221 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2222 const EnumDecl *ED = ET->getDecl();
2224 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2225 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2226 Info.Align = AttrAlign;
2227 Info.AlignIsRequired = true;
2232 const auto *RT = cast<RecordType>(TT);
2233 const RecordDecl *RD = RT->getDecl();
2234 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2235 Width = toBits(Layout.getSize());
2236 Align = toBits(Layout.getAlignment());
2237 AlignIsRequired = RD->hasAttr<AlignedAttr>();
2241 case Type::SubstTemplateTypeParm:
2242 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2243 getReplacementType().getTypePtr());
2246 case Type::DeducedTemplateSpecialization: {
2247 const auto *A = cast<DeducedType>(T);
2248 assert(!A->getDeducedType().isNull() &&
2249 "cannot request the size of an undeduced or dependent auto type");
2250 return getTypeInfo(A->getDeducedType().getTypePtr());
2254 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2256 case Type::MacroQualified:
2258 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2260 case Type::ObjCTypeParam:
2261 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2263 case Type::Typedef: {
2264 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2265 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2266 // If the typedef has an aligned attribute on it, it overrides any computed
2267 // alignment we have. This violates the GCC documentation (which says that
2268 // attribute(aligned) can only round up) but matches its implementation.
2269 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2271 AlignIsRequired = true;
2274 AlignIsRequired = Info.AlignIsRequired;
2280 case Type::Elaborated:
2281 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2283 case Type::Attributed:
2285 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2287 case Type::Atomic: {
2288 // Start with the base type information.
2289 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2294 // An otherwise zero-sized type should still generate an
2295 // atomic operation.
2296 Width = Target->getCharWidth();
2298 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2299 // If the size of the type doesn't exceed the platform's max
2300 // atomic promotion width, make the size and alignment more
2301 // favorable to atomic operations:
2303 // Round the size up to a power of 2.
2304 if (!llvm::isPowerOf2_64(Width))
2305 Width = llvm::NextPowerOf2(Width);
2307 // Set the alignment equal to the size.
2308 Align = static_cast<unsigned>(Width);
2314 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2315 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2319 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2320 return TypeInfo(Width, Align, AlignIsRequired);
2323 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2324 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2325 if (I != MemoizedUnadjustedAlign.end())
2328 unsigned UnadjustedAlign;
2329 if (const auto *RT = T->getAs<RecordType>()) {
2330 const RecordDecl *RD = RT->getDecl();
2331 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2332 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2333 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2334 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2335 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2337 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2340 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2341 return UnadjustedAlign;
2344 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2345 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2346 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2347 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2348 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2349 getTargetInfo().getABI() == "elfv1-qpx" &&
2350 T->isSpecificBuiltinType(BuiltinType::Double))
2355 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2356 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2357 return CharUnits::fromQuantity(BitSize / getCharWidth());
2360 /// toBits - Convert a size in characters to a size in characters.
2361 int64_t ASTContext::toBits(CharUnits CharSize) const {
2362 return CharSize.getQuantity() * getCharWidth();
2365 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2366 /// This method does not work on incomplete types.
2367 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2368 return getTypeInfoInChars(T).first;
2370 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2371 return getTypeInfoInChars(T).first;
2374 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2375 /// characters. This method does not work on incomplete types.
2376 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2377 return toCharUnitsFromBits(getTypeAlign(T));
2379 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2380 return toCharUnitsFromBits(getTypeAlign(T));
2383 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2384 /// type, in characters, before alignment adustments. This method does
2385 /// not work on incomplete types.
2386 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2387 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2389 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2390 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2393 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2394 /// type for the current target in bits. This can be different than the ABI
2395 /// alignment in cases where it is beneficial for performance to overalign
2397 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2398 TypeInfo TI = getTypeInfo(T);
2399 unsigned ABIAlign = TI.Align;
2401 T = T->getBaseElementTypeUnsafe();
2403 // The preferred alignment of member pointers is that of a pointer.
2404 if (T->isMemberPointerType())
2405 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2407 if (!Target->allowsLargerPreferedTypeAlignment())
2410 // Double and long long should be naturally aligned if possible.
2411 if (const auto *CT = T->getAs<ComplexType>())
2412 T = CT->getElementType().getTypePtr();
2413 if (const auto *ET = T->getAs<EnumType>())
2414 T = ET->getDecl()->getIntegerType().getTypePtr();
2415 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2416 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2417 T->isSpecificBuiltinType(BuiltinType::ULongLong))
2418 // Don't increase the alignment if an alignment attribute was specified on a
2419 // typedef declaration.
2420 if (!TI.AlignIsRequired)
2421 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2426 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2427 /// for __attribute__((aligned)) on this target, to be used if no alignment
2428 /// value is specified.
2429 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2430 return getTargetInfo().getDefaultAlignForAttributeAligned();
2433 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2434 /// to a global variable of the specified type.
2435 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2436 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2437 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
2440 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2441 /// should be given to a global variable of the specified type.
2442 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2443 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2446 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2447 CharUnits Offset = CharUnits::Zero();
2448 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2449 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2450 Offset += Layout->getBaseClassOffset(Base);
2451 Layout = &getASTRecordLayout(Base);
2456 /// DeepCollectObjCIvars -
2457 /// This routine first collects all declared, but not synthesized, ivars in
2458 /// super class and then collects all ivars, including those synthesized for
2459 /// current class. This routine is used for implementation of current class
2460 /// when all ivars, declared and synthesized are known.
2461 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2463 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2464 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2465 DeepCollectObjCIvars(SuperClass, false, Ivars);
2467 for (const auto *I : OI->ivars())
2470 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2471 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2472 Iv= Iv->getNextIvar())
2473 Ivars.push_back(Iv);
2477 /// CollectInheritedProtocols - Collect all protocols in current class and
2478 /// those inherited by it.
2479 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2480 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2481 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2482 // We can use protocol_iterator here instead of
2483 // all_referenced_protocol_iterator since we are walking all categories.
2484 for (auto *Proto : OI->all_referenced_protocols()) {
2485 CollectInheritedProtocols(Proto, Protocols);
2488 // Categories of this Interface.
2489 for (const auto *Cat : OI->visible_categories())
2490 CollectInheritedProtocols(Cat, Protocols);
2492 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2494 CollectInheritedProtocols(SD, Protocols);
2495 SD = SD->getSuperClass();
2497 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2498 for (auto *Proto : OC->protocols()) {
2499 CollectInheritedProtocols(Proto, Protocols);
2501 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2502 // Insert the protocol.
2503 if (!Protocols.insert(
2504 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2507 for (auto *Proto : OP->protocols())
2508 CollectInheritedProtocols(Proto, Protocols);
2512 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2513 const RecordDecl *RD) {
2514 assert(RD->isUnion() && "Must be union type");
2515 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2517 for (const auto *Field : RD->fields()) {
2518 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2520 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2521 if (FieldSize != UnionSize)
2524 return !RD->field_empty();
2527 static bool isStructEmpty(QualType Ty) {
2528 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2530 if (!RD->field_empty())
2533 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2534 return ClassDecl->isEmpty();
2539 static llvm::Optional<int64_t>
2540 structHasUniqueObjectRepresentations(const ASTContext &Context,
2541 const RecordDecl *RD) {
2542 assert(!RD->isUnion() && "Must be struct/class type");
2543 const auto &Layout = Context.getASTRecordLayout(RD);
2545 int64_t CurOffsetInBits = 0;
2546 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2547 if (ClassDecl->isDynamicClass())
2550 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2551 for (const auto &Base : ClassDecl->bases()) {
2552 // Empty types can be inherited from, and non-empty types can potentially
2553 // have tail padding, so just make sure there isn't an error.
2554 if (!isStructEmpty(Base.getType())) {
2555 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2556 Context, Base.getType()->castAs<RecordType>()->getDecl());
2559 Bases.emplace_back(Base.getType(), Size.getValue());
2563 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2564 const std::pair<QualType, int64_t> &R) {
2565 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2566 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2569 for (const auto &Base : Bases) {
2570 int64_t BaseOffset = Context.toBits(
2571 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2572 int64_t BaseSize = Base.second;
2573 if (BaseOffset != CurOffsetInBits)
2575 CurOffsetInBits = BaseOffset + BaseSize;
2579 for (const auto *Field : RD->fields()) {
2580 if (!Field->getType()->isReferenceType() &&
2581 !Context.hasUniqueObjectRepresentations(Field->getType()))
2584 int64_t FieldSizeInBits =
2585 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2586 if (Field->isBitField()) {
2587 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2589 if (BitfieldSize > FieldSizeInBits)
2591 FieldSizeInBits = BitfieldSize;
2594 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2596 if (FieldOffsetInBits != CurOffsetInBits)
2599 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2602 return CurOffsetInBits;
2605 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2606 // C++17 [meta.unary.prop]:
2607 // The predicate condition for a template specialization
2608 // has_unique_object_representations<T> shall be
2609 // satisfied if and only if:
2610 // (9.1) - T is trivially copyable, and
2611 // (9.2) - any two objects of type T with the same value have the same
2612 // object representation, where two objects
2613 // of array or non-union class type are considered to have the same value
2614 // if their respective sequences of
2615 // direct subobjects have the same values, and two objects of union type
2616 // are considered to have the same
2617 // value if they have the same active member and the corresponding members
2618 // have the same value.
2619 // The set of scalar types for which this condition holds is
2620 // implementation-defined. [ Note: If a type has padding
2621 // bits, the condition does not hold; otherwise, the condition holds true
2622 // for unsigned integral types. -- end note ]
2623 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2625 // Arrays are unique only if their element type is unique.
2626 if (Ty->isArrayType())
2627 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2629 // (9.1) - T is trivially copyable...
2630 if (!Ty.isTriviallyCopyableType(*this))
2633 // All integrals and enums are unique.
2634 if (Ty->isIntegralOrEnumerationType())
2637 // All other pointers are unique.
2638 if (Ty->isPointerType())
2641 if (Ty->isMemberPointerType()) {
2642 const auto *MPT = Ty->getAs<MemberPointerType>();
2643 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2646 if (Ty->isRecordType()) {
2647 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2649 if (Record->isInvalidDecl())
2652 if (Record->isUnion())
2653 return unionHasUniqueObjectRepresentations(*this, Record);
2655 Optional<int64_t> StructSize =
2656 structHasUniqueObjectRepresentations(*this, Record);
2658 return StructSize &&
2659 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2662 // FIXME: More cases to handle here (list by rsmith):
2663 // vectors (careful about, eg, vector of 3 foo)
2664 // _Complex int and friends
2666 // Obj-C block pointers
2667 // Obj-C object pointers
2668 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2669 // clk_event_t, queue_t, reserve_id_t)
2670 // There're also Obj-C class types and the Obj-C selector type, but I think it
2671 // makes sense for those to return false here.
2676 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2678 // Count ivars declared in class extension.
2679 for (const auto *Ext : OI->known_extensions())
2680 count += Ext->ivar_size();
2682 // Count ivar defined in this class's implementation. This
2683 // includes synthesized ivars.
2684 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2685 count += ImplDecl->ivar_size();
2690 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2694 // nullptr_t is always treated as null.
2695 if (E->getType()->isNullPtrType()) return true;
2697 if (E->getType()->isAnyPointerType() &&
2698 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2699 Expr::NPC_ValueDependentIsNull))
2702 // Unfortunately, __null has type 'int'.
2703 if (isa<GNUNullExpr>(E)) return true;
2708 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2710 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2711 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2712 I = ObjCImpls.find(D);
2713 if (I != ObjCImpls.end())
2714 return cast<ObjCImplementationDecl>(I->second);
2718 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2720 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2721 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2722 I = ObjCImpls.find(D);
2723 if (I != ObjCImpls.end())
2724 return cast<ObjCCategoryImplDecl>(I->second);
2728 /// Set the implementation of ObjCInterfaceDecl.
2729 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2730 ObjCImplementationDecl *ImplD) {
2731 assert(IFaceD && ImplD && "Passed null params");
2732 ObjCImpls[IFaceD] = ImplD;
2735 /// Set the implementation of ObjCCategoryDecl.
2736 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2737 ObjCCategoryImplDecl *ImplD) {
2738 assert(CatD && ImplD && "Passed null params");
2739 ObjCImpls[CatD] = ImplD;
2742 const ObjCMethodDecl *
2743 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2744 return ObjCMethodRedecls.lookup(MD);
2747 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2748 const ObjCMethodDecl *Redecl) {
2749 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2750 ObjCMethodRedecls[MD] = Redecl;
2753 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2754 const NamedDecl *ND) const {
2755 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2757 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2758 return CD->getClassInterface();
2759 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2760 return IMD->getClassInterface();
2765 /// Get the copy initialization expression of VarDecl, or nullptr if
2767 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2768 assert(VD && "Passed null params");
2769 assert(VD->hasAttr<BlocksAttr>() &&
2770 "getBlockVarCopyInits - not __block var");
2771 auto I = BlockVarCopyInits.find(VD);
2772 if (I != BlockVarCopyInits.end())
2774 return {nullptr, false};
2777 /// Set the copy initialization expression of a block var decl.
2778 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2780 assert(VD && CopyExpr && "Passed null params");
2781 assert(VD->hasAttr<BlocksAttr>() &&
2782 "setBlockVarCopyInits - not __block var");
2783 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2786 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2787 unsigned DataSize) const {
2789 DataSize = TypeLoc::getFullDataSizeForType(T);
2791 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2792 "incorrect data size provided to CreateTypeSourceInfo!");
2795 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2796 new (TInfo) TypeSourceInfo(T);
2800 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2801 SourceLocation L) const {
2802 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2803 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2807 const ASTRecordLayout &
2808 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2809 return getObjCLayout(D, nullptr);
2812 const ASTRecordLayout &
2813 ASTContext::getASTObjCImplementationLayout(
2814 const ObjCImplementationDecl *D) const {
2815 return getObjCLayout(D->getClassInterface(), D);
2818 //===----------------------------------------------------------------------===//
2819 // Type creation/memoization methods
2820 //===----------------------------------------------------------------------===//
2823 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2824 unsigned fastQuals = quals.getFastQualifiers();
2825 quals.removeFastQualifiers();
2827 // Check if we've already instantiated this type.
2828 llvm::FoldingSetNodeID ID;
2829 ExtQuals::Profile(ID, baseType, quals);
2830 void *insertPos = nullptr;
2831 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2832 assert(eq->getQualifiers() == quals);
2833 return QualType(eq, fastQuals);
2836 // If the base type is not canonical, make the appropriate canonical type.
2838 if (!baseType->isCanonicalUnqualified()) {
2839 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2840 canonSplit.Quals.addConsistentQualifiers(quals);
2841 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2843 // Re-find the insert position.
2844 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2847 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2848 ExtQualNodes.InsertNode(eq, insertPos);
2849 return QualType(eq, fastQuals);
2852 QualType ASTContext::getAddrSpaceQualType(QualType T,
2853 LangAS AddressSpace) const {
2854 QualType CanT = getCanonicalType(T);
2855 if (CanT.getAddressSpace() == AddressSpace)
2858 // If we are composing extended qualifiers together, merge together
2859 // into one ExtQuals node.
2860 QualifierCollector Quals;
2861 const Type *TypeNode = Quals.strip(T);
2863 // If this type already has an address space specified, it cannot get
2865 assert(!Quals.hasAddressSpace() &&
2866 "Type cannot be in multiple addr spaces!");
2867 Quals.addAddressSpace(AddressSpace);
2869 return getExtQualType(TypeNode, Quals);
2872 QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2873 // If we are composing extended qualifiers together, merge together
2874 // into one ExtQuals node.
2875 QualifierCollector Quals;
2876 const Type *TypeNode = Quals.strip(T);
2878 // If the qualifier doesn't have an address space just return it.
2879 if (!Quals.hasAddressSpace())
2882 Quals.removeAddressSpace();
2884 // Removal of the address space can mean there are no longer any
2885 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2887 if (Quals.hasNonFastQualifiers())
2888 return getExtQualType(TypeNode, Quals);
2890 return QualType(TypeNode, Quals.getFastQualifiers());
2893 QualType ASTContext::getObjCGCQualType(QualType T,
2894 Qualifiers::GC GCAttr) const {
2895 QualType CanT = getCanonicalType(T);
2896 if (CanT.getObjCGCAttr() == GCAttr)
2899 if (const auto *ptr = T->getAs<PointerType>()) {
2900 QualType Pointee = ptr->getPointeeType();
2901 if (Pointee->isAnyPointerType()) {
2902 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2903 return getPointerType(ResultType);
2907 // If we are composing extended qualifiers together, merge together
2908 // into one ExtQuals node.
2909 QualifierCollector Quals;
2910 const Type *TypeNode = Quals.strip(T);
2912 // If this type already has an ObjCGC specified, it cannot get
2914 assert(!Quals.hasObjCGCAttr() &&
2915 "Type cannot have multiple ObjCGCs!");
2916 Quals.addObjCGCAttr(GCAttr);
2918 return getExtQualType(TypeNode, Quals);
2921 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
2922 if (const PointerType *Ptr = T->getAs<PointerType>()) {
2923 QualType Pointee = Ptr->getPointeeType();
2924 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
2925 return getPointerType(removeAddrSpaceQualType(Pointee));
2931 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2932 FunctionType::ExtInfo Info) {
2933 if (T->getExtInfo() == Info)
2937 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2938 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2940 const auto *FPT = cast<FunctionProtoType>(T);
2941 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2943 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2946 return cast<FunctionType>(Result.getTypePtr());
2949 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2950 QualType ResultType) {
2951 FD = FD->getMostRecentDecl();
2953 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
2954 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2955 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2956 if (FunctionDecl *Next = FD->getPreviousDecl())
2961 if (ASTMutationListener *L = getASTMutationListener())
2962 L->DeducedReturnType(FD, ResultType);
2965 /// Get a function type and produce the equivalent function type with the
2966 /// specified exception specification. Type sugar that can be present on a
2967 /// declaration of a function with an exception specification is permitted
2968 /// and preserved. Other type sugar (for instance, typedefs) is not.
2969 QualType ASTContext::getFunctionTypeWithExceptionSpec(
2970 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
2971 // Might have some parens.
2972 if (const auto *PT = dyn_cast<ParenType>(Orig))
2973 return getParenType(
2974 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
2976 // Might be wrapped in a macro qualified type.
2977 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2978 return getMacroQualifiedType(
2979 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2980 MQT->getMacroIdentifier());
2982 // Might have a calling-convention attribute.
2983 if (const auto *AT = dyn_cast<AttributedType>(Orig))
2984 return getAttributedType(
2986 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2987 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
2989 // Anything else must be a function type. Rebuild it with the new exception
2991 const auto *Proto = Orig->castAs<FunctionProtoType>();
2992 return getFunctionType(
2993 Proto->getReturnType(), Proto->getParamTypes(),
2994 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2997 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2999 return hasSameType(T, U) ||
3000 (getLangOpts().CPlusPlus17 &&
3001 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3002 getFunctionTypeWithExceptionSpec(U, EST_None)));
3005 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3006 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3007 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3008 SmallVector<QualType, 16> Args(Proto->param_types());
3009 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3010 Args[i] = removePtrSizeAddrSpace(Args[i]);
3011 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3014 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3015 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3016 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3022 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3023 return hasSameType(T, U) ||
3024 hasSameType(getFunctionTypeWithoutPtrSizes(T),
3025 getFunctionTypeWithoutPtrSizes(U));
3028 void ASTContext::adjustExceptionSpec(
3029 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3033 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3034 FD->setType(Updated);
3039 // Update the type in the type source information too.
3040 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3041 // If the type and the type-as-written differ, we may need to update
3042 // the type-as-written too.
3043 if (TSInfo->getType() != FD->getType())
3044 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3046 // FIXME: When we get proper type location information for exceptions,
3047 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3048 // up the TypeSourceInfo;
3049 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3050 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3051 "TypeLoc size mismatch from updating exception specification");
3052 TSInfo->overrideType(Updated);
3056 /// getComplexType - Return the uniqued reference to the type for a complex
3057 /// number with the specified element type.
3058 QualType ASTContext::getComplexType(QualType T) const {
3059 // Unique pointers, to guarantee there is only one pointer of a particular
3061 llvm::FoldingSetNodeID ID;
3062 ComplexType::Profile(ID, T);
3064 void *InsertPos = nullptr;
3065 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3066 return QualType(CT, 0);
3068 // If the pointee type isn't canonical, this won't be a canonical type either,
3069 // so fill in the canonical type field.
3071 if (!T.isCanonical()) {
3072 Canonical = getComplexType(getCanonicalType(T));
3074 // Get the new insert position for the node we care about.
3075 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3076 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3078 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
3079 Types.push_back(New);
3080 ComplexTypes.InsertNode(New, InsertPos);
3081 return QualType(New, 0);
3084 /// getPointerType - Return the uniqued reference to the type for a pointer to
3085 /// the specified type.
3086 QualType ASTContext::getPointerType(QualType T) const {
3087 // Unique pointers, to guarantee there is only one pointer of a particular
3089 llvm::FoldingSetNodeID ID;
3090 PointerType::Profile(ID, T);
3092 void *InsertPos = nullptr;
3093 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3094 return QualType(PT, 0);
3096 // If the pointee type isn't canonical, this won't be a canonical type either,
3097 // so fill in the canonical type field.
3099 if (!T.isCanonical()) {
3100 Canonical = getPointerType(getCanonicalType(T));
3102 // Get the new insert position for the node we care about.
3103 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3104 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3106 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3107 Types.push_back(New);
3108 PointerTypes.InsertNode(New, InsertPos);
3109 return QualType(New, 0);
3112 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3113 llvm::FoldingSetNodeID ID;
3114 AdjustedType::Profile(ID, Orig, New);
3115 void *InsertPos = nullptr;
3116 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3118 return QualType(AT, 0);
3120 QualType Canonical = getCanonicalType(New);
3122 // Get the new insert position for the node we care about.
3123 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3124 assert(!AT && "Shouldn't be in the map!");
3126 AT = new (*this, TypeAlignment)
3127 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3128 Types.push_back(AT);
3129 AdjustedTypes.InsertNode(AT, InsertPos);
3130 return QualType(AT, 0);
3133 QualType ASTContext::getDecayedType(QualType T) const {
3134 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3139 // A declaration of a parameter as "array of type" shall be
3140 // adjusted to "qualified pointer to type", where the type
3141 // qualifiers (if any) are those specified within the [ and ] of
3142 // the array type derivation.
3143 if (T->isArrayType())
3144 Decayed = getArrayDecayedType(T);
3147 // A declaration of a parameter as "function returning type"
3148 // shall be adjusted to "pointer to function returning type", as
3150 if (T->isFunctionType())
3151 Decayed = getPointerType(T);
3153 llvm::FoldingSetNodeID ID;
3154 AdjustedType::Profile(ID, T, Decayed);
3155 void *InsertPos = nullptr;
3156 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3158 return QualType(AT, 0);
3160 QualType Canonical = getCanonicalType(Decayed);
3162 // Get the new insert position for the node we care about.
3163 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3164 assert(!AT && "Shouldn't be in the map!");
3166 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3167 Types.push_back(AT);
3168 AdjustedTypes.InsertNode(AT, InsertPos);
3169 return QualType(AT, 0);
3172 /// getBlockPointerType - Return the uniqued reference to the type for
3173 /// a pointer to the specified block.
3174 QualType ASTContext::getBlockPointerType(QualType T) const {
3175 assert(T->isFunctionType() && "block of function types only");
3176 // Unique pointers, to guarantee there is only one block of a particular
3178 llvm::FoldingSetNodeID ID;
3179 BlockPointerType::Profile(ID, T);
3181 void *InsertPos = nullptr;
3182 if (BlockPointerType *PT =
3183 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3184 return QualType(PT, 0);
3186 // If the block pointee type isn't canonical, this won't be a canonical
3187 // type either so fill in the canonical type field.
3189 if (!T.isCanonical()) {
3190 Canonical = getBlockPointerType(getCanonicalType(T));
3192 // Get the new insert position for the node we care about.
3193 BlockPointerType *NewIP =
3194 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3195 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3197 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3198 Types.push_back(New);
3199 BlockPointerTypes.InsertNode(New, InsertPos);
3200 return QualType(New, 0);
3203 /// getLValueReferenceType - Return the uniqued reference to the type for an
3204 /// lvalue reference to the specified type.
3206 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3207 assert(getCanonicalType(T) != OverloadTy &&
3208 "Unresolved overloaded function type");
3210 // Unique pointers, to guarantee there is only one pointer of a particular
3212 llvm::FoldingSetNodeID ID;
3213 ReferenceType::Profile(ID, T, SpelledAsLValue);
3215 void *InsertPos = nullptr;
3216 if (LValueReferenceType *RT =
3217 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3218 return QualType(RT, 0);
3220 const auto *InnerRef = T->getAs<ReferenceType>();
3222 // If the referencee type isn't canonical, this won't be a canonical type
3223 // either, so fill in the canonical type field.
3225 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3226 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3227 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3229 // Get the new insert position for the node we care about.
3230 LValueReferenceType *NewIP =
3231 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3232 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3235 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3237 Types.push_back(New);
3238 LValueReferenceTypes.InsertNode(New, InsertPos);
3240 return QualType(New, 0);
3243 /// getRValueReferenceType - Return the uniqued reference to the type for an
3244 /// rvalue reference to the specified type.
3245 QualType ASTContext::getRValueReferenceType(QualType T) const {
3246 // Unique pointers, to guarantee there is only one pointer of a particular
3248 llvm::FoldingSetNodeID ID;
3249 ReferenceType::Profile(ID, T, false);
3251 void *InsertPos = nullptr;
3252 if (RValueReferenceType *RT =
3253 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3254 return QualType(RT, 0);
3256 const auto *InnerRef = T->getAs<ReferenceType>();
3258 // If the referencee type isn't canonical, this won't be a canonical type
3259 // either, so fill in the canonical type field.
3261 if (InnerRef || !T.isCanonical()) {
3262 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3263 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3265 // Get the new insert position for the node we care about.
3266 RValueReferenceType *NewIP =
3267 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3268 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3271 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3272 Types.push_back(New);
3273 RValueReferenceTypes.InsertNode(New, InsertPos);
3274 return QualType(New, 0);
3277 /// getMemberPointerType - Return the uniqued reference to the type for a
3278 /// member pointer to the specified type, in the specified class.
3279 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3280 // Unique pointers, to guarantee there is only one pointer of a particular
3282 llvm::FoldingSetNodeID ID;
3283 MemberPointerType::Profile(ID, T, Cls);
3285 void *InsertPos = nullptr;
3286 if (MemberPointerType *PT =
3287 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3288 return QualType(PT, 0);
3290 // If the pointee or class type isn't canonical, this won't be a canonical
3291 // type either, so fill in the canonical type field.
3293 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3294 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3296 // Get the new insert position for the node we care about.
3297 MemberPointerType *NewIP =
3298 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3299 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3301 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3302 Types.push_back(New);
3303 MemberPointerTypes.InsertNode(New, InsertPos);
3304 return QualType(New, 0);
3307 /// getConstantArrayType - Return the unique reference to the type for an
3308 /// array of the specified element type.
3309 QualType ASTContext::getConstantArrayType(QualType EltTy,
3310 const llvm::APInt &ArySizeIn,
3311 const Expr *SizeExpr,
3312 ArrayType::ArraySizeModifier ASM,
3313 unsigned IndexTypeQuals) const {
3314 assert((EltTy->isDependentType() ||
3315 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3316 "Constant array of VLAs is illegal!");
3318 // We only need the size as part of the type if it's instantiation-dependent.
3319 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3322 // Convert the array size into a canonical width matching the pointer size for
3324 llvm::APInt ArySize(ArySizeIn);
3325 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3327 llvm::FoldingSetNodeID ID;
3328 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3331 void *InsertPos = nullptr;
3332 if (ConstantArrayType *ATP =
3333 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3334 return QualType(ATP, 0);
3336 // If the element type isn't canonical or has qualifiers, or the array bound
3337 // is instantiation-dependent, this won't be a canonical type either, so fill
3338 // in the canonical type field.
3340 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3341 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3342 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3343 ASM, IndexTypeQuals);
3344 Canon = getQualifiedType(Canon, canonSplit.Quals);
3346 // Get the new insert position for the node we care about.
3347 ConstantArrayType *NewIP =
3348 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3349 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3352 void *Mem = Allocate(
3353 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3355 auto *New = new (Mem)
3356 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3357 ConstantArrayTypes.InsertNode(New, InsertPos);
3358 Types.push_back(New);
3359 return QualType(New, 0);
3362 /// getVariableArrayDecayedType - Turns the given type, which may be
3363 /// variably-modified, into the corresponding type with all the known
3364 /// sizes replaced with [*].
3365 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3366 // Vastly most common case.
3367 if (!type->isVariablyModifiedType()) return type;
3371 SplitQualType split = type.getSplitDesugaredType();
3372 const Type *ty = split.Ty;
3373 switch (ty->getTypeClass()) {
3374 #define TYPE(Class, Base)
3375 #define ABSTRACT_TYPE(Class, Base)
3376 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3377 #include "clang/AST/TypeNodes.inc"
3378 llvm_unreachable("didn't desugar past all non-canonical types?");
3380 // These types should never be variably-modified.
3384 case Type::DependentVector:
3385 case Type::ExtVector:
3386 case Type::DependentSizedExtVector:
3387 case Type::ConstantMatrix:
3388 case Type::DependentSizedMatrix:
3389 case Type::DependentAddressSpace:
3390 case Type::ObjCObject:
3391 case Type::ObjCInterface:
3392 case Type::ObjCObjectPointer:
3395 case Type::UnresolvedUsing:
3396 case Type::TypeOfExpr:
3398 case Type::Decltype:
3399 case Type::UnaryTransform:
3400 case Type::DependentName:
3401 case Type::InjectedClassName:
3402 case Type::TemplateSpecialization:
3403 case Type::DependentTemplateSpecialization:
3404 case Type::TemplateTypeParm:
3405 case Type::SubstTemplateTypeParmPack:
3407 case Type::DeducedTemplateSpecialization:
3408 case Type::PackExpansion:
3410 case Type::DependentExtInt:
3411 llvm_unreachable("type should never be variably-modified");
3413 // These types can be variably-modified but should never need to
3415 case Type::FunctionNoProto:
3416 case Type::FunctionProto:
3417 case Type::BlockPointer:
3418 case Type::MemberPointer:
3422 // These types can be variably-modified. All these modifications
3423 // preserve structure except as noted by comments.
3424 // TODO: if we ever care about optimizing VLAs, there are no-op
3425 // optimizations available here.
3427 result = getPointerType(getVariableArrayDecayedType(
3428 cast<PointerType>(ty)->getPointeeType()));
3431 case Type::LValueReference: {
3432 const auto *lv = cast<LValueReferenceType>(ty);
3433 result = getLValueReferenceType(
3434 getVariableArrayDecayedType(lv->getPointeeType()),
3435 lv->isSpelledAsLValue());
3439 case Type::RValueReference: {
3440 const auto *lv = cast<RValueReferenceType>(ty);
3441 result = getRValueReferenceType(
3442 getVariableArrayDecayedType(lv->getPointeeType()));
3446 case Type::Atomic: {
3447 const auto *at = cast<AtomicType>(ty);
3448 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3452 case Type::ConstantArray: {
3453 const auto *cat = cast<ConstantArrayType>(ty);
3454 result = getConstantArrayType(
3455 getVariableArrayDecayedType(cat->getElementType()),
3458 cat->getSizeModifier(),
3459 cat->getIndexTypeCVRQualifiers());
3463 case Type::DependentSizedArray: {
3464 const auto *dat = cast<DependentSizedArrayType>(ty);
3465 result = getDependentSizedArrayType(
3466 getVariableArrayDecayedType(dat->getElementType()),
3468 dat->getSizeModifier(),
3469 dat->getIndexTypeCVRQualifiers(),
3470 dat->getBracketsRange());
3474 // Turn incomplete types into [*] types.
3475 case Type::IncompleteArray: {
3476 const auto *iat = cast<IncompleteArrayType>(ty);
3477 result = getVariableArrayType(
3478 getVariableArrayDecayedType(iat->getElementType()),
3481 iat->getIndexTypeCVRQualifiers(),
3486 // Turn VLA types into [*] types.
3487 case Type::VariableArray: {
3488 const auto *vat = cast<VariableArrayType>(ty);
3489 result = getVariableArrayType(
3490 getVariableArrayDecayedType(vat->getElementType()),
3493 vat->getIndexTypeCVRQualifiers(),
3494 vat->getBracketsRange());
3499 // Apply the top-level qualifiers from the original.
3500 return getQualifiedType(result, split.Quals);
3503 /// getVariableArrayType - Returns a non-unique reference to the type for a
3504 /// variable array of the specified element type.
3505 QualType ASTContext::getVariableArrayType(QualType EltTy,
3507 ArrayType::ArraySizeModifier ASM,
3508 unsigned IndexTypeQuals,
3509 SourceRange Brackets) const {
3510 // Since we don't unique expressions, it isn't possible to unique VLA's
3511 // that have an expression provided for their size.
3514 // Be sure to pull qualifiers off the element type.
3515 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3516 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3517 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3518 IndexTypeQuals, Brackets);
3519 Canon = getQualifiedType(Canon, canonSplit.Quals);
3522 auto *New = new (*this, TypeAlignment)
3523 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3525 VariableArrayTypes.push_back(New);
3526 Types.push_back(New);
3527 return QualType(New, 0);
3530 /// getDependentSizedArrayType - Returns a non-unique reference to
3531 /// the type for a dependently-sized array of the specified element
3533 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3535 ArrayType::ArraySizeModifier ASM,
3536 unsigned elementTypeQuals,
3537 SourceRange brackets) const {
3538 assert((!numElements || numElements->isTypeDependent() ||
3539 numElements->isValueDependent()) &&
3540 "Size must be type- or value-dependent!");
3542 // Dependently-sized array types that do not have a specified number
3543 // of elements will have their sizes deduced from a dependent
3544 // initializer. We do no canonicalization here at all, which is okay
3545 // because they can't be used in most locations.
3548 = new (*this, TypeAlignment)
3549 DependentSizedArrayType(*this, elementType, QualType(),
3550 numElements, ASM, elementTypeQuals,
3552 Types.push_back(newType);
3553 return QualType(newType, 0);
3556 // Otherwise, we actually build a new type every time, but we
3557 // also build a canonical type.
3559 SplitQualType canonElementType = getCanonicalType(elementType).split();
3561 void *insertPos = nullptr;
3562 llvm::FoldingSetNodeID ID;
3563 DependentSizedArrayType::Profile(ID, *this,
3564 QualType(canonElementType.Ty, 0),
3565 ASM, elementTypeQuals, numElements);
3567 // Look for an existing type with these properties.
3568 DependentSizedArrayType *canonTy =
3569 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3571 // If we don't have one, build one.
3573 canonTy = new (*this, TypeAlignment)
3574 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3575 QualType(), numElements, ASM, elementTypeQuals,
3577 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3578 Types.push_back(canonTy);
3581 // Apply qualifiers from the element type to the array.
3582 QualType canon = getQualifiedType(QualType(canonTy,0),
3583 canonElementType.Quals);
3585 // If we didn't need extra canonicalization for the element type or the size
3586 // expression, then just use that as our result.
3587 if (QualType(canonElementType.Ty, 0) == elementType &&
3588 canonTy->getSizeExpr() == numElements)
3591 // Otherwise, we need to build a type which follows the spelling
3592 // of the element type.
3594 = new (*this, TypeAlignment)
3595 DependentSizedArrayType(*this, elementType, canon, numElements,
3596 ASM, elementTypeQuals, brackets);
3597 Types.push_back(sugaredType);
3598 return QualType(sugaredType, 0);
3601 QualType ASTContext::getIncompleteArrayType(QualType elementType,
3602 ArrayType::ArraySizeModifier ASM,
3603 unsigned elementTypeQuals) const {
3604 llvm::FoldingSetNodeID ID;
3605 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3607 void *insertPos = nullptr;
3608 if (IncompleteArrayType *iat =
3609 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3610 return QualType(iat, 0);
3612 // If the element type isn't canonical, this won't be a canonical type
3613 // either, so fill in the canonical type field. We also have to pull
3614 // qualifiers off the element type.
3617 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3618 SplitQualType canonSplit = getCanonicalType(elementType).split();
3619 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3620 ASM, elementTypeQuals);
3621 canon = getQualifiedType(canon, canonSplit.Quals);
3623 // Get the new insert position for the node we care about.
3624 IncompleteArrayType *existing =
3625 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3626 assert(!existing && "Shouldn't be in the map!"); (void) existing;
3629 auto *newType = new (*this, TypeAlignment)
3630 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3632 IncompleteArrayTypes.InsertNode(newType, insertPos);
3633 Types.push_back(newType);
3634 return QualType(newType, 0);
3637 ASTContext::BuiltinVectorTypeInfo
3638 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
3639 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
3640 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount(ELTS, true), \
3643 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
3644 {ELTTY, llvm::ElementCount(ELTS, true), NUMVECTORS};
3646 switch (Ty->getKind()) {
3648 llvm_unreachable("Unsupported builtin vector type");
3649 case BuiltinType::SveInt8:
3650 return SVE_INT_ELTTY(8, 16, true, 1);
3651 case BuiltinType::SveUint8:
3652 return SVE_INT_ELTTY(8, 16, false, 1);
3653 case BuiltinType::SveInt8x2:
3654 return SVE_INT_ELTTY(8, 16, true, 2);
3655 case BuiltinType::SveUint8x2:
3656 return SVE_INT_ELTTY(8, 16, false, 2);
3657 case BuiltinType::SveInt8x3:
3658 return SVE_INT_ELTTY(8, 16, true, 3);
3659 case BuiltinType::SveUint8x3:
3660 return SVE_INT_ELTTY(8, 16, false, 3);
3661 case BuiltinType::SveInt8x4:
3662 return SVE_INT_ELTTY(8, 16, true, 4);
3663 case BuiltinType::SveUint8x4:
3664 return SVE_INT_ELTTY(8, 16, false, 4);
3665 case BuiltinType::SveInt16:
3666 return SVE_INT_ELTTY(16, 8, true, 1);
3667 case BuiltinType::SveUint16:
3668 return SVE_INT_ELTTY(16, 8, false, 1);
3669 case BuiltinType::SveInt16x2:
3670 return SVE_INT_ELTTY(16, 8, true, 2);
3671 case BuiltinType::SveUint16x2:
3672 return SVE_INT_ELTTY(16, 8, false, 2);
3673 case BuiltinType::SveInt16x3:
3674 return SVE_INT_ELTTY(16, 8, true, 3);
3675 case BuiltinType::SveUint16x3:
3676 return SVE_INT_ELTTY(16, 8, false, 3);
3677 case BuiltinType::SveInt16x4:
3678 return SVE_INT_ELTTY(16, 8, true, 4);
3679 case BuiltinType::SveUint16x4:
3680 return SVE_INT_ELTTY(16, 8, false, 4);
3681 case BuiltinType::SveInt32:
3682 return SVE_INT_ELTTY(32, 4, true, 1);
3683 case BuiltinType::SveUint32:
3684 return SVE_INT_ELTTY(32, 4, false, 1);
3685 case BuiltinType::SveInt32x2:
3686 return SVE_INT_ELTTY(32, 4, true, 2);
3687 case BuiltinType::SveUint32x2:
3688 return SVE_INT_ELTTY(32, 4, false, 2);
3689 case BuiltinType::SveInt32x3:
3690 return SVE_INT_ELTTY(32, 4, true, 3);
3691 case BuiltinType::SveUint32x3:
3692 return SVE_INT_ELTTY(32, 4, false, 3);
3693 case BuiltinType::SveInt32x4:
3694 return SVE_INT_ELTTY(32, 4, true, 4);
3695 case BuiltinType::SveUint32x4:
3696 return SVE_INT_ELTTY(32, 4, false, 4);
3697 case BuiltinType::SveInt64:
3698 return SVE_INT_ELTTY(64, 2, true, 1);
3699 case BuiltinType::SveUint64:
3700 return SVE_INT_ELTTY(64, 2, false, 1);
3701 case BuiltinType::SveInt64x2:
3702 return SVE_INT_ELTTY(64, 2, true, 2);
3703 case BuiltinType::SveUint64x2:
3704 return SVE_INT_ELTTY(64, 2, false, 2);
3705 case BuiltinType::SveInt64x3:
3706 return SVE_INT_ELTTY(64, 2, true, 3);
3707 case BuiltinType::SveUint64x3:
3708 return SVE_INT_ELTTY(64, 2, false, 3);
3709 case BuiltinType::SveInt64x4:
3710 return SVE_INT_ELTTY(64, 2, true, 4);
3711 case BuiltinType::SveUint64x4:
3712 return SVE_INT_ELTTY(64, 2, false, 4);
3713 case BuiltinType::SveBool:
3714 return SVE_ELTTY(BoolTy, 16, 1);
3715 case BuiltinType::SveFloat16:
3716 return SVE_ELTTY(HalfTy, 8, 1);
3717 case BuiltinType::SveFloat16x2:
3718 return SVE_ELTTY(HalfTy, 8, 2);
3719 case BuiltinType::SveFloat16x3:
3720 return SVE_ELTTY(HalfTy, 8, 3);
3721 case BuiltinType::SveFloat16x4:
3722 return SVE_ELTTY(HalfTy, 8, 4);
3723 case BuiltinType::SveFloat32:
3724 return SVE_ELTTY(FloatTy, 4, 1);
3725 case BuiltinType::SveFloat32x2:
3726 return SVE_ELTTY(FloatTy, 4, 2);
3727 case BuiltinType::SveFloat32x3:
3728 return SVE_ELTTY(FloatTy, 4, 3);
3729 case BuiltinType::SveFloat32x4:
3730 return SVE_ELTTY(FloatTy, 4, 4);
3731 case BuiltinType::SveFloat64:
3732 return SVE_ELTTY(DoubleTy, 2, 1);
3733 case BuiltinType::SveFloat64x2:
3734 return SVE_ELTTY(DoubleTy, 2, 2);
3735 case BuiltinType::SveFloat64x3:
3736 return SVE_ELTTY(DoubleTy, 2, 3);
3737 case BuiltinType::SveFloat64x4:
3738 return SVE_ELTTY(DoubleTy, 2, 4);
3739 case BuiltinType::SveBFloat16:
3740 return SVE_ELTTY(BFloat16Ty, 8, 1);
3741 case BuiltinType::SveBFloat16x2:
3742 return SVE_ELTTY(BFloat16Ty, 8, 2);
3743 case BuiltinType::SveBFloat16x3:
3744 return SVE_ELTTY(BFloat16Ty, 8, 3);
3745 case BuiltinType::SveBFloat16x4:
3746 return SVE_ELTTY(BFloat16Ty, 8, 4);
3750 /// getScalableVectorType - Return the unique reference to a scalable vector
3751 /// type of the specified element type and size. VectorType must be a built-in
3753 QualType ASTContext::getScalableVectorType(QualType EltTy,
3754 unsigned NumElts) const {
3755 if (Target->hasAArch64SVETypes()) {
3756 uint64_t EltTySize = getTypeSize(EltTy);
3757 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
3758 IsSigned, IsFP, IsBF) \
3759 if (!EltTy->isBooleanType() && \
3760 ((EltTy->hasIntegerRepresentation() && \
3761 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
3762 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
3764 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
3765 IsBF && !IsFP)) && \
3766 EltTySize == ElBits && NumElts == NumEls) { \
3767 return SingletonId; \
3769 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
3770 if (EltTy->isBooleanType() && NumElts == NumEls) \
3772 #include "clang/Basic/AArch64SVEACLETypes.def"
3777 /// getVectorType - Return the unique reference to a vector type of
3778 /// the specified element type and size. VectorType must be a built-in type.
3779 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3780 VectorType::VectorKind VecKind) const {
3781 assert(vecType->isBuiltinType());
3783 // Check if we've already instantiated a vector of this type.
3784 llvm::FoldingSetNodeID ID;
3785 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3787 void *InsertPos = nullptr;
3788 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3789 return QualType(VTP, 0);
3791 // If the element type isn't canonical, this won't be a canonical type either,
3792 // so fill in the canonical type field.
3794 if (!vecType.isCanonical()) {
3795 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3797 // Get the new insert position for the node we care about.
3798 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3799 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3801 auto *New = new (*this, TypeAlignment)
3802 VectorType(vecType, NumElts, Canonical, VecKind);
3803 VectorTypes.InsertNode(New, InsertPos);
3804 Types.push_back(New);
3805 return QualType(New, 0);
3809 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3810 SourceLocation AttrLoc,
3811 VectorType::VectorKind VecKind) const {
3812 llvm::FoldingSetNodeID ID;
3813 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3815 void *InsertPos = nullptr;
3816 DependentVectorType *Canon =
3817 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3818 DependentVectorType *New;
3821 New = new (*this, TypeAlignment) DependentVectorType(
3822 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3824 QualType CanonVecTy = getCanonicalType(VecType);
3825 if (CanonVecTy == VecType) {
3826 New = new (*this, TypeAlignment) DependentVectorType(
3827 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3829 DependentVectorType *CanonCheck =
3830 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3831 assert(!CanonCheck &&
3832 "Dependent-sized vector_size canonical type broken");
3834 DependentVectorTypes.InsertNode(New, InsertPos);
3836 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
3837 SourceLocation(), VecKind);
3838 New = new (*this, TypeAlignment) DependentVectorType(
3839 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
3843 Types.push_back(New);
3844 return QualType(New, 0);
3847 /// getExtVectorType - Return the unique reference to an extended vector type of
3848 /// the specified element type and size. VectorType must be a built-in type.
3850 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3851 assert(vecType->isBuiltinType() || vecType->isDependentType());
3853 // Check if we've already instantiated a vector of this type.
3854 llvm::FoldingSetNodeID ID;
3855 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3856 VectorType::GenericVector);
3857 void *InsertPos = nullptr;
3858 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3859 return QualType(VTP, 0);
3861 // If the element type isn't canonical, this won't be a canonical type either,
3862 // so fill in the canonical type field.
3864 if (!vecType.isCanonical()) {
3865 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3867 // Get the new insert position for the node we care about.
3868 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3869 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3871 auto *New = new (*this, TypeAlignment)
3872 ExtVectorType(vecType, NumElts, Canonical);
3873 VectorTypes.InsertNode(New, InsertPos);
3874 Types.push_back(New);
3875 return QualType(New, 0);
3879 ASTContext::getDependentSizedExtVectorType(QualType vecType,
3881 SourceLocation AttrLoc) const {
3882 llvm::FoldingSetNodeID ID;
3883 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
3886 void *InsertPos = nullptr;
3887 DependentSizedExtVectorType *Canon
3888 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3889 DependentSizedExtVectorType *New;
3891 // We already have a canonical version of this array type; use it as
3892 // the canonical type for a newly-built type.
3893 New = new (*this, TypeAlignment)
3894 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3897 QualType CanonVecTy = getCanonicalType(vecType);
3898 if (CanonVecTy == vecType) {
3899 New = new (*this, TypeAlignment)
3900 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3903 DependentSizedExtVectorType *CanonCheck
3904 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3905 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3907 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3909 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3911 New = new (*this, TypeAlignment) DependentSizedExtVectorType(
3912 *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
3916 Types.push_back(New);
3917 return QualType(New, 0);
3920 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
3921 unsigned NumColumns) const {
3922 llvm::FoldingSetNodeID ID;
3923 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
3924 Type::ConstantMatrix);
3926 assert(MatrixType::isValidElementType(ElementTy) &&
3927 "need a valid element type");
3928 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
3929 ConstantMatrixType::isDimensionValid(NumColumns) &&
3930 "need valid matrix dimensions");
3931 void *InsertPos = nullptr;
3932 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
3933 return QualType(MTP, 0);
3936 if (!ElementTy.isCanonical()) {
3938 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
3940 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
3941 assert(!NewIP && "Matrix type shouldn't already exist in the map");
3945 auto *New = new (*this, TypeAlignment)
3946 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
3947 MatrixTypes.InsertNode(New, InsertPos);
3948 Types.push_back(New);
3949 return QualType(New, 0);
3952 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
3955 SourceLocation AttrLoc) const {
3956 QualType CanonElementTy = getCanonicalType(ElementTy);
3957 llvm::FoldingSetNodeID ID;
3958 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
3961 void *InsertPos = nullptr;
3962 DependentSizedMatrixType *Canon =
3963 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
3966 Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
3967 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
3969 DependentSizedMatrixType *CanonCheck =
3970 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
3971 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
3973 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
3974 Types.push_back(Canon);
3977 // Already have a canonical version of the matrix type
3979 // If it exactly matches the requested type, use it directly.
3980 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
3981 Canon->getRowExpr() == ColumnExpr)
3982 return QualType(Canon, 0);
3984 // Use Canon as the canonical type for newly-built type.
3985 DependentSizedMatrixType *New = new (*this, TypeAlignment)
3986 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
3987 ColumnExpr, AttrLoc);
3988 Types.push_back(New);
3989 return QualType(New, 0);
3992 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3993 Expr *AddrSpaceExpr,
3994 SourceLocation AttrLoc) const {
3995 assert(AddrSpaceExpr->isInstantiationDependent());
3997 QualType canonPointeeType = getCanonicalType(PointeeType);
3999 void *insertPos = nullptr;
4000 llvm::FoldingSetNodeID ID;
4001 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4004 DependentAddressSpaceType *canonTy =
4005 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4008 canonTy = new (*this, TypeAlignment)
4009 DependentAddressSpaceType(*this, canonPointeeType,
4010 QualType(), AddrSpaceExpr, AttrLoc);
4011 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4012 Types.push_back(canonTy);
4015 if (canonPointeeType == PointeeType &&
4016 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4017 return QualType(canonTy, 0);
4020 = new (*this, TypeAlignment)
4021 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
4022 AddrSpaceExpr, AttrLoc);
4023 Types.push_back(sugaredType);
4024 return QualType(sugaredType, 0);
4027 /// Determine whether \p T is canonical as the result type of a function.
4028 static bool isCanonicalResultType(QualType T) {
4029 return T.isCanonical() &&
4030 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4031 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4034 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4036 ASTContext::getFunctionNoProtoType(QualType ResultTy,
4037 const FunctionType::ExtInfo &Info) const {
4038 // Unique functions, to guarantee there is only one function of a particular
4040 llvm::FoldingSetNodeID ID;
4041 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4043 void *InsertPos = nullptr;
4044 if (FunctionNoProtoType *FT =
4045 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4046 return QualType(FT, 0);
4049 if (!isCanonicalResultType(ResultTy)) {
4051 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
4053 // Get the new insert position for the node we care about.
4054 FunctionNoProtoType *NewIP =
4055 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4056 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4059 auto *New = new (*this, TypeAlignment)
4060 FunctionNoProtoType(ResultTy, Canonical, Info);
4061 Types.push_back(New);
4062 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4063 return QualType(New, 0);
4067 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
4068 CanQualType CanResultType = getCanonicalType(ResultType);
4070 // Canonical result types do not have ARC lifetime qualifiers.
4071 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4072 Qualifiers Qs = CanResultType.getQualifiers();
4073 Qs.removeObjCLifetime();
4074 return CanQualType::CreateUnsafe(
4075 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4078 return CanResultType;
4081 static bool isCanonicalExceptionSpecification(
4082 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4083 if (ESI.Type == EST_None)
4085 if (!NoexceptInType)
4088 // C++17 onwards: exception specification is part of the type, as a simple
4089 // boolean "can this function type throw".
4090 if (ESI.Type == EST_BasicNoexcept)
4093 // A noexcept(expr) specification is (possibly) canonical if expr is
4095 if (ESI.Type == EST_DependentNoexcept)
4098 // A dynamic exception specification is canonical if it only contains pack
4099 // expansions (so we can't tell whether it's non-throwing) and all its
4100 // contained types are canonical.
4101 if (ESI.Type == EST_Dynamic) {
4102 bool AnyPackExpansions = false;
4103 for (QualType ET : ESI.Exceptions) {
4104 if (!ET.isCanonical())
4106 if (ET->getAs<PackExpansionType>())
4107 AnyPackExpansions = true;
4109 return AnyPackExpansions;
4115 QualType ASTContext::getFunctionTypeInternal(
4116 QualType ResultTy, ArrayRef<QualType> ArgArray,
4117 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4118 size_t NumArgs = ArgArray.size();
4120 // Unique functions, to guarantee there is only one function of a particular
4122 llvm::FoldingSetNodeID ID;
4123 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4127 bool Unique = false;
4129 void *InsertPos = nullptr;
4130 if (FunctionProtoType *FPT =
4131 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4132 QualType Existing = QualType(FPT, 0);
4134 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4135 // it so long as our exception specification doesn't contain a dependent
4136 // noexcept expression, or we're just looking for a canonical type.
4137 // Otherwise, we're going to need to create a type
4138 // sugar node to hold the concrete expression.
4139 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4140 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4143 // We need a new type sugar node for this one, to hold the new noexcept
4144 // expression. We do no canonicalization here, but that's OK since we don't
4145 // expect to see the same noexcept expression much more than once.
4146 Canonical = getCanonicalType(Existing);
4150 bool NoexceptInType = getLangOpts().CPlusPlus17;
4151 bool IsCanonicalExceptionSpec =
4152 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4154 // Determine whether the type being created is already canonical or not.
4155 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4156 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4157 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4158 if (!ArgArray[i].isCanonicalAsParam())
4159 isCanonical = false;
4161 if (OnlyWantCanonical)
4162 assert(isCanonical &&
4163 "given non-canonical parameters constructing canonical type");
4165 // If this type isn't canonical, get the canonical version of it if we don't
4166 // already have it. The exception spec is only partially part of the
4167 // canonical type, and only in C++17 onwards.
4168 if (!isCanonical && Canonical.isNull()) {
4169 SmallVector<QualType, 16> CanonicalArgs;
4170 CanonicalArgs.reserve(NumArgs);
4171 for (unsigned i = 0; i != NumArgs; ++i)
4172 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4174 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4175 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4176 CanonicalEPI.HasTrailingReturn = false;
4178 if (IsCanonicalExceptionSpec) {
4179 // Exception spec is already OK.
4180 } else if (NoexceptInType) {
4181 switch (EPI.ExceptionSpec.Type) {
4182 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
4183 // We don't know yet. It shouldn't matter what we pick here; no-one
4184 // should ever look at this.
4186 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4187 CanonicalEPI.ExceptionSpec.Type = EST_None;
4190 // A dynamic exception specification is almost always "not noexcept",
4191 // with the exception that a pack expansion might expand to no types.
4193 bool AnyPacks = false;
4194 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4195 if (ET->getAs<PackExpansionType>())
4197 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4200 CanonicalEPI.ExceptionSpec.Type = EST_None;
4202 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4203 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4208 case EST_DynamicNone:
4209 case EST_BasicNoexcept:
4210 case EST_NoexceptTrue:
4212 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4215 case EST_DependentNoexcept:
4216 llvm_unreachable("dependent noexcept is already canonical");
4219 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
4222 // Adjust the canonical function result type.
4223 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4225 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4227 // Get the new insert position for the node we care about.
4228 FunctionProtoType *NewIP =
4229 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4230 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4233 // Compute the needed size to hold this FunctionProtoType and the
4234 // various trailing objects.
4235 auto ESH = FunctionProtoType::getExceptionSpecSize(
4236 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4237 size_t Size = FunctionProtoType::totalSizeToAlloc<
4238 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
4239 FunctionType::ExceptionType, Expr *, FunctionDecl *,
4240 FunctionProtoType::ExtParameterInfo, Qualifiers>(
4241 NumArgs, EPI.Variadic,
4242 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
4243 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4244 EPI.ExtParameterInfos ? NumArgs : 0,
4245 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4247 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
4248 FunctionProtoType::ExtProtoInfo newEPI = EPI;
4249 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4250 Types.push_back(FTP);
4252 FunctionProtoTypes.InsertNode(FTP, InsertPos);
4253 return QualType(FTP, 0);
4256 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4257 llvm::FoldingSetNodeID ID;
4258 PipeType::Profile(ID, T, ReadOnly);
4260 void *InsertPos = nullptr;
4261 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4262 return QualType(PT, 0);
4264 // If the pipe element type isn't canonical, this won't be a canonical type
4265 // either, so fill in the canonical type field.
4267 if (!T.isCanonical()) {
4268 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4270 // Get the new insert position for the node we care about.
4271 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4272 assert(!NewIP && "Shouldn't be in the map!");
4275 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
4276 Types.push_back(New);
4277 PipeTypes.InsertNode(New, InsertPos);
4278 return QualType(New, 0);
4281 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4282 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4283 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4287 QualType ASTContext::getReadPipeType(QualType T) const {
4288 return getPipeType(T, true);
4291 QualType ASTContext::getWritePipeType(QualType T) const {
4292 return getPipeType(T, false);
4295 QualType ASTContext::getExtIntType(bool IsUnsigned, unsigned NumBits) const {
4296 llvm::FoldingSetNodeID ID;
4297 ExtIntType::Profile(ID, IsUnsigned, NumBits);
4299 void *InsertPos = nullptr;
4300 if (ExtIntType *EIT = ExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4301 return QualType(EIT, 0);
4303 auto *New = new (*this, TypeAlignment) ExtIntType(IsUnsigned, NumBits);
4304 ExtIntTypes.InsertNode(New, InsertPos);
4305 Types.push_back(New);
4306 return QualType(New, 0);
4309 QualType ASTContext::getDependentExtIntType(bool IsUnsigned,
4310 Expr *NumBitsExpr) const {
4311 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4312 llvm::FoldingSetNodeID ID;
4313 DependentExtIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4315 void *InsertPos = nullptr;
4316 if (DependentExtIntType *Existing =
4317 DependentExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4318 return QualType(Existing, 0);
4320 auto *New = new (*this, TypeAlignment)
4321 DependentExtIntType(*this, IsUnsigned, NumBitsExpr);
4322 DependentExtIntTypes.InsertNode(New, InsertPos);
4324 Types.push_back(New);
4325 return QualType(New, 0);
4329 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4330 if (!isa<CXXRecordDecl>(D)) return false;
4331 const auto *RD = cast<CXXRecordDecl>(D);
4332 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4334 if (RD->getDescribedClassTemplate() &&
4335 !isa<ClassTemplateSpecializationDecl>(RD))
4341 /// getInjectedClassNameType - Return the unique reference to the
4342 /// injected class name type for the specified templated declaration.
4343 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4344 QualType TST) const {
4345 assert(NeedsInjectedClassNameType(Decl));
4346 if (Decl->TypeForDecl) {
4347 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4348 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4349 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4350 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4351 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4354 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4355 Decl->TypeForDecl = newType;
4356 Types.push_back(newType);
4358 return QualType(Decl->TypeForDecl, 0);
4361 /// getTypeDeclType - Return the unique reference to the type for the
4362 /// specified type declaration.
4363 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4364 assert(Decl && "Passed null for Decl param");
4365 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4367 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4368 return getTypedefType(Typedef);
4370 assert(!isa<TemplateTypeParmDecl>(Decl) &&
4371 "Template type parameter types are always available.");
4373 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4374 assert(Record->isFirstDecl() && "struct/union has previous declaration");
4375 assert(!NeedsInjectedClassNameType(Record));
4376 return getRecordType(Record);
4377 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4378 assert(Enum->isFirstDecl() && "enum has previous declaration");
4379 return getEnumType(Enum);
4380 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4381 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
4382 Decl->TypeForDecl = newType;
4383 Types.push_back(newType);
4385 llvm_unreachable("TypeDecl without a type?");
4387 return QualType(Decl->TypeForDecl, 0);
4390 /// getTypedefType - Return the unique reference to the type for the
4391 /// specified typedef name decl.
4393 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4394 QualType Canonical) const {
4395 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4397 if (Canonical.isNull())
4398 Canonical = getCanonicalType(Decl->getUnderlyingType());
4399 auto *newType = new (*this, TypeAlignment)
4400 TypedefType(Type::Typedef, Decl, Canonical);
4401 Decl->TypeForDecl = newType;
4402 Types.push_back(newType);
4403 return QualType(newType, 0);
4406 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4407 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4409 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4410 if (PrevDecl->TypeForDecl)
4411 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4413 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4414 Decl->TypeForDecl = newType;
4415 Types.push_back(newType);
4416 return QualType(newType, 0);
4419 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4420 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4422 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4423 if (PrevDecl->TypeForDecl)
4424 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4426 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4427 Decl->TypeForDecl = newType;
4428 Types.push_back(newType);
4429 return QualType(newType, 0);
4432 QualType ASTContext::getAttributedType(attr::Kind attrKind,
4433 QualType modifiedType,
4434 QualType equivalentType) {
4435 llvm::FoldingSetNodeID id;
4436 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4438 void *insertPos = nullptr;
4439 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4440 if (type) return QualType(type, 0);
4442 QualType canon = getCanonicalType(equivalentType);
4443 type = new (*this, TypeAlignment)
4444 AttributedType(canon, attrKind, modifiedType, equivalentType);
4446 Types.push_back(type);
4447 AttributedTypes.InsertNode(type, insertPos);
4449 return QualType(type, 0);
4452 /// Retrieve a substitution-result type.
4454 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
4455 QualType Replacement) const {
4456 assert(Replacement.isCanonical()
4457 && "replacement types must always be canonical");
4459 llvm::FoldingSetNodeID ID;
4460 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
4461 void *InsertPos = nullptr;
4462 SubstTemplateTypeParmType *SubstParm
4463 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4466 SubstParm = new (*this, TypeAlignment)
4467 SubstTemplateTypeParmType(Parm, Replacement);
4468 Types.push_back(SubstParm);
4469 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4472 return QualType(SubstParm, 0);
4476 QualType ASTContext::getSubstTemplateTypeParmPackType(
4477 const TemplateTypeParmType *Parm,
4478 const TemplateArgument &ArgPack) {
4480 for (const auto &P : ArgPack.pack_elements()) {
4481 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4482 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4486 llvm::FoldingSetNodeID ID;
4487 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4488 void *InsertPos = nullptr;
4489 if (SubstTemplateTypeParmPackType *SubstParm
4490 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4491 return QualType(SubstParm, 0);
4494 if (!Parm->isCanonicalUnqualified()) {
4495 Canon = getCanonicalType(QualType(Parm, 0));
4496 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4498 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4502 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4504 Types.push_back(SubstParm);
4505 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4506 return QualType(SubstParm, 0);
4509 /// Retrieve the template type parameter type for a template
4510 /// parameter or parameter pack with the given depth, index, and (optionally)
4512 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4514 TemplateTypeParmDecl *TTPDecl) const {
4515 llvm::FoldingSetNodeID ID;
4516 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4517 void *InsertPos = nullptr;
4518 TemplateTypeParmType *TypeParm
4519 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4522 return QualType(TypeParm, 0);
4525 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4526 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4528 TemplateTypeParmType *TypeCheck
4529 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4530 assert(!TypeCheck && "Template type parameter canonical type broken");
4533 TypeParm = new (*this, TypeAlignment)
4534 TemplateTypeParmType(Depth, Index, ParameterPack);
4536 Types.push_back(TypeParm);
4537 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4539 return QualType(TypeParm, 0);
4543 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4544 SourceLocation NameLoc,
4545 const TemplateArgumentListInfo &Args,
4546 QualType Underlying) const {
4547 assert(!Name.getAsDependentTemplateName() &&
4548 "No dependent template names here!");
4549 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4551 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4552 TemplateSpecializationTypeLoc TL =
4553 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4554 TL.setTemplateKeywordLoc(SourceLocation());
4555 TL.setTemplateNameLoc(NameLoc);
4556 TL.setLAngleLoc(Args.getLAngleLoc());
4557 TL.setRAngleLoc(Args.getRAngleLoc());
4558 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4559 TL.setArgLocInfo(i, Args[i].getLocInfo());
4564 ASTContext::getTemplateSpecializationType(TemplateName Template,
4565 const TemplateArgumentListInfo &Args,
4566 QualType Underlying) const {
4567 assert(!Template.getAsDependentTemplateName() &&
4568 "No dependent template names here!");
4570 SmallVector<TemplateArgument, 4> ArgVec;
4571 ArgVec.reserve(Args.size());
4572 for (const TemplateArgumentLoc &Arg : Args.arguments())
4573 ArgVec.push_back(Arg.getArgument());
4575 return getTemplateSpecializationType(Template, ArgVec, Underlying);
4579 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4580 for (const TemplateArgument &Arg : Args)
4581 if (Arg.isPackExpansion())
4589 ASTContext::getTemplateSpecializationType(TemplateName Template,
4590 ArrayRef<TemplateArgument> Args,
4591 QualType Underlying) const {
4592 assert(!Template.getAsDependentTemplateName() &&
4593 "No dependent template names here!");
4594 // Look through qualified template names.
4595 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4596 Template = TemplateName(QTN->getTemplateDecl());
4599 Template.getAsTemplateDecl() &&
4600 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4602 if (!Underlying.isNull())
4603 CanonType = getCanonicalType(Underlying);
4605 // We can get here with an alias template when the specialization contains
4606 // a pack expansion that does not match up with a parameter pack.
4607 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4608 "Caller must compute aliased type");
4609 IsTypeAlias = false;
4610 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4613 // Allocate the (non-canonical) template specialization type, but don't
4614 // try to unique it: these types typically have location information that
4615 // we don't unique and don't want to lose.
4616 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4617 sizeof(TemplateArgument) * Args.size() +
4618 (IsTypeAlias? sizeof(QualType) : 0),
4621 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4622 IsTypeAlias ? Underlying : QualType());
4624 Types.push_back(Spec);
4625 return QualType(Spec, 0);
4628 QualType ASTContext::getCanonicalTemplateSpecializationType(
4629 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4630 assert(!Template.getAsDependentTemplateName() &&
4631 "No dependent template names here!");
4633 // Look through qualified template names.
4634 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4635 Template = TemplateName(QTN->getTemplateDecl());
4637 // Build the canonical template specialization type.
4638 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4639 SmallVector<TemplateArgument, 4> CanonArgs;
4640 unsigned NumArgs = Args.size();
4641 CanonArgs.reserve(NumArgs);
4642 for (const TemplateArgument &Arg : Args)
4643 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
4645 // Determine whether this canonical template specialization type already
4647 llvm::FoldingSetNodeID ID;
4648 TemplateSpecializationType::Profile(ID, CanonTemplate,
4651 void *InsertPos = nullptr;
4652 TemplateSpecializationType *Spec
4653 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4656 // Allocate a new canonical template specialization type.
4657 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4658 sizeof(TemplateArgument) * NumArgs),
4660 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4662 QualType(), QualType());
4663 Types.push_back(Spec);
4664 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4667 assert(Spec->isDependentType() &&
4668 "Non-dependent template-id type must have a canonical type");
4669 return QualType(Spec, 0);
4672 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4673 NestedNameSpecifier *NNS,
4675 TagDecl *OwnedTagDecl) const {
4676 llvm::FoldingSetNodeID ID;
4677 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4679 void *InsertPos = nullptr;
4680 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4682 return QualType(T, 0);
4684 QualType Canon = NamedType;
4685 if (!Canon.isCanonical()) {
4686 Canon = getCanonicalType(NamedType);
4687 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4688 assert(!CheckT && "Elaborated canonical type broken");
4692 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4694 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4697 ElaboratedTypes.InsertNode(T, InsertPos);
4698 return QualType(T, 0);
4702 ASTContext::getParenType(QualType InnerType) const {
4703 llvm::FoldingSetNodeID ID;
4704 ParenType::Profile(ID, InnerType);
4706 void *InsertPos = nullptr;
4707 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4709 return QualType(T, 0);
4711 QualType Canon = InnerType;
4712 if (!Canon.isCanonical()) {
4713 Canon = getCanonicalType(InnerType);
4714 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4715 assert(!CheckT && "Paren canonical type broken");
4719 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4721 ParenTypes.InsertNode(T, InsertPos);
4722 return QualType(T, 0);
4726 ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4727 const IdentifierInfo *MacroII) const {
4728 QualType Canon = UnderlyingTy;
4729 if (!Canon.isCanonical())
4730 Canon = getCanonicalType(UnderlyingTy);
4732 auto *newType = new (*this, TypeAlignment)
4733 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4734 Types.push_back(newType);
4735 return QualType(newType, 0);
4738 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4739 NestedNameSpecifier *NNS,
4740 const IdentifierInfo *Name,
4741 QualType Canon) const {
4742 if (Canon.isNull()) {
4743 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4744 if (CanonNNS != NNS)
4745 Canon = getDependentNameType(Keyword, CanonNNS, Name);
4748 llvm::FoldingSetNodeID ID;
4749 DependentNameType::Profile(ID, Keyword, NNS, Name);
4751 void *InsertPos = nullptr;
4752 DependentNameType *T
4753 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
4755 return QualType(T, 0);
4757 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
4759 DependentNameTypes.InsertNode(T, InsertPos);
4760 return QualType(T, 0);
4764 ASTContext::getDependentTemplateSpecializationType(
4765 ElaboratedTypeKeyword Keyword,
4766 NestedNameSpecifier *NNS,
4767 const IdentifierInfo *Name,
4768 const TemplateArgumentListInfo &Args) const {
4769 // TODO: avoid this copy
4770 SmallVector<TemplateArgument, 16> ArgCopy;
4771 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4772 ArgCopy.push_back(Args[I].getArgument());
4773 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
4777 ASTContext::getDependentTemplateSpecializationType(
4778 ElaboratedTypeKeyword Keyword,
4779 NestedNameSpecifier *NNS,
4780 const IdentifierInfo *Name,
4781 ArrayRef<TemplateArgument> Args) const {
4782 assert((!NNS || NNS->isDependent()) &&
4783 "nested-name-specifier must be dependent");
4785 llvm::FoldingSetNodeID ID;
4786 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
4789 void *InsertPos = nullptr;
4790 DependentTemplateSpecializationType *T
4791 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4793 return QualType(T, 0);
4795 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4797 ElaboratedTypeKeyword CanonKeyword = Keyword;
4798 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4800 bool AnyNonCanonArgs = false;
4801 unsigned NumArgs = Args.size();
4802 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
4803 for (unsigned I = 0; I != NumArgs; ++I) {
4804 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4805 if (!CanonArgs[I].structurallyEquals(Args[I]))
4806 AnyNonCanonArgs = true;
4810 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4811 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
4815 // Find the insert position again.
4816 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4819 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4820 sizeof(TemplateArgument) * NumArgs),
4822 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
4825 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
4826 return QualType(T, 0);
4829 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4830 TemplateArgument Arg;
4831 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4832 QualType ArgType = getTypeDeclType(TTP);
4833 if (TTP->isParameterPack())
4834 ArgType = getPackExpansionType(ArgType, None);
4836 Arg = TemplateArgument(ArgType);
4837 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4838 Expr *E = new (*this) DeclRefExpr(
4839 *this, NTTP, /*enclosing*/ false,
4840 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this),
4841 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4843 if (NTTP->isParameterPack())
4844 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4846 Arg = TemplateArgument(E);
4848 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4849 if (TTP->isParameterPack())
4850 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4852 Arg = TemplateArgument(TemplateName(TTP));
4855 if (Param->isTemplateParameterPack())
4856 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4862 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4863 SmallVectorImpl<TemplateArgument> &Args) {
4864 Args.reserve(Args.size() + Params->size());
4866 for (NamedDecl *Param : *Params)
4867 Args.push_back(getInjectedTemplateArg(Param));
4870 QualType ASTContext::getPackExpansionType(QualType Pattern,
4871 Optional<unsigned> NumExpansions) {
4872 llvm::FoldingSetNodeID ID;
4873 PackExpansionType::Profile(ID, Pattern, NumExpansions);
4875 // A deduced type can deduce to a pack, eg
4876 // auto ...x = some_pack;
4877 // That declaration isn't (yet) valid, but is created as part of building an
4878 // init-capture pack:
4879 // [...x = some_pack] {}
4880 assert((Pattern->containsUnexpandedParameterPack() ||
4881 Pattern->getContainedDeducedType()) &&
4882 "Pack expansions must expand one or more parameter packs");
4883 void *InsertPos = nullptr;
4884 PackExpansionType *T
4885 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4887 return QualType(T, 0);
4890 if (!Pattern.isCanonical()) {
4891 Canon = getCanonicalType(Pattern);
4892 // The canonical type might not contain an unexpanded parameter pack, if it
4893 // contains an alias template specialization which ignores one of its
4895 if (Canon->containsUnexpandedParameterPack()) {
4896 Canon = getPackExpansionType(Canon, NumExpansions);
4898 // Find the insert position again, in case we inserted an element into
4899 // PackExpansionTypes and invalidated our insert position.
4900 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4904 T = new (*this, TypeAlignment)
4905 PackExpansionType(Pattern, Canon, NumExpansions);
4907 PackExpansionTypes.InsertNode(T, InsertPos);
4908 return QualType(T, 0);
4911 /// CmpProtocolNames - Comparison predicate for sorting protocols
4913 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4914 ObjCProtocolDecl *const *RHS) {
4915 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
4918 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4919 if (Protocols.empty()) return true;
4921 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4924 for (unsigned i = 1; i != Protocols.size(); ++i)
4925 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
4926 Protocols[i]->getCanonicalDecl() != Protocols[i])
4932 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
4933 // Sort protocols, keyed by name.
4934 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
4937 for (ObjCProtocolDecl *&P : Protocols)
4938 P = P->getCanonicalDecl();
4940 // Remove duplicates.
4941 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4942 Protocols.erase(ProtocolsEnd, Protocols.end());
4945 QualType ASTContext::getObjCObjectType(QualType BaseType,
4946 ObjCProtocolDecl * const *Protocols,
4947 unsigned NumProtocols) const {
4948 return getObjCObjectType(BaseType, {},
4949 llvm::makeArrayRef(Protocols, NumProtocols),
4950 /*isKindOf=*/false);
4953 QualType ASTContext::getObjCObjectType(
4955 ArrayRef<QualType> typeArgs,
4956 ArrayRef<ObjCProtocolDecl *> protocols,
4957 bool isKindOf) const {
4958 // If the base type is an interface and there aren't any protocols or
4959 // type arguments to add, then the interface type will do just fine.
4960 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4961 isa<ObjCInterfaceType>(baseType))
4964 // Look in the folding set for an existing type.
4965 llvm::FoldingSetNodeID ID;
4966 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4967 void *InsertPos = nullptr;
4968 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4969 return QualType(QT, 0);
4971 // Determine the type arguments to be used for canonicalization,
4972 // which may be explicitly specified here or written on the base
4974 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4975 if (effectiveTypeArgs.empty()) {
4976 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
4977 effectiveTypeArgs = baseObject->getTypeArgs();
4980 // Build the canonical type, which has the canonical base type and a
4981 // sorted-and-uniqued list of protocols and the type arguments
4984 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4985 effectiveTypeArgs.end(),
4986 [&](QualType type) {
4987 return type.isCanonical();
4989 bool protocolsSorted = areSortedAndUniqued(protocols);
4990 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4991 // Determine the canonical type arguments.
4992 ArrayRef<QualType> canonTypeArgs;
4993 SmallVector<QualType, 4> canonTypeArgsVec;
4994 if (!typeArgsAreCanonical) {
4995 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4996 for (auto typeArg : effectiveTypeArgs)
4997 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4998 canonTypeArgs = canonTypeArgsVec;
5000 canonTypeArgs = effectiveTypeArgs;
5003 ArrayRef<ObjCProtocolDecl *> canonProtocols;
5004 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5005 if (!protocolsSorted) {
5006 canonProtocolsVec.append(protocols.begin(), protocols.end());
5007 SortAndUniqueProtocols(canonProtocolsVec);
5008 canonProtocols = canonProtocolsVec;
5010 canonProtocols = protocols;
5013 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5014 canonProtocols, isKindOf);
5016 // Regenerate InsertPos.
5017 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5020 unsigned size = sizeof(ObjCObjectTypeImpl);
5021 size += typeArgs.size() * sizeof(QualType);
5022 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5023 void *mem = Allocate(size, TypeAlignment);
5025 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5029 ObjCObjectTypes.InsertNode(T, InsertPos);
5030 return QualType(T, 0);
5033 /// Apply Objective-C protocol qualifiers to the given type.
5034 /// If this is for the canonical type of a type parameter, we can apply
5035 /// protocol qualifiers on the ObjCObjectPointerType.
5037 ASTContext::applyObjCProtocolQualifiers(QualType type,
5038 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5039 bool allowOnPointerType) const {
5042 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5043 return getObjCTypeParamType(objT->getDecl(), protocols);
5046 // Apply protocol qualifiers to ObjCObjectPointerType.
5047 if (allowOnPointerType) {
5048 if (const auto *objPtr =
5049 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5050 const ObjCObjectType *objT = objPtr->getObjectType();
5051 // Merge protocol lists and construct ObjCObjectType.
5052 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
5053 protocolsVec.append(objT->qual_begin(),
5055 protocolsVec.append(protocols.begin(), protocols.end());
5056 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5057 type = getObjCObjectType(
5058 objT->getBaseType(),
5059 objT->getTypeArgsAsWritten(),
5061 objT->isKindOfTypeAsWritten());
5062 return getObjCObjectPointerType(type);
5066 // Apply protocol qualifiers to ObjCObjectType.
5067 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5068 // FIXME: Check for protocols to which the class type is already
5069 // known to conform.
5071 return getObjCObjectType(objT->getBaseType(),
5072 objT->getTypeArgsAsWritten(),
5074 objT->isKindOfTypeAsWritten());
5077 // If the canonical type is ObjCObjectType, ...
5078 if (type->isObjCObjectType()) {
5079 // Silently overwrite any existing protocol qualifiers.
5080 // TODO: determine whether that's the right thing to do.
5082 // FIXME: Check for protocols to which the class type is already
5083 // known to conform.
5084 return getObjCObjectType(type, {}, protocols, false);
5087 // id<protocol-list>
5088 if (type->isObjCIdType()) {
5089 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5090 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5091 objPtr->isKindOfType());
5092 return getObjCObjectPointerType(type);
5095 // Class<protocol-list>
5096 if (type->isObjCClassType()) {
5097 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5098 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5099 objPtr->isKindOfType());
5100 return getObjCObjectPointerType(type);
5108 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
5109 ArrayRef<ObjCProtocolDecl *> protocols) const {
5110 // Look in the folding set for an existing type.
5111 llvm::FoldingSetNodeID ID;
5112 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5113 void *InsertPos = nullptr;
5114 if (ObjCTypeParamType *TypeParam =
5115 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5116 return QualType(TypeParam, 0);
5118 // We canonicalize to the underlying type.
5119 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5120 if (!protocols.empty()) {
5121 // Apply the protocol qualifers.
5123 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
5124 Canonical, protocols, hasError, true /*allowOnPointerType*/));
5125 assert(!hasError && "Error when apply protocol qualifier to bound type");
5128 unsigned size = sizeof(ObjCTypeParamType);
5129 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5130 void *mem = Allocate(size, TypeAlignment);
5131 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5133 Types.push_back(newType);
5134 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5135 return QualType(newType, 0);
5138 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
5139 ObjCTypeParamDecl *New) const {
5140 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
5141 // Update TypeForDecl after updating TypeSourceInfo.
5142 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5143 SmallVector<ObjCProtocolDecl *, 8> protocols;
5144 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5145 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5146 New->setTypeForDecl(UpdatedTy.getTypePtr());
5149 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5150 /// protocol list adopt all protocols in QT's qualified-id protocol
5152 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
5153 ObjCInterfaceDecl *IC) {
5154 if (!QT->isObjCQualifiedIdType())
5157 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5158 // If both the right and left sides have qualifiers.
5159 for (auto *Proto : OPT->quals()) {
5160 if (!IC->ClassImplementsProtocol(Proto, false))
5168 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5169 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
5171 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
5172 ObjCInterfaceDecl *IDecl) {
5173 if (!QT->isObjCQualifiedIdType())
5175 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5178 if (!IDecl->hasDefinition())
5180 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
5181 CollectInheritedProtocols(IDecl, InheritedProtocols);
5182 if (InheritedProtocols.empty())
5184 // Check that if every protocol in list of id<plist> conforms to a protocol
5185 // of IDecl's, then bridge casting is ok.
5186 bool Conforms = false;
5187 for (auto *Proto : OPT->quals()) {
5189 for (auto *PI : InheritedProtocols) {
5190 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5201 for (auto *PI : InheritedProtocols) {
5202 // If both the right and left sides have qualifiers.
5203 bool Adopts = false;
5204 for (auto *Proto : OPT->quals()) {
5205 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5206 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5215 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5216 /// the given object type.
5217 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
5218 llvm::FoldingSetNodeID ID;
5219 ObjCObjectPointerType::Profile(ID, ObjectT);
5221 void *InsertPos = nullptr;
5222 if (ObjCObjectPointerType *QT =
5223 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5224 return QualType(QT, 0);
5226 // Find the canonical object type.
5228 if (!ObjectT.isCanonical()) {
5229 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5231 // Regenerate InsertPos.
5232 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5236 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
5238 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5240 Types.push_back(QType);
5241 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5242 return QualType(QType, 0);
5245 /// getObjCInterfaceType - Return the unique reference to the type for the
5246 /// specified ObjC interface decl. The list of protocols is optional.
5247 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
5248 ObjCInterfaceDecl *PrevDecl) const {
5249 if (Decl->TypeForDecl)
5250 return QualType(Decl->TypeForDecl, 0);
5253 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5254 Decl->TypeForDecl = PrevDecl->TypeForDecl;
5255 return QualType(PrevDecl->TypeForDecl, 0);
5258 // Prefer the definition, if there is one.
5259 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5262 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
5263 auto *T = new (Mem) ObjCInterfaceType(Decl);
5264 Decl->TypeForDecl = T;
5266 return QualType(T, 0);
5269 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5270 /// TypeOfExprType AST's (since expression's are never shared). For example,
5271 /// multiple declarations that refer to "typeof(x)" all contain different
5272 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
5273 /// on canonical type's (which are always unique).
5274 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
5275 TypeOfExprType *toe;
5276 if (tofExpr->isTypeDependent()) {
5277 llvm::FoldingSetNodeID ID;
5278 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
5280 void *InsertPos = nullptr;
5281 DependentTypeOfExprType *Canon
5282 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5284 // We already have a "canonical" version of an identical, dependent
5285 // typeof(expr) type. Use that as our canonical type.
5286 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
5287 QualType((TypeOfExprType*)Canon, 0));
5289 // Build a new, canonical typeof(expr) type.
5291 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
5292 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5296 QualType Canonical = getCanonicalType(tofExpr->getType());
5297 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
5299 Types.push_back(toe);
5300 return QualType(toe, 0);
5303 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
5304 /// TypeOfType nodes. The only motivation to unique these nodes would be
5305 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5306 /// an issue. This doesn't affect the type checker, since it operates
5307 /// on canonical types (which are always unique).
5308 QualType ASTContext::getTypeOfType(QualType tofType) const {
5309 QualType Canonical = getCanonicalType(tofType);
5310 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
5311 Types.push_back(tot);
5312 return QualType(tot, 0);
5315 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
5316 /// nodes. This would never be helpful, since each such type has its own
5317 /// expression, and would not give a significant memory saving, since there
5318 /// is an Expr tree under each such type.
5319 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
5322 // C++11 [temp.type]p2:
5323 // If an expression e involves a template parameter, decltype(e) denotes a
5324 // unique dependent type. Two such decltype-specifiers refer to the same
5325 // type only if their expressions are equivalent (14.5.6.1).
5326 if (e->isInstantiationDependent()) {
5327 llvm::FoldingSetNodeID ID;
5328 DependentDecltypeType::Profile(ID, *this, e);
5330 void *InsertPos = nullptr;
5331 DependentDecltypeType *Canon
5332 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5334 // Build a new, canonical decltype(expr) type.
5335 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
5336 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5338 dt = new (*this, TypeAlignment)
5339 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5341 dt = new (*this, TypeAlignment)
5342 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5344 Types.push_back(dt);
5345 return QualType(dt, 0);
5348 /// getUnaryTransformationType - We don't unique these, since the memory
5349 /// savings are minimal and these are rare.
5350 QualType ASTContext::getUnaryTransformType(QualType BaseType,
5351 QualType UnderlyingType,
5352 UnaryTransformType::UTTKind Kind)
5354 UnaryTransformType *ut = nullptr;
5356 if (BaseType->isDependentType()) {
5357 // Look in the folding set for an existing type.
5358 llvm::FoldingSetNodeID ID;
5359 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5361 void *InsertPos = nullptr;
5362 DependentUnaryTransformType *Canon
5363 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5366 // Build a new, canonical __underlying_type(type) type.
5367 Canon = new (*this, TypeAlignment)
5368 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5370 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5372 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5374 QualType(Canon, 0));
5376 QualType CanonType = getCanonicalType(UnderlyingType);
5377 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5378 UnderlyingType, Kind,
5381 Types.push_back(ut);
5382 return QualType(ut, 0);
5385 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
5386 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5387 /// canonical deduced-but-dependent 'auto' type.
5389 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5390 bool IsDependent, bool IsPack,
5391 ConceptDecl *TypeConstraintConcept,
5392 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5393 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5394 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5395 !TypeConstraintConcept && !IsDependent)
5396 return getAutoDeductType();
5398 // Look in the folding set for an existing type.
5399 void *InsertPos = nullptr;
5400 llvm::FoldingSetNodeID ID;
5401 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5402 TypeConstraintConcept, TypeConstraintArgs);
5403 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5404 return QualType(AT, 0);
5406 void *Mem = Allocate(sizeof(AutoType) +
5407 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5409 auto *AT = new (Mem) AutoType(
5410 DeducedType, Keyword,
5411 (IsDependent ? TypeDependence::DependentInstantiation
5412 : TypeDependence::None) |
5413 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5414 TypeConstraintConcept, TypeConstraintArgs);
5415 Types.push_back(AT);
5417 AutoTypes.InsertNode(AT, InsertPos);
5418 return QualType(AT, 0);
5421 /// Return the uniqued reference to the deduced template specialization type
5422 /// which has been deduced to the given type, or to the canonical undeduced
5423 /// such type, or the canonical deduced-but-dependent such type.
5424 QualType ASTContext::getDeducedTemplateSpecializationType(
5425 TemplateName Template, QualType DeducedType, bool IsDependent) const {
5426 // Look in the folding set for an existing type.
5427 void *InsertPos = nullptr;
5428 llvm::FoldingSetNodeID ID;
5429 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5431 if (DeducedTemplateSpecializationType *DTST =
5432 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5433 return QualType(DTST, 0);
5435 auto *DTST = new (*this, TypeAlignment)
5436 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5437 Types.push_back(DTST);
5439 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5440 return QualType(DTST, 0);
5443 /// getAtomicType - Return the uniqued reference to the atomic type for
5444 /// the given value type.
5445 QualType ASTContext::getAtomicType(QualType T) const {
5446 // Unique pointers, to guarantee there is only one pointer of a particular
5448 llvm::FoldingSetNodeID ID;
5449 AtomicType::Profile(ID, T);
5451 void *InsertPos = nullptr;
5452 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5453 return QualType(AT, 0);
5455 // If the atomic value type isn't canonical, this won't be a canonical type
5456 // either, so fill in the canonical type field.
5458 if (!T.isCanonical()) {
5459 Canonical = getAtomicType(getCanonicalType(T));
5461 // Get the new insert position for the node we care about.
5462 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5463 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5465 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
5466 Types.push_back(New);
5467 AtomicTypes.InsertNode(New, InsertPos);
5468 return QualType(New, 0);
5471 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
5472 QualType ASTContext::getAutoDeductType() const {
5473 if (AutoDeductTy.isNull())
5474 AutoDeductTy = QualType(new (*this, TypeAlignment)
5475 AutoType(QualType(), AutoTypeKeyword::Auto,
5476 TypeDependence::None,
5477 /*concept*/ nullptr, /*args*/ {}),
5479 return AutoDeductTy;
5482 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5483 QualType ASTContext::getAutoRRefDeductType() const {
5484 if (AutoRRefDeductTy.isNull())
5485 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5486 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5487 return AutoRRefDeductTy;
5490 /// getTagDeclType - Return the unique reference to the type for the
5491 /// specified TagDecl (struct/union/class/enum) decl.
5492 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
5494 // FIXME: What is the design on getTagDeclType when it requires casting
5495 // away const? mutable?
5496 return getTypeDeclType(const_cast<TagDecl*>(Decl));
5499 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5500 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5501 /// needs to agree with the definition in <stddef.h>.
5502 CanQualType ASTContext::getSizeType() const {
5503 return getFromTargetType(Target->getSizeType());
5506 /// Return the unique signed counterpart of the integer type
5507 /// corresponding to size_t.
5508 CanQualType ASTContext::getSignedSizeType() const {
5509 return getFromTargetType(Target->getSignedSizeType());
5512 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5513 CanQualType ASTContext::getIntMaxType() const {
5514 return getFromTargetType(Target->getIntMaxType());
5517 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5518 CanQualType ASTContext::getUIntMaxType() const {
5519 return getFromTargetType(Target->getUIntMaxType());
5522 /// getSignedWCharType - Return the type of "signed wchar_t".
5523 /// Used when in C++, as a GCC extension.
5524 QualType ASTContext::getSignedWCharType() const {
5525 // FIXME: derive from "Target" ?
5529 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5530 /// Used when in C++, as a GCC extension.
5531 QualType ASTContext::getUnsignedWCharType() const {
5532 // FIXME: derive from "Target" ?
5533 return UnsignedIntTy;
5536 QualType ASTContext::getIntPtrType() const {
5537 return getFromTargetType(Target->getIntPtrType());
5540 QualType ASTContext::getUIntPtrType() const {
5541 return getCorrespondingUnsignedType(getIntPtrType());
5544 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5545 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5546 QualType ASTContext::getPointerDiffType() const {
5547 return getFromTargetType(Target->getPtrDiffType(0));
5550 /// Return the unique unsigned counterpart of "ptrdiff_t"
5551 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5552 /// in the definition of %tu format specifier.
5553 QualType ASTContext::getUnsignedPointerDiffType() const {
5554 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5557 /// Return the unique type for "pid_t" defined in
5558 /// <sys/types.h>. We need this to compute the correct type for vfork().
5559 QualType ASTContext::getProcessIDType() const {
5560 return getFromTargetType(Target->getProcessIDType());
5563 //===----------------------------------------------------------------------===//
5565 //===----------------------------------------------------------------------===//
5567 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5568 // Push qualifiers into arrays, and then discard any remaining
5570 T = getCanonicalType(T);
5571 T = getVariableArrayDecayedType(T);
5572 const Type *Ty = T.getTypePtr();
5574 if (isa<ArrayType>(Ty)) {
5575 Result = getArrayDecayedType(QualType(Ty,0));
5576 } else if (isa<FunctionType>(Ty)) {
5577 Result = getPointerType(QualType(Ty, 0));
5579 Result = QualType(Ty, 0);
5582 return CanQualType::CreateUnsafe(Result);
5585 QualType ASTContext::getUnqualifiedArrayType(QualType type,
5586 Qualifiers &quals) {
5587 SplitQualType splitType = type.getSplitUnqualifiedType();
5589 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5590 // the unqualified desugared type and then drops it on the floor.
5591 // We then have to strip that sugar back off with
5592 // getUnqualifiedDesugaredType(), which is silly.
5594 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5596 // If we don't have an array, just use the results in splitType.
5598 quals = splitType.Quals;
5599 return QualType(splitType.Ty, 0);
5602 // Otherwise, recurse on the array's element type.
5603 QualType elementType = AT->getElementType();
5604 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5606 // If that didn't change the element type, AT has no qualifiers, so we
5607 // can just use the results in splitType.
5608 if (elementType == unqualElementType) {
5609 assert(quals.empty()); // from the recursive call
5610 quals = splitType.Quals;
5611 return QualType(splitType.Ty, 0);
5614 // Otherwise, add in the qualifiers from the outermost type, then
5615 // build the type back up.
5616 quals.addConsistentQualifiers(splitType.Quals);
5618 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5619 return getConstantArrayType(unqualElementType, CAT->getSize(),
5620 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
5623 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5624 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5627 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5628 return getVariableArrayType(unqualElementType,
5630 VAT->getSizeModifier(),
5631 VAT->getIndexTypeCVRQualifiers(),
5632 VAT->getBracketsRange());
5635 const auto *DSAT = cast<DependentSizedArrayType>(AT);
5636 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5637 DSAT->getSizeModifier(), 0,
5641 /// Attempt to unwrap two types that may both be array types with the same bound
5642 /// (or both be array types of unknown bound) for the purpose of comparing the
5643 /// cv-decomposition of two types per C++ [conv.qual].
5644 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5645 bool UnwrappedAny = false;
5647 auto *AT1 = getAsArrayType(T1);
5648 if (!AT1) return UnwrappedAny;
5650 auto *AT2 = getAsArrayType(T2);
5651 if (!AT2) return UnwrappedAny;
5653 // If we don't have two array types with the same constant bound nor two
5654 // incomplete array types, we've unwrapped everything we can.
5655 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5656 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5657 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
5658 return UnwrappedAny;
5659 } else if (!isa<IncompleteArrayType>(AT1) ||
5660 !isa<IncompleteArrayType>(AT2)) {
5661 return UnwrappedAny;
5664 T1 = AT1->getElementType();
5665 T2 = AT2->getElementType();
5666 UnwrappedAny = true;
5670 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5672 /// If T1 and T2 are both pointer types of the same kind, or both array types
5673 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5674 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5676 /// This function will typically be called in a loop that successively
5677 /// "unwraps" pointer and pointer-to-member types to compare them at each
5680 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
5681 /// pair of types that can't be unwrapped further.
5682 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
5683 UnwrapSimilarArrayTypes(T1, T2);
5685 const auto *T1PtrType = T1->getAs<PointerType>();
5686 const auto *T2PtrType = T2->getAs<PointerType>();
5687 if (T1PtrType && T2PtrType) {
5688 T1 = T1PtrType->getPointeeType();
5689 T2 = T2PtrType->getPointeeType();
5693 const auto *T1MPType = T1->getAs<MemberPointerType>();
5694 const auto *T2MPType = T2->getAs<MemberPointerType>();
5695 if (T1MPType && T2MPType &&
5696 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
5697 QualType(T2MPType->getClass(), 0))) {
5698 T1 = T1MPType->getPointeeType();
5699 T2 = T2MPType->getPointeeType();
5703 if (getLangOpts().ObjC) {
5704 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5705 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
5706 if (T1OPType && T2OPType) {
5707 T1 = T1OPType->getPointeeType();
5708 T2 = T2OPType->getPointeeType();
5713 // FIXME: Block pointers, too?
5718 bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5721 T1 = getUnqualifiedArrayType(T1, Quals);
5722 T2 = getUnqualifiedArrayType(T2, Quals);
5723 if (hasSameType(T1, T2))
5725 if (!UnwrapSimilarTypes(T1, T2))
5730 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5732 Qualifiers Quals1, Quals2;
5733 T1 = getUnqualifiedArrayType(T1, Quals1);
5734 T2 = getUnqualifiedArrayType(T2, Quals2);
5736 Quals1.removeCVRQualifiers();
5737 Quals2.removeCVRQualifiers();
5738 if (Quals1 != Quals2)
5741 if (hasSameType(T1, T2))
5744 if (!UnwrapSimilarTypes(T1, T2))
5750 ASTContext::getNameForTemplate(TemplateName Name,
5751 SourceLocation NameLoc) const {
5752 switch (Name.getKind()) {
5753 case TemplateName::QualifiedTemplate:
5754 case TemplateName::Template:
5755 // DNInfo work in progress: CHECKME: what about DNLoc?
5756 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5759 case TemplateName::OverloadedTemplate: {
5760 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5761 // DNInfo work in progress: CHECKME: what about DNLoc?
5762 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5765 case TemplateName::AssumedTemplate: {
5766 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5767 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5770 case TemplateName::DependentTemplate: {
5771 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5772 DeclarationName DName;
5773 if (DTN->isIdentifier()) {
5774 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5775 return DeclarationNameInfo(DName, NameLoc);
5777 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5778 // DNInfo work in progress: FIXME: source locations?
5779 DeclarationNameLoc DNLoc;
5780 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5781 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5782 return DeclarationNameInfo(DName, NameLoc, DNLoc);
5786 case TemplateName::SubstTemplateTemplateParm: {
5787 SubstTemplateTemplateParmStorage *subst
5788 = Name.getAsSubstTemplateTemplateParm();
5789 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5793 case TemplateName::SubstTemplateTemplateParmPack: {
5794 SubstTemplateTemplateParmPackStorage *subst
5795 = Name.getAsSubstTemplateTemplateParmPack();
5796 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5801 llvm_unreachable("bad template name kind!");
5804 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
5805 switch (Name.getKind()) {
5806 case TemplateName::QualifiedTemplate:
5807 case TemplateName::Template: {
5808 TemplateDecl *Template = Name.getAsTemplateDecl();
5809 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
5810 Template = getCanonicalTemplateTemplateParmDecl(TTP);
5812 // The canonical template name is the canonical template declaration.
5813 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
5816 case TemplateName::OverloadedTemplate:
5817 case TemplateName::AssumedTemplate:
5818 llvm_unreachable("cannot canonicalize unresolved template");
5820 case TemplateName::DependentTemplate: {
5821 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5822 assert(DTN && "Non-dependent template names must refer to template decls.");
5823 return DTN->CanonicalTemplateName;
5826 case TemplateName::SubstTemplateTemplateParm: {
5827 SubstTemplateTemplateParmStorage *subst
5828 = Name.getAsSubstTemplateTemplateParm();
5829 return getCanonicalTemplateName(subst->getReplacement());
5832 case TemplateName::SubstTemplateTemplateParmPack: {
5833 SubstTemplateTemplateParmPackStorage *subst
5834 = Name.getAsSubstTemplateTemplateParmPack();
5835 TemplateTemplateParmDecl *canonParameter
5836 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5837 TemplateArgument canonArgPack
5838 = getCanonicalTemplateArgument(subst->getArgumentPack());
5839 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5843 llvm_unreachable("bad template name!");
5846 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5847 X = getCanonicalTemplateName(X);
5848 Y = getCanonicalTemplateName(Y);
5849 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5853 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
5854 switch (Arg.getKind()) {
5855 case TemplateArgument::Null:
5858 case TemplateArgument::Expression:
5861 case TemplateArgument::Declaration: {
5862 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
5863 return TemplateArgument(D, Arg.getParamTypeForDecl());
5866 case TemplateArgument::NullPtr:
5867 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5870 case TemplateArgument::Template:
5871 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
5873 case TemplateArgument::TemplateExpansion:
5874 return TemplateArgument(getCanonicalTemplateName(
5875 Arg.getAsTemplateOrTemplatePattern()),
5876 Arg.getNumTemplateExpansions());
5878 case TemplateArgument::Integral:
5879 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
5881 case TemplateArgument::Type:
5882 return TemplateArgument(getCanonicalType(Arg.getAsType()));
5884 case TemplateArgument::Pack: {
5885 if (Arg.pack_size() == 0)
5888 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
5890 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
5891 AEnd = Arg.pack_end();
5892 A != AEnd; (void)++A, ++Idx)
5893 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
5895 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
5899 // Silence GCC warning
5900 llvm_unreachable("Unhandled template argument kind");
5903 NestedNameSpecifier *
5904 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
5908 switch (NNS->getKind()) {
5909 case NestedNameSpecifier::Identifier:
5910 // Canonicalize the prefix but keep the identifier the same.
5911 return NestedNameSpecifier::Create(*this,
5912 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5913 NNS->getAsIdentifier());
5915 case NestedNameSpecifier::Namespace:
5916 // A namespace is canonical; build a nested-name-specifier with
5917 // this namespace and no prefix.
5918 return NestedNameSpecifier::Create(*this, nullptr,
5919 NNS->getAsNamespace()->getOriginalNamespace());
5921 case NestedNameSpecifier::NamespaceAlias:
5922 // A namespace is canonical; build a nested-name-specifier with
5923 // this namespace and no prefix.
5924 return NestedNameSpecifier::Create(*this, nullptr,
5925 NNS->getAsNamespaceAlias()->getNamespace()
5926 ->getOriginalNamespace());
5928 case NestedNameSpecifier::TypeSpec:
5929 case NestedNameSpecifier::TypeSpecWithTemplate: {
5930 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
5932 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5933 // break it apart into its prefix and identifier, then reconsititute those
5934 // as the canonical nested-name-specifier. This is required to canonicalize
5935 // a dependent nested-name-specifier involving typedefs of dependent-name
5937 // typedef typename T::type T1;
5938 // typedef typename T1::type T2;
5939 if (const auto *DNT = T->getAs<DependentNameType>())
5940 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
5941 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
5943 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5944 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5946 return NestedNameSpecifier::Create(*this, nullptr, false,
5947 const_cast<Type *>(T.getTypePtr()));
5950 case NestedNameSpecifier::Global:
5951 case NestedNameSpecifier::Super:
5952 // The global specifier and __super specifer are canonical and unique.
5956 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5959 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
5960 // Handle the non-qualified case efficiently.
5961 if (!T.hasLocalQualifiers()) {
5962 // Handle the common positive case fast.
5963 if (const auto *AT = dyn_cast<ArrayType>(T))
5967 // Handle the common negative case fast.
5968 if (!isa<ArrayType>(T.getCanonicalType()))
5971 // Apply any qualifiers from the array type to the element type. This
5972 // implements C99 6.7.3p8: "If the specification of an array type includes
5973 // any type qualifiers, the element type is so qualified, not the array type."
5975 // If we get here, we either have type qualifiers on the type, or we have
5976 // sugar such as a typedef in the way. If we have type qualifiers on the type
5977 // we must propagate them down into the element type.
5979 SplitQualType split = T.getSplitDesugaredType();
5980 Qualifiers qs = split.Quals;
5982 // If we have a simple case, just return now.
5983 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
5984 if (!ATy || qs.empty())
5987 // Otherwise, we have an array and we have qualifiers on it. Push the
5988 // qualifiers into the array element type and return a new array type.
5989 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
5991 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
5992 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5994 CAT->getSizeModifier(),
5995 CAT->getIndexTypeCVRQualifiers()));
5996 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
5997 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5998 IAT->getSizeModifier(),
5999 IAT->getIndexTypeCVRQualifiers()));
6001 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6002 return cast<ArrayType>(
6003 getDependentSizedArrayType(NewEltTy,
6004 DSAT->getSizeExpr(),
6005 DSAT->getSizeModifier(),
6006 DSAT->getIndexTypeCVRQualifiers(),
6007 DSAT->getBracketsRange()));
6009 const auto *VAT = cast<VariableArrayType>(ATy);
6010 return cast<ArrayType>(getVariableArrayType(NewEltTy,
6012 VAT->getSizeModifier(),
6013 VAT->getIndexTypeCVRQualifiers(),
6014 VAT->getBracketsRange()));
6017 QualType ASTContext::getAdjustedParameterType(QualType T) const {
6018 if (T->isArrayType() || T->isFunctionType())
6019 return getDecayedType(T);
6023 QualType ASTContext::getSignatureParameterType(QualType T) const {
6024 T = getVariableArrayDecayedType(T);
6025 T = getAdjustedParameterType(T);
6026 return T.getUnqualifiedType();
6029 QualType ASTContext::getExceptionObjectType(QualType T) const {
6030 // C++ [except.throw]p3:
6031 // A throw-expression initializes a temporary object, called the exception
6032 // object, the type of which is determined by removing any top-level
6033 // cv-qualifiers from the static type of the operand of throw and adjusting
6034 // the type from "array of T" or "function returning T" to "pointer to T"
6035 // or "pointer to function returning T", [...]
6036 T = getVariableArrayDecayedType(T);
6037 if (T->isArrayType() || T->isFunctionType())
6038 T = getDecayedType(T);
6039 return T.getUnqualifiedType();
6042 /// getArrayDecayedType - Return the properly qualified result of decaying the
6043 /// specified array type to a pointer. This operation is non-trivial when
6044 /// handling typedefs etc. The canonical type of "T" must be an array type,
6045 /// this returns a pointer to a properly qualified element of the array.
6047 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
6048 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
6049 // Get the element type with 'getAsArrayType' so that we don't lose any
6050 // typedefs in the element type of the array. This also handles propagation
6051 // of type qualifiers from the array type into the element type if present
6053 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
6054 assert(PrettyArrayType && "Not an array type!");
6056 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
6058 // int x[restrict 4] -> int *restrict
6059 QualType Result = getQualifiedType(PtrTy,
6060 PrettyArrayType->getIndexTypeQualifiers());
6062 // int x[_Nullable] -> int * _Nullable
6063 if (auto Nullability = Ty->getNullability(*this)) {
6064 Result = const_cast<ASTContext *>(this)->getAttributedType(
6065 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
6070 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
6071 return getBaseElementType(array->getElementType());
6074 QualType ASTContext::getBaseElementType(QualType type) const {
6077 SplitQualType split = type.getSplitDesugaredType();
6078 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
6081 type = array->getElementType();
6082 qs.addConsistentQualifiers(split.Quals);
6085 return getQualifiedType(type, qs);
6088 /// getConstantArrayElementCount - Returns number of constant array elements.
6090 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
6091 uint64_t ElementCount = 1;
6093 ElementCount *= CA->getSize().getZExtValue();
6094 CA = dyn_cast_or_null<ConstantArrayType>(
6095 CA->getElementType()->getAsArrayTypeUnsafe());
6097 return ElementCount;
6100 /// getFloatingRank - Return a relative rank for floating point types.
6101 /// This routine will assert if passed a built-in type that isn't a float.
6102 static FloatingRank getFloatingRank(QualType T) {
6103 if (const auto *CT = T->getAs<ComplexType>())
6104 return getFloatingRank(CT->getElementType());
6106 switch (T->castAs<BuiltinType>()->getKind()) {
6107 default: llvm_unreachable("getFloatingRank(): not a floating type");
6108 case BuiltinType::Float16: return Float16Rank;
6109 case BuiltinType::Half: return HalfRank;
6110 case BuiltinType::Float: return FloatRank;
6111 case BuiltinType::Double: return DoubleRank;
6112 case BuiltinType::LongDouble: return LongDoubleRank;
6113 case BuiltinType::Float128: return Float128Rank;
6114 case BuiltinType::BFloat16: return BFloat16Rank;
6118 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
6119 /// point or a complex type (based on typeDomain/typeSize).
6120 /// 'typeDomain' is a real floating point or complex type.
6121 /// 'typeSize' is a real floating point or complex type.
6122 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
6123 QualType Domain) const {
6124 FloatingRank EltRank = getFloatingRank(Size);
6125 if (Domain->isComplexType()) {
6127 case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported");
6129 case HalfRank: llvm_unreachable("Complex half is not supported");
6130 case FloatRank: return FloatComplexTy;
6131 case DoubleRank: return DoubleComplexTy;
6132 case LongDoubleRank: return LongDoubleComplexTy;
6133 case Float128Rank: return Float128ComplexTy;
6137 assert(Domain->isRealFloatingType() && "Unknown domain!");
6139 case Float16Rank: return HalfTy;
6140 case BFloat16Rank: return BFloat16Ty;
6141 case HalfRank: return HalfTy;
6142 case FloatRank: return FloatTy;
6143 case DoubleRank: return DoubleTy;
6144 case LongDoubleRank: return LongDoubleTy;
6145 case Float128Rank: return Float128Ty;
6147 llvm_unreachable("getFloatingRank(): illegal value for rank");
6150 /// getFloatingTypeOrder - Compare the rank of the two specified floating
6151 /// point types, ignoring the domain of the type (i.e. 'double' ==
6152 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
6153 /// LHS < RHS, return -1.
6154 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
6155 FloatingRank LHSR = getFloatingRank(LHS);
6156 FloatingRank RHSR = getFloatingRank(RHS);
6165 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
6166 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
6168 return getFloatingTypeOrder(LHS, RHS);
6171 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
6172 /// routine will assert if passed a built-in type that isn't an integer or enum,
6173 /// or if it is not canonicalized.
6174 unsigned ASTContext::getIntegerRank(const Type *T) const {
6175 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
6177 // Results in this 'losing' to any type of the same size, but winning if
6179 if (const auto *EIT = dyn_cast<ExtIntType>(T))
6180 return 0 + (EIT->getNumBits() << 3);
6182 switch (cast<BuiltinType>(T)->getKind()) {
6183 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
6184 case BuiltinType::Bool:
6185 return 1 + (getIntWidth(BoolTy) << 3);
6186 case BuiltinType::Char_S:
6187 case BuiltinType::Char_U:
6188 case BuiltinType::SChar:
6189 case BuiltinType::UChar:
6190 return 2 + (getIntWidth(CharTy) << 3);
6191 case BuiltinType::Short:
6192 case BuiltinType::UShort:
6193 return 3 + (getIntWidth(ShortTy) << 3);
6194 case BuiltinType::Int:
6195 case BuiltinType::UInt:
6196 return 4 + (getIntWidth(IntTy) << 3);
6197 case BuiltinType::Long:
6198 case BuiltinType::ULong:
6199 return 5 + (getIntWidth(LongTy) << 3);
6200 case BuiltinType::LongLong:
6201 case BuiltinType::ULongLong:
6202 return 6 + (getIntWidth(LongLongTy) << 3);
6203 case BuiltinType::Int128:
6204 case BuiltinType::UInt128:
6205 return 7 + (getIntWidth(Int128Ty) << 3);
6209 /// Whether this is a promotable bitfield reference according
6210 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
6212 /// \returns the type this bit-field will promote to, or NULL if no
6213 /// promotion occurs.
6214 QualType ASTContext::isPromotableBitField(Expr *E) const {
6215 if (E->isTypeDependent() || E->isValueDependent())
6218 // C++ [conv.prom]p5:
6219 // If the bit-field has an enumerated type, it is treated as any other
6220 // value of that type for promotion purposes.
6221 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
6224 // FIXME: We should not do this unless E->refersToBitField() is true. This
6225 // matters in C where getSourceBitField() will find bit-fields for various
6226 // cases where the source expression is not a bit-field designator.
6228 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
6232 QualType FT = Field->getType();
6234 uint64_t BitWidth = Field->getBitWidthValue(*this);
6235 uint64_t IntSize = getTypeSize(IntTy);
6236 // C++ [conv.prom]p5:
6237 // A prvalue for an integral bit-field can be converted to a prvalue of type
6238 // int if int can represent all the values of the bit-field; otherwise, it
6239 // can be converted to unsigned int if unsigned int can represent all the
6240 // values of the bit-field. If the bit-field is larger yet, no integral
6241 // promotion applies to it.
6243 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
6244 // If an int can represent all values of the original type (as restricted by
6245 // the width, for a bit-field), the value is converted to an int; otherwise,
6246 // it is converted to an unsigned int.
6248 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
6249 // We perform that promotion here to match GCC and C++.
6250 // FIXME: C does not permit promotion of an enum bit-field whose rank is
6251 // greater than that of 'int'. We perform that promotion to match GCC.
6252 if (BitWidth < IntSize)
6255 if (BitWidth == IntSize)
6256 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
6258 // Bit-fields wider than int are not subject to promotions, and therefore act
6259 // like the base type. GCC has some weird bugs in this area that we
6260 // deliberately do not follow (GCC follows a pre-standard resolution to
6261 // C's DR315 which treats bit-width as being part of the type, and this leaks
6262 // into their semantics in some cases).
6266 /// getPromotedIntegerType - Returns the type that Promotable will
6267 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
6269 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
6270 assert(!Promotable.isNull());
6271 assert(Promotable->isPromotableIntegerType());
6272 if (const auto *ET = Promotable->getAs<EnumType>())
6273 return ET->getDecl()->getPromotionType();
6275 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
6276 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
6277 // (3.9.1) can be converted to a prvalue of the first of the following
6278 // types that can represent all the values of its underlying type:
6279 // int, unsigned int, long int, unsigned long int, long long int, or
6280 // unsigned long long int [...]
6281 // FIXME: Is there some better way to compute this?
6282 if (BT->getKind() == BuiltinType::WChar_S ||
6283 BT->getKind() == BuiltinType::WChar_U ||
6284 BT->getKind() == BuiltinType::Char8 ||
6285 BT->getKind() == BuiltinType::Char16 ||
6286 BT->getKind() == BuiltinType::Char32) {
6287 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
6288 uint64_t FromSize = getTypeSize(BT);
6289 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
6290 LongLongTy, UnsignedLongLongTy };
6291 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
6292 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
6293 if (FromSize < ToSize ||
6294 (FromSize == ToSize &&
6295 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
6296 return PromoteTypes[Idx];
6298 llvm_unreachable("char type should fit into long long");
6302 // At this point, we should have a signed or unsigned integer type.
6303 if (Promotable->isSignedIntegerType())
6305 uint64_t PromotableSize = getIntWidth(Promotable);
6306 uint64_t IntSize = getIntWidth(IntTy);
6307 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
6308 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
6311 /// Recurses in pointer/array types until it finds an objc retainable
6312 /// type and returns its ownership.
6313 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
6314 while (!T.isNull()) {
6315 if (T.getObjCLifetime() != Qualifiers::OCL_None)
6316 return T.getObjCLifetime();
6317 if (T->isArrayType())
6318 T = getBaseElementType(T);
6319 else if (const auto *PT = T->getAs<PointerType>())
6320 T = PT->getPointeeType();
6321 else if (const auto *RT = T->getAs<ReferenceType>())
6322 T = RT->getPointeeType();
6327 return Qualifiers::OCL_None;
6330 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
6331 // Incomplete enum types are not treated as integer types.
6332 // FIXME: In C++, enum types are never integer types.
6333 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
6334 return ET->getDecl()->getIntegerType().getTypePtr();
6338 /// getIntegerTypeOrder - Returns the highest ranked integer type:
6339 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
6340 /// LHS < RHS, return -1.
6341 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
6342 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
6343 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
6345 // Unwrap enums to their underlying type.
6346 if (const auto *ET = dyn_cast<EnumType>(LHSC))
6347 LHSC = getIntegerTypeForEnum(ET);
6348 if (const auto *ET = dyn_cast<EnumType>(RHSC))
6349 RHSC = getIntegerTypeForEnum(ET);
6351 if (LHSC == RHSC) return 0;
6353 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
6354 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
6356 unsigned LHSRank = getIntegerRank(LHSC);
6357 unsigned RHSRank = getIntegerRank(RHSC);
6359 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
6360 if (LHSRank == RHSRank) return 0;
6361 return LHSRank > RHSRank ? 1 : -1;
6364 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
6366 // If the unsigned [LHS] type is larger, return it.
6367 if (LHSRank >= RHSRank)
6370 // If the signed type can represent all values of the unsigned type, it
6371 // wins. Because we are dealing with 2's complement and types that are
6372 // powers of two larger than each other, this is always safe.
6376 // If the unsigned [RHS] type is larger, return it.
6377 if (RHSRank >= LHSRank)
6380 // If the signed type can represent all values of the unsigned type, it
6381 // wins. Because we are dealing with 2's complement and types that are
6382 // powers of two larger than each other, this is always safe.
6386 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
6387 if (CFConstantStringTypeDecl)
6388 return CFConstantStringTypeDecl;
6390 assert(!CFConstantStringTagDecl &&
6391 "tag and typedef should be initialized together");
6392 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
6393 CFConstantStringTagDecl->startDefinition();
6403 /// typedef struct __NSConstantString_tag {
6406 /// const char *str;
6408 /// } __NSConstantString;
6410 /// Swift ABI (4.1, 4.2)
6412 /// typedef struct __NSConstantString_tag {
6413 /// uintptr_t _cfisa;
6414 /// uintptr_t _swift_rc;
6415 /// _Atomic(uint64_t) _cfinfoa;
6416 /// const char *_ptr;
6417 /// uint32_t _length;
6418 /// } __NSConstantString;
6422 /// typedef struct __NSConstantString_tag {
6423 /// uintptr_t _cfisa;
6424 /// uintptr_t _swift_rc;
6425 /// _Atomic(uint64_t) _cfinfoa;
6426 /// const char *_ptr;
6427 /// uintptr_t _length;
6428 /// } __NSConstantString;
6430 const auto CFRuntime = getLangOpts().CFRuntime;
6431 if (static_cast<unsigned>(CFRuntime) <
6432 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
6433 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
6434 Fields[Count++] = { IntTy, "flags" };
6435 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
6436 Fields[Count++] = { LongTy, "length" };
6438 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
6439 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6440 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6441 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6442 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6443 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6444 Fields[Count++] = { IntTy, "_ptr" };
6446 Fields[Count++] = { getUIntPtrType(), "_ptr" };
6450 for (unsigned i = 0; i < Count; ++i) {
6452 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
6453 SourceLocation(), &Idents.get(Fields[i].Name),
6454 Fields[i].Type, /*TInfo=*/nullptr,
6455 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6456 Field->setAccess(AS_public);
6457 CFConstantStringTagDecl->addDecl(Field);
6460 CFConstantStringTagDecl->completeDefinition();
6461 // This type is designed to be compatible with NSConstantString, but cannot
6462 // use the same name, since NSConstantString is an interface.
6463 auto tagType = getTagDeclType(CFConstantStringTagDecl);
6464 CFConstantStringTypeDecl =
6465 buildImplicitTypedef(tagType, "__NSConstantString");
6467 return CFConstantStringTypeDecl;
6470 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
6471 if (!CFConstantStringTagDecl)
6472 getCFConstantStringDecl(); // Build the tag and the typedef.
6473 return CFConstantStringTagDecl;
6476 // getCFConstantStringType - Return the type used for constant CFStrings.
6477 QualType ASTContext::getCFConstantStringType() const {
6478 return getTypedefType(getCFConstantStringDecl());
6481 QualType ASTContext::getObjCSuperType() const {
6482 if (ObjCSuperType.isNull()) {
6483 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
6484 TUDecl->addDecl(ObjCSuperTypeDecl);
6485 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6487 return ObjCSuperType;
6490 void ASTContext::setCFConstantStringType(QualType T) {
6491 const auto *TD = T->castAs<TypedefType>();
6492 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
6493 const auto *TagType =
6494 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
6495 CFConstantStringTagDecl = TagType->getDecl();
6498 QualType ASTContext::getBlockDescriptorType() const {
6499 if (BlockDescriptorType)
6500 return getTagDeclType(BlockDescriptorType);
6503 // FIXME: Needs the FlagAppleBlock bit.
6504 RD = buildImplicitRecord("__block_descriptor");
6505 RD->startDefinition();
6507 QualType FieldTypes[] = {
6512 static const char *const FieldNames[] = {
6517 for (size_t i = 0; i < 2; ++i) {
6518 FieldDecl *Field = FieldDecl::Create(
6519 *this, RD, SourceLocation(), SourceLocation(),
6520 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6521 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6522 Field->setAccess(AS_public);
6526 RD->completeDefinition();
6528 BlockDescriptorType = RD;
6530 return getTagDeclType(BlockDescriptorType);
6533 QualType ASTContext::getBlockDescriptorExtendedType() const {
6534 if (BlockDescriptorExtendedType)
6535 return getTagDeclType(BlockDescriptorExtendedType);
6538 // FIXME: Needs the FlagAppleBlock bit.
6539 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6540 RD->startDefinition();
6542 QualType FieldTypes[] = {
6545 getPointerType(VoidPtrTy),
6546 getPointerType(VoidPtrTy)
6549 static const char *const FieldNames[] = {
6556 for (size_t i = 0; i < 4; ++i) {
6557 FieldDecl *Field = FieldDecl::Create(
6558 *this, RD, SourceLocation(), SourceLocation(),
6559 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6560 /*BitWidth=*/nullptr,
6561 /*Mutable=*/false, ICIS_NoInit);
6562 Field->setAccess(AS_public);
6566 RD->completeDefinition();
6568 BlockDescriptorExtendedType = RD;
6569 return getTagDeclType(BlockDescriptorExtendedType);
6572 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
6573 const auto *BT = dyn_cast<BuiltinType>(T);
6576 if (isa<PipeType>(T))
6579 return OCLTK_Default;
6582 switch (BT->getKind()) {
6583 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6584 case BuiltinType::Id: \
6586 #include "clang/Basic/OpenCLImageTypes.def"
6588 case BuiltinType::OCLClkEvent:
6589 return OCLTK_ClkEvent;
6591 case BuiltinType::OCLEvent:
6594 case BuiltinType::OCLQueue:
6597 case BuiltinType::OCLReserveID:
6598 return OCLTK_ReserveID;
6600 case BuiltinType::OCLSampler:
6601 return OCLTK_Sampler;
6604 return OCLTK_Default;
6608 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6609 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6612 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6613 /// requires copy/dispose. Note that this must match the logic
6614 /// in buildByrefHelpers.
6615 bool ASTContext::BlockRequiresCopying(QualType Ty,
6617 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
6618 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
6619 if (!copyExpr && record->hasTrivialDestructor()) return false;
6624 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6626 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6629 if (!Ty->isObjCRetainableType()) return false;
6631 Qualifiers qs = Ty.getQualifiers();
6633 // If we have lifetime, that dominates.
6634 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
6636 case Qualifiers::OCL_None: llvm_unreachable("impossible");
6638 // These are just bits as far as the runtime is concerned.
6639 case Qualifiers::OCL_ExplicitNone:
6640 case Qualifiers::OCL_Autoreleasing:
6643 // These cases should have been taken care of when checking the type's
6645 case Qualifiers::OCL_Weak:
6646 case Qualifiers::OCL_Strong:
6647 llvm_unreachable("impossible");
6649 llvm_unreachable("fell out of lifetime switch!");
6651 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6652 Ty->isObjCObjectPointerType());
6655 bool ASTContext::getByrefLifetime(QualType Ty,
6656 Qualifiers::ObjCLifetime &LifeTime,
6657 bool &HasByrefExtendedLayout) const {
6658 if (!getLangOpts().ObjC ||
6659 getLangOpts().getGC() != LangOptions::NonGC)
6662 HasByrefExtendedLayout = false;
6663 if (Ty->isRecordType()) {
6664 HasByrefExtendedLayout = true;
6665 LifeTime = Qualifiers::OCL_None;
6666 } else if ((LifeTime = Ty.getObjCLifetime())) {
6667 // Honor the ARC qualifiers.
6668 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6670 LifeTime = Qualifiers::OCL_ExplicitNone;
6672 LifeTime = Qualifiers::OCL_None;
6677 CanQualType ASTContext::getNSUIntegerType() const {
6678 assert(Target && "Expected target to be initialized");
6679 const llvm::Triple &T = Target->getTriple();
6680 // Windows is LLP64 rather than LP64
6681 if (T.isOSWindows() && T.isArch64Bit())
6682 return UnsignedLongLongTy;
6683 return UnsignedLongTy;
6686 CanQualType ASTContext::getNSIntegerType() const {
6687 assert(Target && "Expected target to be initialized");
6688 const llvm::Triple &T = Target->getTriple();
6689 // Windows is LLP64 rather than LP64
6690 if (T.isOSWindows() && T.isArch64Bit())
6695 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6696 if (!ObjCInstanceTypeDecl)
6697 ObjCInstanceTypeDecl =
6698 buildImplicitTypedef(getObjCIdType(), "instancetype");
6699 return ObjCInstanceTypeDecl;
6702 // This returns true if a type has been typedefed to BOOL:
6703 // typedef <type> BOOL;
6704 static bool isTypeTypedefedAsBOOL(QualType T) {
6705 if (const auto *TT = dyn_cast<TypedefType>(T))
6706 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6707 return II->isStr("BOOL");
6712 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
6714 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
6715 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6716 return CharUnits::Zero();
6718 CharUnits sz = getTypeSizeInChars(type);
6720 // Make all integer and enum types at least as large as an int
6721 if (sz.isPositive() && type->isIntegralOrEnumerationType())
6722 sz = std::max(sz, getTypeSizeInChars(IntTy));
6723 // Treat arrays as pointers, since that's how they're passed in.
6724 else if (type->isArrayType())
6725 sz = getTypeSizeInChars(VoidPtrTy);
6729 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
6730 return getTargetInfo().getCXXABI().isMicrosoft() &&
6731 VD->isStaticDataMember() &&
6732 VD->getType()->isIntegralOrEnumerationType() &&
6733 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
6736 ASTContext::InlineVariableDefinitionKind
6737 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6738 if (!VD->isInline())
6739 return InlineVariableDefinitionKind::None;
6741 // In almost all cases, it's a weak definition.
6742 auto *First = VD->getFirstDecl();
6743 if (First->isInlineSpecified() || !First->isStaticDataMember())
6744 return InlineVariableDefinitionKind::Weak;
6746 // If there's a file-context declaration in this translation unit, it's a
6747 // non-discardable definition.
6748 for (auto *D : VD->redecls())
6749 if (D->getLexicalDeclContext()->isFileContext() &&
6750 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
6751 return InlineVariableDefinitionKind::Strong;
6753 // If we've not seen one yet, we don't know.
6754 return InlineVariableDefinitionKind::WeakUnknown;
6757 static std::string charUnitsToString(const CharUnits &CU) {
6758 return llvm::itostr(CU.getQuantity());
6761 /// getObjCEncodingForBlock - Return the encoded type for this block
6763 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6766 const BlockDecl *Decl = Expr->getBlockDecl();
6768 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
6769 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
6770 // Encode result type.
6771 if (getLangOpts().EncodeExtendedBlockSig)
6772 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
6775 getObjCEncodingForType(BlockReturnTy, S);
6776 // Compute size of all parameters.
6777 // Start with computing size of a pointer in number of bytes.
6778 // FIXME: There might(should) be a better way of doing this computation!
6779 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6780 CharUnits ParmOffset = PtrSize;
6781 for (auto PI : Decl->parameters()) {
6782 QualType PType = PI->getType();
6783 CharUnits sz = getObjCEncodingTypeSize(PType);
6786 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
6789 // Size of the argument frame
6790 S += charUnitsToString(ParmOffset);
6791 // Block pointer and offset.
6795 ParmOffset = PtrSize;
6796 for (auto PVDecl : Decl->parameters()) {
6797 QualType PType = PVDecl->getOriginalType();
6798 if (const auto *AT =
6799 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6800 // Use array's original type only if it has known number of
6802 if (!isa<ConstantArrayType>(AT))
6803 PType = PVDecl->getType();
6804 } else if (PType->isFunctionType())
6805 PType = PVDecl->getType();
6806 if (getLangOpts().EncodeExtendedBlockSig)
6807 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6808 S, true /*Extended*/);
6810 getObjCEncodingForType(PType, S);
6811 S += charUnitsToString(ParmOffset);
6812 ParmOffset += getObjCEncodingTypeSize(PType);
6819 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6821 // Encode result type.
6822 getObjCEncodingForType(Decl->getReturnType(), S);
6823 CharUnits ParmOffset;
6824 // Compute size of all parameters.
6825 for (auto PI : Decl->parameters()) {
6826 QualType PType = PI->getType();
6827 CharUnits sz = getObjCEncodingTypeSize(PType);
6831 assert(sz.isPositive() &&
6832 "getObjCEncodingForFunctionDecl - Incomplete param type");
6835 S += charUnitsToString(ParmOffset);
6836 ParmOffset = CharUnits::Zero();
6839 for (auto PVDecl : Decl->parameters()) {
6840 QualType PType = PVDecl->getOriginalType();
6841 if (const auto *AT =
6842 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6843 // Use array's original type only if it has known number of
6845 if (!isa<ConstantArrayType>(AT))
6846 PType = PVDecl->getType();
6847 } else if (PType->isFunctionType())
6848 PType = PVDecl->getType();
6849 getObjCEncodingForType(PType, S);
6850 S += charUnitsToString(ParmOffset);
6851 ParmOffset += getObjCEncodingTypeSize(PType);
6857 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
6858 /// method parameter or return type. If Extended, include class names and
6859 /// block object types.
6860 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6861 QualType T, std::string& S,
6862 bool Extended) const {
6863 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6864 getObjCEncodingForTypeQualifier(QT, S);
6865 // Encode parameter type.
6866 ObjCEncOptions Options = ObjCEncOptions()
6867 .setExpandPointedToStructures()
6868 .setExpandStructures()
6869 .setIsOutermostType();
6871 Options.setEncodeBlockParameters().setEncodeClassNames();
6872 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
6875 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
6877 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6878 bool Extended) const {
6879 // FIXME: This is not very efficient.
6880 // Encode return type.
6882 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6883 Decl->getReturnType(), S, Extended);
6884 // Compute size of all parameters.
6885 // Start with computing size of a pointer in number of bytes.
6886 // FIXME: There might(should) be a better way of doing this computation!
6887 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6888 // The first two arguments (self and _cmd) are pointers; account for
6890 CharUnits ParmOffset = 2 * PtrSize;
6891 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
6892 E = Decl->sel_param_end(); PI != E; ++PI) {
6893 QualType PType = (*PI)->getType();
6894 CharUnits sz = getObjCEncodingTypeSize(PType);
6898 assert(sz.isPositive() &&
6899 "getObjCEncodingForMethodDecl - Incomplete param type");
6902 S += charUnitsToString(ParmOffset);
6904 S += charUnitsToString(PtrSize);
6907 ParmOffset = 2 * PtrSize;
6908 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
6909 E = Decl->sel_param_end(); PI != E; ++PI) {
6910 const ParmVarDecl *PVDecl = *PI;
6911 QualType PType = PVDecl->getOriginalType();
6912 if (const auto *AT =
6913 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6914 // Use array's original type only if it has known number of
6916 if (!isa<ConstantArrayType>(AT))
6917 PType = PVDecl->getType();
6918 } else if (PType->isFunctionType())
6919 PType = PVDecl->getType();
6920 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
6921 PType, S, Extended);
6922 S += charUnitsToString(ParmOffset);
6923 ParmOffset += getObjCEncodingTypeSize(PType);
6929 ObjCPropertyImplDecl *
6930 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6931 const ObjCPropertyDecl *PD,
6932 const Decl *Container) const {
6935 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
6936 for (auto *PID : CID->property_impls())
6937 if (PID->getPropertyDecl() == PD)
6940 const auto *OID = cast<ObjCImplementationDecl>(Container);
6941 for (auto *PID : OID->property_impls())
6942 if (PID->getPropertyDecl() == PD)
6948 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
6949 /// property declaration. If non-NULL, Container must be either an
6950 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6951 /// NULL when getting encodings for protocol properties.
6952 /// Property attributes are stored as a comma-delimited C string. The simple
6953 /// attributes readonly and bycopy are encoded as single characters. The
6954 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
6955 /// encoded as single characters, followed by an identifier. Property types
6956 /// are also encoded as a parametrized attribute. The characters used to encode
6957 /// these attributes are defined by the following enumeration:
6959 /// enum PropertyAttributes {
6960 /// kPropertyReadOnly = 'R', // property is read-only.
6961 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6962 /// kPropertyByref = '&', // property is a reference to the value last assigned
6963 /// kPropertyDynamic = 'D', // property is dynamic
6964 /// kPropertyGetter = 'G', // followed by getter selector name
6965 /// kPropertySetter = 'S', // followed by setter selector name
6966 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
6967 /// kPropertyType = 'T' // followed by old-style type encoding.
6968 /// kPropertyWeak = 'W' // 'weak' property
6969 /// kPropertyStrong = 'P' // property GC'able
6970 /// kPropertyNonAtomic = 'N' // property non-atomic
6974 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6975 const Decl *Container) const {
6976 // Collect information from the property implementation decl(s).
6977 bool Dynamic = false;
6978 ObjCPropertyImplDecl *SynthesizePID = nullptr;
6980 if (ObjCPropertyImplDecl *PropertyImpDecl =
6981 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6982 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6985 SynthesizePID = PropertyImpDecl;
6988 // FIXME: This is not very efficient.
6989 std::string S = "T";
6991 // Encode result type.
6992 // GCC has some special rules regarding encoding of properties which
6993 // closely resembles encoding of ivars.
6994 getObjCEncodingForPropertyType(PD->getType(), S);
6996 if (PD->isReadOnly()) {
6998 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
7000 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
7002 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
7005 switch (PD->getSetterKind()) {
7006 case ObjCPropertyDecl::Assign: break;
7007 case ObjCPropertyDecl::Copy: S += ",C"; break;
7008 case ObjCPropertyDecl::Retain: S += ",&"; break;
7009 case ObjCPropertyDecl::Weak: S += ",W"; break;
7013 // It really isn't clear at all what this means, since properties
7014 // are "dynamic by default".
7018 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
7021 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
7023 S += PD->getGetterName().getAsString();
7026 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
7028 S += PD->getSetterName().getAsString();
7031 if (SynthesizePID) {
7032 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
7034 S += OID->getNameAsString();
7037 // FIXME: OBJCGC: weak & strong
7041 /// getLegacyIntegralTypeEncoding -
7042 /// Another legacy compatibility encoding: 32-bit longs are encoded as
7043 /// 'l' or 'L' , but not always. For typedefs, we need to use
7044 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
7045 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
7046 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
7047 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
7048 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
7049 PointeeTy = UnsignedIntTy;
7051 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
7057 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
7058 const FieldDecl *Field,
7059 QualType *NotEncodedT) const {
7060 // We follow the behavior of gcc, expanding structures which are
7061 // directly pointed to, and expanding embedded structures. Note that
7062 // these rules are sufficient to prevent recursive encoding of the
7064 getObjCEncodingForTypeImpl(T, S,
7066 .setExpandPointedToStructures()
7067 .setExpandStructures()
7068 .setIsOutermostType(),
7069 Field, NotEncodedT);
7072 void ASTContext::getObjCEncodingForPropertyType(QualType T,
7073 std::string& S) const {
7074 // Encode result type.
7075 // GCC has some special rules regarding encoding of properties which
7076 // closely resembles encoding of ivars.
7077 getObjCEncodingForTypeImpl(T, S,
7079 .setExpandPointedToStructures()
7080 .setExpandStructures()
7081 .setIsOutermostType()
7082 .setEncodingProperty(),
7086 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
7087 const BuiltinType *BT) {
7088 BuiltinType::Kind kind = BT->getKind();
7090 case BuiltinType::Void: return 'v';
7091 case BuiltinType::Bool: return 'B';
7092 case BuiltinType::Char8:
7093 case BuiltinType::Char_U:
7094 case BuiltinType::UChar: return 'C';
7095 case BuiltinType::Char16:
7096 case BuiltinType::UShort: return 'S';
7097 case BuiltinType::Char32:
7098 case BuiltinType::UInt: return 'I';
7099 case BuiltinType::ULong:
7100 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
7101 case BuiltinType::UInt128: return 'T';
7102 case BuiltinType::ULongLong: return 'Q';
7103 case BuiltinType::Char_S:
7104 case BuiltinType::SChar: return 'c';
7105 case BuiltinType::Short: return 's';
7106 case BuiltinType::WChar_S:
7107 case BuiltinType::WChar_U:
7108 case BuiltinType::Int: return 'i';
7109 case BuiltinType::Long:
7110 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
7111 case BuiltinType::LongLong: return 'q';
7112 case BuiltinType::Int128: return 't';
7113 case BuiltinType::Float: return 'f';
7114 case BuiltinType::Double: return 'd';
7115 case BuiltinType::LongDouble: return 'D';
7116 case BuiltinType::NullPtr: return '*'; // like char*
7118 case BuiltinType::BFloat16:
7119 case BuiltinType::Float16:
7120 case BuiltinType::Float128:
7121 case BuiltinType::Half:
7122 case BuiltinType::ShortAccum:
7123 case BuiltinType::Accum:
7124 case BuiltinType::LongAccum:
7125 case BuiltinType::UShortAccum:
7126 case BuiltinType::UAccum:
7127 case BuiltinType::ULongAccum:
7128 case BuiltinType::ShortFract:
7129 case BuiltinType::Fract:
7130 case BuiltinType::LongFract:
7131 case BuiltinType::UShortFract:
7132 case BuiltinType::UFract:
7133 case BuiltinType::ULongFract:
7134 case BuiltinType::SatShortAccum:
7135 case BuiltinType::SatAccum:
7136 case BuiltinType::SatLongAccum:
7137 case BuiltinType::SatUShortAccum:
7138 case BuiltinType::SatUAccum:
7139 case BuiltinType::SatULongAccum:
7140 case BuiltinType::SatShortFract:
7141 case BuiltinType::SatFract:
7142 case BuiltinType::SatLongFract:
7143 case BuiltinType::SatUShortFract:
7144 case BuiltinType::SatUFract:
7145 case BuiltinType::SatULongFract:
7146 // FIXME: potentially need @encodes for these!
7149 #define SVE_TYPE(Name, Id, SingletonId) \
7150 case BuiltinType::Id:
7151 #include "clang/Basic/AArch64SVEACLETypes.def"
7153 DiagnosticsEngine &Diags = C->getDiagnostics();
7154 unsigned DiagID = Diags.getCustomDiagID(
7155 DiagnosticsEngine::Error, "cannot yet @encode type %0");
7156 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
7160 case BuiltinType::ObjCId:
7161 case BuiltinType::ObjCClass:
7162 case BuiltinType::ObjCSel:
7163 llvm_unreachable("@encoding ObjC primitive type");
7165 // OpenCL and placeholder types don't need @encodings.
7166 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7167 case BuiltinType::Id:
7168 #include "clang/Basic/OpenCLImageTypes.def"
7169 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7170 case BuiltinType::Id:
7171 #include "clang/Basic/OpenCLExtensionTypes.def"
7172 case BuiltinType::OCLEvent:
7173 case BuiltinType::OCLClkEvent:
7174 case BuiltinType::OCLQueue:
7175 case BuiltinType::OCLReserveID:
7176 case BuiltinType::OCLSampler:
7177 case BuiltinType::Dependent:
7178 #define BUILTIN_TYPE(KIND, ID)
7179 #define PLACEHOLDER_TYPE(KIND, ID) \
7180 case BuiltinType::KIND:
7181 #include "clang/AST/BuiltinTypes.def"
7182 llvm_unreachable("invalid builtin type for @encode");
7184 llvm_unreachable("invalid BuiltinType::Kind value");
7187 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
7188 EnumDecl *Enum = ET->getDecl();
7190 // The encoding of an non-fixed enum type is always 'i', regardless of size.
7191 if (!Enum->isFixed())
7194 // The encoding of a fixed enum type matches its fixed underlying type.
7195 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
7196 return getObjCEncodingForPrimitiveType(C, BT);
7199 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
7200 QualType T, const FieldDecl *FD) {
7201 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
7203 // The NeXT runtime encodes bit fields as b followed by the number of bits.
7204 // The GNU runtime requires more information; bitfields are encoded as b,
7205 // then the offset (in bits) of the first element, then the type of the
7206 // bitfield, then the size in bits. For example, in this structure:
7213 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
7214 // runtime, but b32i2 for the GNU runtime. The reason for this extra
7215 // information is not especially sensible, but we're stuck with it for
7216 // compatibility with GCC, although providing it breaks anything that
7217 // actually uses runtime introspection and wants to work on both runtimes...
7218 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
7221 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
7222 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
7225 const RecordDecl *RD = FD->getParent();
7226 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
7227 Offset = RL.getFieldOffset(FD->getFieldIndex());
7230 S += llvm::utostr(Offset);
7232 if (const auto *ET = T->getAs<EnumType>())
7233 S += ObjCEncodingForEnumType(Ctx, ET);
7235 const auto *BT = T->castAs<BuiltinType>();
7236 S += getObjCEncodingForPrimitiveType(Ctx, BT);
7239 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
7242 // FIXME: Use SmallString for accumulating string.
7243 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
7244 const ObjCEncOptions Options,
7245 const FieldDecl *FD,
7246 QualType *NotEncodedT) const {
7247 CanQualType CT = getCanonicalType(T);
7248 switch (CT->getTypeClass()) {
7251 if (FD && FD->isBitField())
7252 return EncodeBitField(this, S, T, FD);
7253 if (const auto *BT = dyn_cast<BuiltinType>(CT))
7254 S += getObjCEncodingForPrimitiveType(this, BT);
7256 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
7261 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
7268 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
7273 // encoding for pointer or reference types.
7275 case Type::LValueReference:
7276 case Type::RValueReference: {
7278 if (isa<PointerType>(CT)) {
7279 const auto *PT = T->castAs<PointerType>();
7280 if (PT->isObjCSelType()) {
7284 PointeeTy = PT->getPointeeType();
7286 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
7289 bool isReadOnly = false;
7290 // For historical/compatibility reasons, the read-only qualifier of the
7291 // pointee gets emitted _before_ the '^'. The read-only qualifier of
7292 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
7293 // Also, do not emit the 'r' for anything but the outermost type!
7294 if (isa<TypedefType>(T.getTypePtr())) {
7295 if (Options.IsOutermostType() && T.isConstQualified()) {
7299 } else if (Options.IsOutermostType()) {
7300 QualType P = PointeeTy;
7301 while (auto PT = P->getAs<PointerType>())
7302 P = PT->getPointeeType();
7303 if (P.isConstQualified()) {
7309 // Another legacy compatibility encoding. Some ObjC qualifier and type
7310 // combinations need to be rearranged.
7311 // Rewrite "in const" from "nr" to "rn"
7312 if (StringRef(S).endswith("nr"))
7313 S.replace(S.end()-2, S.end(), "rn");
7316 if (PointeeTy->isCharType()) {
7317 // char pointer types should be encoded as '*' unless it is a
7318 // type that has been typedef'd to 'BOOL'.
7319 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
7323 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
7324 // GCC binary compat: Need to convert "struct objc_class *" to "#".
7325 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
7329 // GCC binary compat: Need to convert "struct objc_object *" to "@".
7330 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
7337 getLegacyIntegralTypeEncoding(PointeeTy);
7339 ObjCEncOptions NewOptions;
7340 if (Options.ExpandPointedToStructures())
7341 NewOptions.setExpandStructures();
7342 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
7343 /*Field=*/nullptr, NotEncodedT);
7347 case Type::ConstantArray:
7348 case Type::IncompleteArray:
7349 case Type::VariableArray: {
7350 const auto *AT = cast<ArrayType>(CT);
7352 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
7353 // Incomplete arrays are encoded as a pointer to the array element.
7356 getObjCEncodingForTypeImpl(
7357 AT->getElementType(), S,
7358 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
7362 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
7363 S += llvm::utostr(CAT->getSize().getZExtValue());
7365 //Variable length arrays are encoded as a regular array with 0 elements.
7366 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
7367 "Unknown array type!");
7371 getObjCEncodingForTypeImpl(
7372 AT->getElementType(), S,
7373 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
7380 case Type::FunctionNoProto:
7381 case Type::FunctionProto:
7385 case Type::Record: {
7386 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
7387 S += RDecl->isUnion() ? '(' : '{';
7388 // Anonymous structures print as '?'
7389 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
7391 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
7392 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
7393 llvm::raw_string_ostream OS(S);
7394 printTemplateArgumentList(OS, TemplateArgs.asArray(),
7395 getPrintingPolicy());
7400 if (Options.ExpandStructures()) {
7402 if (!RDecl->isUnion()) {
7403 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
7405 for (const auto *Field : RDecl->fields()) {
7408 S += Field->getNameAsString();
7412 // Special case bit-fields.
7413 if (Field->isBitField()) {
7414 getObjCEncodingForTypeImpl(Field->getType(), S,
7415 ObjCEncOptions().setExpandStructures(),
7418 QualType qt = Field->getType();
7419 getLegacyIntegralTypeEncoding(qt);
7420 getObjCEncodingForTypeImpl(
7422 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
7428 S += RDecl->isUnion() ? ')' : '}';
7432 case Type::BlockPointer: {
7433 const auto *BT = T->castAs<BlockPointerType>();
7434 S += "@?"; // Unlike a pointer-to-function, which is "^?".
7435 if (Options.EncodeBlockParameters()) {
7436 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
7439 // Block return type
7440 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
7441 Options.forComponentType(), FD, NotEncodedT);
7445 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
7446 for (const auto &I : FPT->param_types())
7447 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
7455 case Type::ObjCObject: {
7456 // hack to match legacy encoding of *id and *Class
7457 QualType Ty = getObjCObjectPointerType(CT);
7458 if (Ty->isObjCIdType()) {
7459 S += "{objc_object=}";
7462 else if (Ty->isObjCClassType()) {
7463 S += "{objc_class=}";
7466 // TODO: Double check to make sure this intentionally falls through.
7470 case Type::ObjCInterface: {
7471 // Ignore protocol qualifiers when mangling at this level.
7472 // @encode(class_name)
7473 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
7475 S += OI->getObjCRuntimeNameAsString();
7476 if (Options.ExpandStructures()) {
7478 SmallVector<const ObjCIvarDecl*, 32> Ivars;
7479 DeepCollectObjCIvars(OI, true, Ivars);
7480 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
7481 const FieldDecl *Field = Ivars[i];
7482 if (Field->isBitField())
7483 getObjCEncodingForTypeImpl(Field->getType(), S,
7484 ObjCEncOptions().setExpandStructures(),
7487 getObjCEncodingForTypeImpl(Field->getType(), S,
7488 ObjCEncOptions().setExpandStructures(), FD,
7496 case Type::ObjCObjectPointer: {
7497 const auto *OPT = T->castAs<ObjCObjectPointerType>();
7498 if (OPT->isObjCIdType()) {
7503 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7504 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
7505 // Since this is a binary compatibility issue, need to consult with
7506 // runtime folks. Fortunately, this is a *very* obscure construct.
7511 if (OPT->isObjCQualifiedIdType()) {
7512 getObjCEncodingForTypeImpl(
7514 Options.keepingOnly(ObjCEncOptions()
7515 .setExpandPointedToStructures()
7516 .setExpandStructures()),
7518 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
7519 // Note that we do extended encoding of protocol qualifer list
7520 // Only when doing ivar or property encoding.
7522 for (const auto *I : OPT->quals()) {
7524 S += I->getObjCRuntimeNameAsString();
7533 if (OPT->getInterfaceDecl() &&
7534 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
7536 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
7537 for (const auto *I : OPT->quals()) {
7539 S += I->getObjCRuntimeNameAsString();
7547 // gcc just blithely ignores member pointers.
7548 // FIXME: we should do better than that. 'M' is available.
7549 case Type::MemberPointer:
7550 // This matches gcc's encoding, even though technically it is insufficient.
7551 //FIXME. We should do a better job than gcc.
7553 case Type::ExtVector:
7554 // Until we have a coherent encoding of these three types, issue warning.
7559 case Type::ConstantMatrix:
7564 // We could see an undeduced auto type here during error recovery.
7567 case Type::DeducedTemplateSpecialization:
7572 #define ABSTRACT_TYPE(KIND, BASE)
7573 #define TYPE(KIND, BASE)
7574 #define DEPENDENT_TYPE(KIND, BASE) \
7576 #define NON_CANONICAL_TYPE(KIND, BASE) \
7578 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7580 #include "clang/AST/TypeNodes.inc"
7581 llvm_unreachable("@encode for dependent type!");
7583 llvm_unreachable("bad type kind!");
7586 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7588 const FieldDecl *FD,
7590 QualType *NotEncodedT) const {
7591 assert(RDecl && "Expected non-null RecordDecl");
7592 assert(!RDecl->isUnion() && "Should not be called for unions");
7593 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
7596 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
7597 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7598 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7601 for (const auto &BI : CXXRec->bases()) {
7602 if (!BI.isVirtual()) {
7603 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7604 if (base->isEmpty())
7606 uint64_t offs = toBits(layout.getBaseClassOffset(base));
7607 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7608 std::make_pair(offs, base));
7614 for (auto *Field : RDecl->fields()) {
7615 uint64_t offs = layout.getFieldOffset(i);
7616 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7617 std::make_pair(offs, Field));
7621 if (CXXRec && includeVBases) {
7622 for (const auto &BI : CXXRec->vbases()) {
7623 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7624 if (base->isEmpty())
7626 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
7627 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7628 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
7629 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7630 std::make_pair(offs, base));
7636 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7638 size = layout.getSize();
7642 uint64_t CurOffs = 0;
7644 std::multimap<uint64_t, NamedDecl *>::iterator
7645 CurLayObj = FieldOrBaseOffsets.begin();
7647 if (CXXRec && CXXRec->isDynamicClass() &&
7648 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
7651 std::string recname = CXXRec->getNameAsString();
7652 if (recname.empty()) recname = "?";
7658 CurOffs += getTypeSize(VoidPtrTy);
7662 if (!RDecl->hasFlexibleArrayMember()) {
7663 // Mark the end of the structure.
7664 uint64_t offs = toBits(size);
7665 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7666 std::make_pair(offs, nullptr));
7669 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
7671 assert(CurOffs <= CurLayObj->first);
7672 if (CurOffs < CurLayObj->first) {
7673 uint64_t padding = CurLayObj->first - CurOffs;
7674 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7675 // packing/alignment of members is different that normal, in which case
7676 // the encoding will be out-of-sync with the real layout.
7677 // If the runtime switches to just consider the size of types without
7678 // taking into account alignment, we could make padding explicit in the
7679 // encoding (e.g. using arrays of chars). The encoding strings would be
7680 // longer then though.
7685 NamedDecl *dcl = CurLayObj->second;
7687 break; // reached end of structure.
7689 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
7690 // We expand the bases without their virtual bases since those are going
7691 // in the initial structure. Note that this differs from gcc which
7692 // expands virtual bases each time one is encountered in the hierarchy,
7693 // making the encoding type bigger than it really is.
7694 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7696 assert(!base->isEmpty());
7698 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
7701 const auto *field = cast<FieldDecl>(dcl);
7704 S += field->getNameAsString();
7708 if (field->isBitField()) {
7709 EncodeBitField(this, S, field->getType(), field);
7711 CurOffs += field->getBitWidthValue(*this);
7714 QualType qt = field->getType();
7715 getLegacyIntegralTypeEncoding(qt);
7716 getObjCEncodingForTypeImpl(
7717 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7720 CurOffs += getTypeSize(field->getType());
7727 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
7728 std::string& S) const {
7729 if (QT & Decl::OBJC_TQ_In)
7731 if (QT & Decl::OBJC_TQ_Inout)
7733 if (QT & Decl::OBJC_TQ_Out)
7735 if (QT & Decl::OBJC_TQ_Bycopy)
7737 if (QT & Decl::OBJC_TQ_Byref)
7739 if (QT & Decl::OBJC_TQ_Oneway)
7743 TypedefDecl *ASTContext::getObjCIdDecl() const {
7745 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
7746 T = getObjCObjectPointerType(T);
7747 ObjCIdDecl = buildImplicitTypedef(T, "id");
7752 TypedefDecl *ASTContext::getObjCSelDecl() const {
7754 QualType T = getPointerType(ObjCBuiltinSelTy);
7755 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
7760 TypedefDecl *ASTContext::getObjCClassDecl() const {
7761 if (!ObjCClassDecl) {
7762 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
7763 T = getObjCObjectPointerType(T);
7764 ObjCClassDecl = buildImplicitTypedef(T, "Class");
7766 return ObjCClassDecl;
7769 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7770 if (!ObjCProtocolClassDecl) {
7771 ObjCProtocolClassDecl
7772 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
7774 &Idents.get("Protocol"),
7775 /*typeParamList=*/nullptr,
7776 /*PrevDecl=*/nullptr,
7777 SourceLocation(), true);
7780 return ObjCProtocolClassDecl;
7783 //===----------------------------------------------------------------------===//
7784 // __builtin_va_list Construction Functions
7785 //===----------------------------------------------------------------------===//
7787 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7789 // typedef char* __builtin[_ms]_va_list;
7790 QualType T = Context->getPointerType(Context->CharTy);
7791 return Context->buildImplicitTypedef(T, Name);
7794 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7795 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7798 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7799 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
7802 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7803 // typedef void* __builtin_va_list;
7804 QualType T = Context->getPointerType(Context->VoidTy);
7805 return Context->buildImplicitTypedef(T, "__builtin_va_list");
7808 static TypedefDecl *
7809 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
7811 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
7812 if (Context->getLangOpts().CPlusPlus) {
7813 // namespace std { struct __va_list {
7815 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7816 Context->getTranslationUnitDecl(),
7817 /*Inline*/ false, SourceLocation(),
7818 SourceLocation(), &Context->Idents.get("std"),
7819 /*PrevDecl*/ nullptr);
7821 VaListTagDecl->setDeclContext(NS);
7824 VaListTagDecl->startDefinition();
7826 const size_t NumFields = 5;
7827 QualType FieldTypes[NumFields];
7828 const char *FieldNames[NumFields];
7831 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7832 FieldNames[0] = "__stack";
7835 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7836 FieldNames[1] = "__gr_top";
7839 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7840 FieldNames[2] = "__vr_top";
7843 FieldTypes[3] = Context->IntTy;
7844 FieldNames[3] = "__gr_offs";
7847 FieldTypes[4] = Context->IntTy;
7848 FieldNames[4] = "__vr_offs";
7851 for (unsigned i = 0; i < NumFields; ++i) {
7852 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7856 &Context->Idents.get(FieldNames[i]),
7857 FieldTypes[i], /*TInfo=*/nullptr,
7858 /*BitWidth=*/nullptr,
7861 Field->setAccess(AS_public);
7862 VaListTagDecl->addDecl(Field);
7864 VaListTagDecl->completeDefinition();
7865 Context->VaListTagDecl = VaListTagDecl;
7866 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7868 // } __builtin_va_list;
7869 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
7872 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7873 // typedef struct __va_list_tag {
7874 RecordDecl *VaListTagDecl;
7876 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7877 VaListTagDecl->startDefinition();
7879 const size_t NumFields = 5;
7880 QualType FieldTypes[NumFields];
7881 const char *FieldNames[NumFields];
7883 // unsigned char gpr;
7884 FieldTypes[0] = Context->UnsignedCharTy;
7885 FieldNames[0] = "gpr";
7887 // unsigned char fpr;
7888 FieldTypes[1] = Context->UnsignedCharTy;
7889 FieldNames[1] = "fpr";
7891 // unsigned short reserved;
7892 FieldTypes[2] = Context->UnsignedShortTy;
7893 FieldNames[2] = "reserved";
7895 // void* overflow_arg_area;
7896 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7897 FieldNames[3] = "overflow_arg_area";
7899 // void* reg_save_area;
7900 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7901 FieldNames[4] = "reg_save_area";
7904 for (unsigned i = 0; i < NumFields; ++i) {
7905 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7908 &Context->Idents.get(FieldNames[i]),
7909 FieldTypes[i], /*TInfo=*/nullptr,
7910 /*BitWidth=*/nullptr,
7913 Field->setAccess(AS_public);
7914 VaListTagDecl->addDecl(Field);
7916 VaListTagDecl->completeDefinition();
7917 Context->VaListTagDecl = VaListTagDecl;
7918 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7921 TypedefDecl *VaListTagTypedefDecl =
7922 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7924 QualType VaListTagTypedefType =
7925 Context->getTypedefType(VaListTagTypedefDecl);
7927 // typedef __va_list_tag __builtin_va_list[1];
7928 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7929 QualType VaListTagArrayType
7930 = Context->getConstantArrayType(VaListTagTypedefType,
7931 Size, nullptr, ArrayType::Normal, 0);
7932 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7935 static TypedefDecl *
7936 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
7937 // struct __va_list_tag {
7938 RecordDecl *VaListTagDecl;
7939 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7940 VaListTagDecl->startDefinition();
7942 const size_t NumFields = 4;
7943 QualType FieldTypes[NumFields];
7944 const char *FieldNames[NumFields];
7946 // unsigned gp_offset;
7947 FieldTypes[0] = Context->UnsignedIntTy;
7948 FieldNames[0] = "gp_offset";
7950 // unsigned fp_offset;
7951 FieldTypes[1] = Context->UnsignedIntTy;
7952 FieldNames[1] = "fp_offset";
7954 // void* overflow_arg_area;
7955 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7956 FieldNames[2] = "overflow_arg_area";
7958 // void* reg_save_area;
7959 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7960 FieldNames[3] = "reg_save_area";
7963 for (unsigned i = 0; i < NumFields; ++i) {
7964 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7968 &Context->Idents.get(FieldNames[i]),
7969 FieldTypes[i], /*TInfo=*/nullptr,
7970 /*BitWidth=*/nullptr,
7973 Field->setAccess(AS_public);
7974 VaListTagDecl->addDecl(Field);
7976 VaListTagDecl->completeDefinition();
7977 Context->VaListTagDecl = VaListTagDecl;
7978 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7982 // typedef struct __va_list_tag __builtin_va_list[1];
7983 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7984 QualType VaListTagArrayType = Context->getConstantArrayType(
7985 VaListTagType, Size, nullptr, ArrayType::Normal, 0);
7986 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7989 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7990 // typedef int __builtin_va_list[4];
7991 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
7992 QualType IntArrayType = Context->getConstantArrayType(
7993 Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
7994 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
7997 static TypedefDecl *
7998 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
8000 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
8001 if (Context->getLangOpts().CPlusPlus) {
8002 // namespace std { struct __va_list {
8004 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
8005 Context->getTranslationUnitDecl(),
8006 /*Inline*/false, SourceLocation(),
8007 SourceLocation(), &Context->Idents.get("std"),
8008 /*PrevDecl*/ nullptr);
8010 VaListDecl->setDeclContext(NS);
8013 VaListDecl->startDefinition();
8016 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8020 &Context->Idents.get("__ap"),
8021 Context->getPointerType(Context->VoidTy),
8023 /*BitWidth=*/nullptr,
8026 Field->setAccess(AS_public);
8027 VaListDecl->addDecl(Field);
8030 VaListDecl->completeDefinition();
8031 Context->VaListTagDecl = VaListDecl;
8033 // typedef struct __va_list __builtin_va_list;
8034 QualType T = Context->getRecordType(VaListDecl);
8035 return Context->buildImplicitTypedef(T, "__builtin_va_list");
8038 static TypedefDecl *
8039 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
8040 // struct __va_list_tag {
8041 RecordDecl *VaListTagDecl;
8042 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8043 VaListTagDecl->startDefinition();
8045 const size_t NumFields = 4;
8046 QualType FieldTypes[NumFields];
8047 const char *FieldNames[NumFields];
8050 FieldTypes[0] = Context->LongTy;
8051 FieldNames[0] = "__gpr";
8054 FieldTypes[1] = Context->LongTy;
8055 FieldNames[1] = "__fpr";
8057 // void *__overflow_arg_area;
8058 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8059 FieldNames[2] = "__overflow_arg_area";
8061 // void *__reg_save_area;
8062 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8063 FieldNames[3] = "__reg_save_area";
8066 for (unsigned i = 0; i < NumFields; ++i) {
8067 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8071 &Context->Idents.get(FieldNames[i]),
8072 FieldTypes[i], /*TInfo=*/nullptr,
8073 /*BitWidth=*/nullptr,
8076 Field->setAccess(AS_public);
8077 VaListTagDecl->addDecl(Field);
8079 VaListTagDecl->completeDefinition();
8080 Context->VaListTagDecl = VaListTagDecl;
8081 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8085 // typedef __va_list_tag __builtin_va_list[1];
8086 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8087 QualType VaListTagArrayType = Context->getConstantArrayType(
8088 VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8090 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8093 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
8094 // typedef struct __va_list_tag {
8095 RecordDecl *VaListTagDecl;
8096 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8097 VaListTagDecl->startDefinition();
8099 const size_t NumFields = 3;
8100 QualType FieldTypes[NumFields];
8101 const char *FieldNames[NumFields];
8103 // void *CurrentSavedRegisterArea;
8104 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8105 FieldNames[0] = "__current_saved_reg_area_pointer";
8107 // void *SavedRegAreaEnd;
8108 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8109 FieldNames[1] = "__saved_reg_area_end_pointer";
8111 // void *OverflowArea;
8112 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8113 FieldNames[2] = "__overflow_area_pointer";
8116 for (unsigned i = 0; i < NumFields; ++i) {
8117 FieldDecl *Field = FieldDecl::Create(
8118 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
8119 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
8122 /*Mutable=*/false, ICIS_NoInit);
8123 Field->setAccess(AS_public);
8124 VaListTagDecl->addDecl(Field);
8126 VaListTagDecl->completeDefinition();
8127 Context->VaListTagDecl = VaListTagDecl;
8128 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8131 TypedefDecl *VaListTagTypedefDecl =
8132 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8134 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
8136 // typedef __va_list_tag __builtin_va_list[1];
8137 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8138 QualType VaListTagArrayType = Context->getConstantArrayType(
8139 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
8141 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8144 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
8145 TargetInfo::BuiltinVaListKind Kind) {
8147 case TargetInfo::CharPtrBuiltinVaList:
8148 return CreateCharPtrBuiltinVaListDecl(Context);
8149 case TargetInfo::VoidPtrBuiltinVaList:
8150 return CreateVoidPtrBuiltinVaListDecl(Context);
8151 case TargetInfo::AArch64ABIBuiltinVaList:
8152 return CreateAArch64ABIBuiltinVaListDecl(Context);
8153 case TargetInfo::PowerABIBuiltinVaList:
8154 return CreatePowerABIBuiltinVaListDecl(Context);
8155 case TargetInfo::X86_64ABIBuiltinVaList:
8156 return CreateX86_64ABIBuiltinVaListDecl(Context);
8157 case TargetInfo::PNaClABIBuiltinVaList:
8158 return CreatePNaClABIBuiltinVaListDecl(Context);
8159 case TargetInfo::AAPCSABIBuiltinVaList:
8160 return CreateAAPCSABIBuiltinVaListDecl(Context);
8161 case TargetInfo::SystemZBuiltinVaList:
8162 return CreateSystemZBuiltinVaListDecl(Context);
8163 case TargetInfo::HexagonBuiltinVaList:
8164 return CreateHexagonBuiltinVaListDecl(Context);
8167 llvm_unreachable("Unhandled __builtin_va_list type kind");
8170 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
8171 if (!BuiltinVaListDecl) {
8172 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
8173 assert(BuiltinVaListDecl->isImplicit());
8176 return BuiltinVaListDecl;
8179 Decl *ASTContext::getVaListTagDecl() const {
8180 // Force the creation of VaListTagDecl by building the __builtin_va_list
8183 (void)getBuiltinVaListDecl();
8185 return VaListTagDecl;
8188 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
8189 if (!BuiltinMSVaListDecl)
8190 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
8192 return BuiltinMSVaListDecl;
8195 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
8196 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
8199 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
8200 assert(ObjCConstantStringType.isNull() &&
8201 "'NSConstantString' type already set!");
8203 ObjCConstantStringType = getObjCInterfaceType(Decl);
8206 /// Retrieve the template name that corresponds to a non-empty
8209 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
8210 UnresolvedSetIterator End) const {
8211 unsigned size = End - Begin;
8212 assert(size > 1 && "set is not overloaded!");
8214 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
8215 size * sizeof(FunctionTemplateDecl*));
8216 auto *OT = new (memory) OverloadedTemplateStorage(size);
8218 NamedDecl **Storage = OT->getStorage();
8219 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
8221 assert(isa<FunctionTemplateDecl>(D) ||
8222 isa<UnresolvedUsingValueDecl>(D) ||
8223 (isa<UsingShadowDecl>(D) &&
8224 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
8228 return TemplateName(OT);
8231 /// Retrieve a template name representing an unqualified-id that has been
8232 /// assumed to name a template for ADL purposes.
8233 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
8234 auto *OT = new (*this) AssumedTemplateStorage(Name);
8235 return TemplateName(OT);
8238 /// Retrieve the template name that represents a qualified
8239 /// template name such as \c std::vector.
8241 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
8242 bool TemplateKeyword,
8243 TemplateDecl *Template) const {
8244 assert(NNS && "Missing nested-name-specifier in qualified template name");
8246 // FIXME: Canonicalization?
8247 llvm::FoldingSetNodeID ID;
8248 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
8250 void *InsertPos = nullptr;
8251 QualifiedTemplateName *QTN =
8252 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8254 QTN = new (*this, alignof(QualifiedTemplateName))
8255 QualifiedTemplateName(NNS, TemplateKeyword, Template);
8256 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
8259 return TemplateName(QTN);
8262 /// Retrieve the template name that represents a dependent
8263 /// template name such as \c MetaFun::template apply.
8265 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8266 const IdentifierInfo *Name) const {
8267 assert((!NNS || NNS->isDependent()) &&
8268 "Nested name specifier must be dependent");
8270 llvm::FoldingSetNodeID ID;
8271 DependentTemplateName::Profile(ID, NNS, Name);
8273 void *InsertPos = nullptr;
8274 DependentTemplateName *QTN =
8275 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8278 return TemplateName(QTN);
8280 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8281 if (CanonNNS == NNS) {
8282 QTN = new (*this, alignof(DependentTemplateName))
8283 DependentTemplateName(NNS, Name);
8285 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
8286 QTN = new (*this, alignof(DependentTemplateName))
8287 DependentTemplateName(NNS, Name, Canon);
8288 DependentTemplateName *CheckQTN =
8289 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8290 assert(!CheckQTN && "Dependent type name canonicalization broken");
8294 DependentTemplateNames.InsertNode(QTN, InsertPos);
8295 return TemplateName(QTN);
8298 /// Retrieve the template name that represents a dependent
8299 /// template name such as \c MetaFun::template operator+.
8301 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8302 OverloadedOperatorKind Operator) const {
8303 assert((!NNS || NNS->isDependent()) &&
8304 "Nested name specifier must be dependent");
8306 llvm::FoldingSetNodeID ID;
8307 DependentTemplateName::Profile(ID, NNS, Operator);
8309 void *InsertPos = nullptr;
8310 DependentTemplateName *QTN
8311 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8314 return TemplateName(QTN);
8316 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8317 if (CanonNNS == NNS) {
8318 QTN = new (*this, alignof(DependentTemplateName))
8319 DependentTemplateName(NNS, Operator);
8321 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
8322 QTN = new (*this, alignof(DependentTemplateName))
8323 DependentTemplateName(NNS, Operator, Canon);
8325 DependentTemplateName *CheckQTN
8326 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8327 assert(!CheckQTN && "Dependent template name canonicalization broken");
8331 DependentTemplateNames.InsertNode(QTN, InsertPos);
8332 return TemplateName(QTN);
8336 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
8337 TemplateName replacement) const {
8338 llvm::FoldingSetNodeID ID;
8339 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
8341 void *insertPos = nullptr;
8342 SubstTemplateTemplateParmStorage *subst
8343 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
8346 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
8347 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
8350 return TemplateName(subst);
8354 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
8355 const TemplateArgument &ArgPack) const {
8356 auto &Self = const_cast<ASTContext &>(*this);
8357 llvm::FoldingSetNodeID ID;
8358 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
8360 void *InsertPos = nullptr;
8361 SubstTemplateTemplateParmPackStorage *Subst
8362 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
8365 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
8366 ArgPack.pack_size(),
8367 ArgPack.pack_begin());
8368 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
8371 return TemplateName(Subst);
8374 /// getFromTargetType - Given one of the integer types provided by
8375 /// TargetInfo, produce the corresponding type. The unsigned @p Type
8376 /// is actually a value of type @c TargetInfo::IntType.
8377 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
8379 case TargetInfo::NoInt: return {};
8380 case TargetInfo::SignedChar: return SignedCharTy;
8381 case TargetInfo::UnsignedChar: return UnsignedCharTy;
8382 case TargetInfo::SignedShort: return ShortTy;
8383 case TargetInfo::UnsignedShort: return UnsignedShortTy;
8384 case TargetInfo::SignedInt: return IntTy;
8385 case TargetInfo::UnsignedInt: return UnsignedIntTy;
8386 case TargetInfo::SignedLong: return LongTy;
8387 case TargetInfo::UnsignedLong: return UnsignedLongTy;
8388 case TargetInfo::SignedLongLong: return LongLongTy;
8389 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
8392 llvm_unreachable("Unhandled TargetInfo::IntType value");
8395 //===----------------------------------------------------------------------===//
8397 //===----------------------------------------------------------------------===//
8399 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
8400 /// garbage collection attribute.
8402 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
8403 if (getLangOpts().getGC() == LangOptions::NonGC)
8404 return Qualifiers::GCNone;
8406 assert(getLangOpts().ObjC);
8407 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
8409 // Default behaviour under objective-C's gc is for ObjC pointers
8410 // (or pointers to them) be treated as though they were declared
8412 if (GCAttrs == Qualifiers::GCNone) {
8413 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
8414 return Qualifiers::Strong;
8415 else if (Ty->isPointerType())
8416 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
8418 // It's not valid to set GC attributes on anything that isn't a
8421 QualType CT = Ty->getCanonicalTypeInternal();
8422 while (const auto *AT = dyn_cast<ArrayType>(CT))
8423 CT = AT->getElementType();
8424 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
8430 //===----------------------------------------------------------------------===//
8431 // Type Compatibility Testing
8432 //===----------------------------------------------------------------------===//
8434 /// areCompatVectorTypes - Return true if the two specified vector types are
8436 static bool areCompatVectorTypes(const VectorType *LHS,
8437 const VectorType *RHS) {
8438 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8439 return LHS->getElementType() == RHS->getElementType() &&
8440 LHS->getNumElements() == RHS->getNumElements();
8443 /// areCompatMatrixTypes - Return true if the two specified matrix types are
8445 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
8446 const ConstantMatrixType *RHS) {
8447 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8448 return LHS->getElementType() == RHS->getElementType() &&
8449 LHS->getNumRows() == RHS->getNumRows() &&
8450 LHS->getNumColumns() == RHS->getNumColumns();
8453 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
8454 QualType SecondVec) {
8455 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
8456 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
8458 if (hasSameUnqualifiedType(FirstVec, SecondVec))
8461 // Treat Neon vector types and most AltiVec vector types as if they are the
8462 // equivalent GCC vector types.
8463 const auto *First = FirstVec->castAs<VectorType>();
8464 const auto *Second = SecondVec->castAs<VectorType>();
8465 if (First->getNumElements() == Second->getNumElements() &&
8466 hasSameType(First->getElementType(), Second->getElementType()) &&
8467 First->getVectorKind() != VectorType::AltiVecPixel &&
8468 First->getVectorKind() != VectorType::AltiVecBool &&
8469 Second->getVectorKind() != VectorType::AltiVecPixel &&
8470 Second->getVectorKind() != VectorType::AltiVecBool)
8476 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
8479 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
8480 if (Attr->getAttrKind() == attr::ObjCOwnership)
8483 Ty = Attr->getModifiedType();
8485 // X *__strong (...)
8486 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
8487 Ty = Paren->getInnerType();
8489 // We do not want to look through typedefs, typeof(expr),
8490 // typeof(type), or any other way that the type is somehow
8498 //===----------------------------------------------------------------------===//
8499 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
8500 //===----------------------------------------------------------------------===//
8502 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
8503 /// inheritance hierarchy of 'rProto'.
8505 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
8506 ObjCProtocolDecl *rProto) const {
8507 if (declaresSameEntity(lProto, rProto))
8509 for (auto *PI : rProto->protocols())
8510 if (ProtocolCompatibleWithProtocol(lProto, PI))
8515 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
8516 /// Class<pr1, ...>.
8517 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
8518 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
8519 for (auto *lhsProto : lhs->quals()) {
8521 for (auto *rhsProto : rhs->quals()) {
8522 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
8533 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
8534 /// ObjCQualifiedIDType.
8535 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
8536 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
8538 // Allow id<P..> and an 'id' in all cases.
8539 if (lhs->isObjCIdType() || rhs->isObjCIdType())
8542 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
8543 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
8544 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
8547 if (lhs->isObjCQualifiedIdType()) {
8548 if (rhs->qual_empty()) {
8549 // If the RHS is a unqualified interface pointer "NSString*",
8550 // make sure we check the class hierarchy.
8551 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8552 for (auto *I : lhs->quals()) {
8553 // when comparing an id<P> on lhs with a static type on rhs,
8554 // see if static class implements all of id's protocols, directly or
8555 // through its super class and categories.
8556 if (!rhsID->ClassImplementsProtocol(I, true))
8560 // If there are no qualifiers and no interface, we have an 'id'.
8563 // Both the right and left sides have qualifiers.
8564 for (auto *lhsProto : lhs->quals()) {
8567 // when comparing an id<P> on lhs with a static type on rhs,
8568 // see if static class implements all of id's protocols, directly or
8569 // through its super class and categories.
8570 for (auto *rhsProto : rhs->quals()) {
8571 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8572 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8577 // If the RHS is a qualified interface pointer "NSString<P>*",
8578 // make sure we check the class hierarchy.
8579 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8580 for (auto *I : lhs->quals()) {
8581 // when comparing an id<P> on lhs with a static type on rhs,
8582 // see if static class implements all of id's protocols, directly or
8583 // through its super class and categories.
8584 if (rhsID->ClassImplementsProtocol(I, true)) {
8597 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
8599 if (lhs->getInterfaceType()) {
8600 // If both the right and left sides have qualifiers.
8601 for (auto *lhsProto : lhs->quals()) {
8604 // when comparing an id<P> on rhs with a static type on lhs,
8605 // see if static class implements all of id's protocols, directly or
8606 // through its super class and categories.
8607 // First, lhs protocols in the qualifier list must be found, direct
8608 // or indirect in rhs's qualifier list or it is a mismatch.
8609 for (auto *rhsProto : rhs->quals()) {
8610 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8611 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8620 // Static class's protocols, or its super class or category protocols
8621 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8622 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
8623 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8624 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8625 // This is rather dubious but matches gcc's behavior. If lhs has
8626 // no type qualifier and its class has no static protocol(s)
8627 // assume that it is mismatch.
8628 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
8630 for (auto *lhsProto : LHSInheritedProtocols) {
8632 for (auto *rhsProto : rhs->quals()) {
8633 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8634 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8648 /// canAssignObjCInterfaces - Return true if the two interface types are
8649 /// compatible for assignment from RHS to LHS. This handles validation of any
8650 /// protocol qualifiers on the LHS or RHS.
8651 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8652 const ObjCObjectPointerType *RHSOPT) {
8653 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8654 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8656 // If either type represents the built-in 'id' type, return true.
8657 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
8660 // Function object that propagates a successful result or handles
8662 auto finish = [&](bool succeeded) -> bool {
8666 if (!RHS->isKindOfType())
8669 // Strip off __kindof and protocol qualifiers, then check whether
8670 // we can assign the other way.
8671 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8672 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8675 // Casts from or to id<P> are allowed when the other side has compatible
8677 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8678 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
8681 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
8682 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8683 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
8686 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
8687 if (LHS->isObjCClass() && RHS->isObjCClass()) {
8691 // If we have 2 user-defined types, fall into that path.
8692 if (LHS->getInterface() && RHS->getInterface()) {
8693 return finish(canAssignObjCInterfaces(LHS, RHS));
8699 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
8700 /// for providing type-safety for objective-c pointers used to pass/return
8701 /// arguments in block literals. When passed as arguments, passing 'A*' where
8702 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8703 /// not OK. For the return type, the opposite is not OK.
8704 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8705 const ObjCObjectPointerType *LHSOPT,
8706 const ObjCObjectPointerType *RHSOPT,
8707 bool BlockReturnType) {
8709 // Function object that propagates a successful result or handles
8711 auto finish = [&](bool succeeded) -> bool {
8715 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8716 if (!Expected->isKindOfType())
8719 // Strip off __kindof and protocol qualifiers, then check whether
8720 // we can assign the other way.
8721 return canAssignObjCInterfacesInBlockPointer(
8722 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8723 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8727 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
8730 if (LHSOPT->isObjCBuiltinType()) {
8731 return finish(RHSOPT->isObjCBuiltinType() ||
8732 RHSOPT->isObjCQualifiedIdType());
8735 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
8736 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
8737 // Use for block parameters previous type checking for compatibility.
8738 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
8739 // Or corrected type checking as in non-compat mode.
8740 (!BlockReturnType &&
8741 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
8743 return finish(ObjCQualifiedIdTypesAreCompatible(
8744 (BlockReturnType ? LHSOPT : RHSOPT),
8745 (BlockReturnType ? RHSOPT : LHSOPT), false));
8748 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8749 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8750 if (LHS && RHS) { // We have 2 user-defined types.
8752 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
8753 return finish(BlockReturnType);
8754 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
8755 return finish(!BlockReturnType);
8763 /// Comparison routine for Objective-C protocols to be used with
8764 /// llvm::array_pod_sort.
8765 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8766 ObjCProtocolDecl * const *rhs) {
8767 return (*lhs)->getName().compare((*rhs)->getName());
8770 /// getIntersectionOfProtocols - This routine finds the intersection of set
8771 /// of protocols inherited from two distinct objective-c pointer objects with
8772 /// the given common base.
8773 /// It is used to build composite qualifier list of the composite type of
8774 /// the conditional expression involving two objective-c pointer objects.
8776 void getIntersectionOfProtocols(ASTContext &Context,
8777 const ObjCInterfaceDecl *CommonBase,
8778 const ObjCObjectPointerType *LHSOPT,
8779 const ObjCObjectPointerType *RHSOPT,
8780 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
8782 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8783 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8784 assert(LHS->getInterface() && "LHS must have an interface base");
8785 assert(RHS->getInterface() && "RHS must have an interface base");
8787 // Add all of the protocols for the LHS.
8788 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8790 // Start with the protocol qualifiers.
8791 for (auto proto : LHS->quals()) {
8792 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
8795 // Also add the protocols associated with the LHS interface.
8796 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8798 // Add all of the protocols for the RHS.
8799 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8801 // Start with the protocol qualifiers.
8802 for (auto proto : RHS->quals()) {
8803 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
8806 // Also add the protocols associated with the RHS interface.
8807 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8809 // Compute the intersection of the collected protocol sets.
8810 for (auto proto : LHSProtocolSet) {
8811 if (RHSProtocolSet.count(proto))
8812 IntersectionSet.push_back(proto);
8815 // Compute the set of protocols that is implied by either the common type or
8816 // the protocols within the intersection.
8817 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8818 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8820 // Remove any implied protocols from the list of inherited protocols.
8821 if (!ImpliedProtocols.empty()) {
8822 IntersectionSet.erase(
8823 std::remove_if(IntersectionSet.begin(),
8824 IntersectionSet.end(),
8825 [&](ObjCProtocolDecl *proto) -> bool {
8826 return ImpliedProtocols.count(proto) > 0;
8828 IntersectionSet.end());
8831 // Sort the remaining protocols by name.
8832 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8833 compareObjCProtocolsByName);
8836 /// Determine whether the first type is a subtype of the second.
8837 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8839 // Common case: two object pointers.
8840 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8841 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
8842 if (lhsOPT && rhsOPT)
8843 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8845 // Two block pointers.
8846 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8847 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
8848 if (lhsBlock && rhsBlock)
8849 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8851 // If either is an unqualified 'id' and the other is a block, it's
8853 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8854 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8860 // Check that the given Objective-C type argument lists are equivalent.
8861 static bool sameObjCTypeArgs(ASTContext &ctx,
8862 const ObjCInterfaceDecl *iface,
8863 ArrayRef<QualType> lhsArgs,
8864 ArrayRef<QualType> rhsArgs,
8866 if (lhsArgs.size() != rhsArgs.size())
8869 ObjCTypeParamList *typeParams = iface->getTypeParamList();
8870 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
8871 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8874 switch (typeParams->begin()[i]->getVariance()) {
8875 case ObjCTypeParamVariance::Invariant:
8877 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8878 rhsArgs[i].stripObjCKindOfType(ctx))) {
8883 case ObjCTypeParamVariance::Covariant:
8884 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8888 case ObjCTypeParamVariance::Contravariant:
8889 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8898 QualType ASTContext::areCommonBaseCompatible(
8899 const ObjCObjectPointerType *Lptr,
8900 const ObjCObjectPointerType *Rptr) {
8901 const ObjCObjectType *LHS = Lptr->getObjectType();
8902 const ObjCObjectType *RHS = Rptr->getObjectType();
8903 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8904 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
8906 if (!LDecl || !RDecl)
8909 // When either LHS or RHS is a kindof type, we should return a kindof type.
8910 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8912 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8914 // Follow the left-hand side up the class hierarchy until we either hit a
8915 // root or find the RHS. Record the ancestors in case we don't find it.
8916 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8919 // Record this ancestor. We'll need this if the common type isn't in the
8920 // path from the LHS to the root.
8921 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
8923 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8924 // Get the type arguments.
8925 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8926 bool anyChanges = false;
8927 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8928 // Both have type arguments, compare them.
8929 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8930 LHS->getTypeArgs(), RHS->getTypeArgs(),
8931 /*stripKindOf=*/true))
8933 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8934 // If only one has type arguments, the result will not have type
8940 // Compute the intersection of protocols.
8941 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8942 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8944 if (!Protocols.empty())
8947 // If anything in the LHS will have changed, build a new result type.
8948 // If we need to return a kindof type but LHS is not a kindof type, we
8949 // build a new result type.
8950 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
8951 QualType Result = getObjCInterfaceType(LHS->getInterface());
8952 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
8953 anyKindOf || LHS->isKindOfType());
8954 return getObjCObjectPointerType(Result);
8957 return getObjCObjectPointerType(QualType(LHS, 0));
8960 // Find the superclass.
8961 QualType LHSSuperType = LHS->getSuperClassType();
8962 if (LHSSuperType.isNull())
8965 LHS = LHSSuperType->castAs<ObjCObjectType>();
8968 // We didn't find anything by following the LHS to its root; now check
8969 // the RHS against the cached set of ancestors.
8971 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8972 if (KnownLHS != LHSAncestors.end()) {
8973 LHS = KnownLHS->second;
8975 // Get the type arguments.
8976 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8977 bool anyChanges = false;
8978 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8979 // Both have type arguments, compare them.
8980 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8981 LHS->getTypeArgs(), RHS->getTypeArgs(),
8982 /*stripKindOf=*/true))
8984 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8985 // If only one has type arguments, the result will not have type
8991 // Compute the intersection of protocols.
8992 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8993 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8995 if (!Protocols.empty())
8998 // If we need to return a kindof type but RHS is not a kindof type, we
8999 // build a new result type.
9000 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
9001 QualType Result = getObjCInterfaceType(RHS->getInterface());
9002 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
9003 anyKindOf || RHS->isKindOfType());
9004 return getObjCObjectPointerType(Result);
9007 return getObjCObjectPointerType(QualType(RHS, 0));
9010 // Find the superclass of the RHS.
9011 QualType RHSSuperType = RHS->getSuperClassType();
9012 if (RHSSuperType.isNull())
9015 RHS = RHSSuperType->castAs<ObjCObjectType>();
9021 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
9022 const ObjCObjectType *RHS) {
9023 assert(LHS->getInterface() && "LHS is not an interface type");
9024 assert(RHS->getInterface() && "RHS is not an interface type");
9026 // Verify that the base decls are compatible: the RHS must be a subclass of
9028 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
9029 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
9033 // If the LHS has protocol qualifiers, determine whether all of them are
9034 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
9036 if (LHS->getNumProtocols() > 0) {
9037 // OK if conversion of LHS to SuperClass results in narrowing of types
9038 // ; i.e., SuperClass may implement at least one of the protocols
9039 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
9040 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
9041 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
9042 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
9043 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
9045 for (auto *RHSPI : RHS->quals())
9046 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
9047 // If there is no protocols associated with RHS, it is not a match.
9048 if (SuperClassInheritedProtocols.empty())
9051 for (const auto *LHSProto : LHS->quals()) {
9052 bool SuperImplementsProtocol = false;
9053 for (auto *SuperClassProto : SuperClassInheritedProtocols)
9054 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
9055 SuperImplementsProtocol = true;
9058 if (!SuperImplementsProtocol)
9063 // If the LHS is specialized, we may need to check type arguments.
9064 if (LHS->isSpecialized()) {
9065 // Follow the superclass chain until we've matched the LHS class in the
9066 // hierarchy. This substitutes type arguments through.
9067 const ObjCObjectType *RHSSuper = RHS;
9068 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
9069 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
9071 // If the RHS is specializd, compare type arguments.
9072 if (RHSSuper->isSpecialized() &&
9073 !sameObjCTypeArgs(*this, LHS->getInterface(),
9074 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
9075 /*stripKindOf=*/true)) {
9083 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
9084 // get the "pointed to" types
9085 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
9086 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
9088 if (!LHSOPT || !RHSOPT)
9091 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
9092 canAssignObjCInterfaces(RHSOPT, LHSOPT);
9095 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
9096 return canAssignObjCInterfaces(
9097 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
9098 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
9101 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
9102 /// both shall have the identically qualified version of a compatible type.
9103 /// C99 6.2.7p1: Two types have compatible types if their types are the
9104 /// same. See 6.7.[2,3,5] for additional rules.
9105 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
9106 bool CompareUnqualified) {
9107 if (getLangOpts().CPlusPlus)
9108 return hasSameType(LHS, RHS);
9110 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
9113 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
9114 return typesAreCompatible(LHS, RHS);
9117 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
9118 return !mergeTypes(LHS, RHS, true).isNull();
9121 /// mergeTransparentUnionType - if T is a transparent union type and a member
9122 /// of T is compatible with SubType, return the merged type, else return
9124 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
9125 bool OfBlockPointer,
9127 if (const RecordType *UT = T->getAsUnionType()) {
9128 RecordDecl *UD = UT->getDecl();
9129 if (UD->hasAttr<TransparentUnionAttr>()) {
9130 for (const auto *I : UD->fields()) {
9131 QualType ET = I->getType().getUnqualifiedType();
9132 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
9142 /// mergeFunctionParameterTypes - merge two types which appear as function
9144 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
9145 bool OfBlockPointer,
9147 // GNU extension: two types are compatible if they appear as a function
9148 // argument, one of the types is a transparent union type and the other
9149 // type is compatible with a union member
9150 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
9152 if (!lmerge.isNull())
9155 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
9157 if (!rmerge.isNull())
9160 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
9163 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
9164 bool OfBlockPointer, bool Unqualified,
9166 const auto *lbase = lhs->castAs<FunctionType>();
9167 const auto *rbase = rhs->castAs<FunctionType>();
9168 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
9169 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
9170 bool allLTypes = true;
9171 bool allRTypes = true;
9173 // Check return type
9175 if (OfBlockPointer) {
9176 QualType RHS = rbase->getReturnType();
9177 QualType LHS = lbase->getReturnType();
9178 bool UnqualifiedResult = Unqualified;
9179 if (!UnqualifiedResult)
9180 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
9181 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
9184 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
9186 if (retType.isNull())
9190 retType = retType.getUnqualifiedType();
9192 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
9193 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
9195 LRetType = LRetType.getUnqualifiedType();
9196 RRetType = RRetType.getUnqualifiedType();
9199 if (getCanonicalType(retType) != LRetType)
9201 if (getCanonicalType(retType) != RRetType)
9204 // FIXME: double check this
9205 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
9206 // rbase->getRegParmAttr() != 0 &&
9207 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
9208 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
9209 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
9211 // Compatible functions must have compatible calling conventions
9212 if (lbaseInfo.getCC() != rbaseInfo.getCC())
9215 // Regparm is part of the calling convention.
9216 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
9218 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
9221 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
9223 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
9225 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
9228 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
9229 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
9231 if (lbaseInfo.getNoReturn() != NoReturn)
9233 if (rbaseInfo.getNoReturn() != NoReturn)
9236 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
9238 if (lproto && rproto) { // two C99 style function prototypes
9240 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
9241 "C++ shouldn't be here");
9242 // Compatible functions must have the same number of parameters
9243 if (lproto->getNumParams() != rproto->getNumParams())
9246 // Variadic and non-variadic functions aren't compatible
9247 if (lproto->isVariadic() != rproto->isVariadic())
9250 if (lproto->getMethodQuals() != rproto->getMethodQuals())
9253 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
9254 bool canUseLeft, canUseRight;
9255 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
9264 // Check parameter type compatibility
9265 SmallVector<QualType, 10> types;
9266 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
9267 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
9268 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
9269 QualType paramType = mergeFunctionParameterTypes(
9270 lParamType, rParamType, OfBlockPointer, Unqualified);
9271 if (paramType.isNull())
9275 paramType = paramType.getUnqualifiedType();
9277 types.push_back(paramType);
9279 lParamType = lParamType.getUnqualifiedType();
9280 rParamType = rParamType.getUnqualifiedType();
9283 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
9285 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
9289 if (allLTypes) return lhs;
9290 if (allRTypes) return rhs;
9292 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
9293 EPI.ExtInfo = einfo;
9294 EPI.ExtParameterInfos =
9295 newParamInfos.empty() ? nullptr : newParamInfos.data();
9296 return getFunctionType(retType, types, EPI);
9299 if (lproto) allRTypes = false;
9300 if (rproto) allLTypes = false;
9302 const FunctionProtoType *proto = lproto ? lproto : rproto;
9304 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
9305 if (proto->isVariadic())
9307 // Check that the types are compatible with the types that
9308 // would result from default argument promotions (C99 6.7.5.3p15).
9309 // The only types actually affected are promotable integer
9310 // types and floats, which would be passed as a different
9311 // type depending on whether the prototype is visible.
9312 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
9313 QualType paramTy = proto->getParamType(i);
9315 // Look at the converted type of enum types, since that is the type used
9316 // to pass enum values.
9317 if (const auto *Enum = paramTy->getAs<EnumType>()) {
9318 paramTy = Enum->getDecl()->getIntegerType();
9319 if (paramTy.isNull())
9323 if (paramTy->isPromotableIntegerType() ||
9324 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
9328 if (allLTypes) return lhs;
9329 if (allRTypes) return rhs;
9331 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
9332 EPI.ExtInfo = einfo;
9333 return getFunctionType(retType, proto->getParamTypes(), EPI);
9336 if (allLTypes) return lhs;
9337 if (allRTypes) return rhs;
9338 return getFunctionNoProtoType(retType, einfo);
9341 /// Given that we have an enum type and a non-enum type, try to merge them.
9342 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
9343 QualType other, bool isBlockReturnType) {
9344 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
9345 // a signed integer type, or an unsigned integer type.
9346 // Compatibility is based on the underlying type, not the promotion
9348 QualType underlyingType = ET->getDecl()->getIntegerType();
9349 if (underlyingType.isNull())
9351 if (Context.hasSameType(underlyingType, other))
9354 // In block return types, we're more permissive and accept any
9355 // integral type of the same size.
9356 if (isBlockReturnType && other->isIntegerType() &&
9357 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
9363 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
9364 bool OfBlockPointer,
9365 bool Unqualified, bool BlockReturnType) {
9366 // C++ [expr]: If an expression initially has the type "reference to T", the
9367 // type is adjusted to "T" prior to any further analysis, the expression
9368 // designates the object or function denoted by the reference, and the
9369 // expression is an lvalue unless the reference is an rvalue reference and
9370 // the expression is a function call (possibly inside parentheses).
9371 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
9372 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
9375 LHS = LHS.getUnqualifiedType();
9376 RHS = RHS.getUnqualifiedType();
9379 QualType LHSCan = getCanonicalType(LHS),
9380 RHSCan = getCanonicalType(RHS);
9382 // If two types are identical, they are compatible.
9383 if (LHSCan == RHSCan)
9386 // If the qualifiers are different, the types aren't compatible... mostly.
9387 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9388 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9389 if (LQuals != RQuals) {
9390 // If any of these qualifiers are different, we have a type
9392 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9393 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
9394 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
9395 LQuals.hasUnaligned() != RQuals.hasUnaligned())
9398 // Exactly one GC qualifier difference is allowed: __strong is
9399 // okay if the other type has no GC qualifier but is an Objective
9400 // C object pointer (i.e. implicitly strong by default). We fix
9401 // this by pretending that the unqualified type was actually
9402 // qualified __strong.
9403 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9404 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9405 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9407 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9410 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
9411 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
9413 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
9414 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
9419 // Okay, qualifiers are equal.
9421 Type::TypeClass LHSClass = LHSCan->getTypeClass();
9422 Type::TypeClass RHSClass = RHSCan->getTypeClass();
9424 // We want to consider the two function types to be the same for these
9425 // comparisons, just force one to the other.
9426 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
9427 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
9429 // Same as above for arrays
9430 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
9431 LHSClass = Type::ConstantArray;
9432 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
9433 RHSClass = Type::ConstantArray;
9435 // ObjCInterfaces are just specialized ObjCObjects.
9436 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
9437 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
9439 // Canonicalize ExtVector -> Vector.
9440 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
9441 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
9443 // If the canonical type classes don't match.
9444 if (LHSClass != RHSClass) {
9445 // Note that we only have special rules for turning block enum
9446 // returns into block int returns, not vice-versa.
9447 if (const auto *ETy = LHS->getAs<EnumType>()) {
9448 return mergeEnumWithInteger(*this, ETy, RHS, false);
9450 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
9451 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
9453 // allow block pointer type to match an 'id' type.
9454 if (OfBlockPointer && !BlockReturnType) {
9455 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
9457 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
9464 // The canonical type classes match.
9466 #define TYPE(Class, Base)
9467 #define ABSTRACT_TYPE(Class, Base)
9468 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
9469 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
9470 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
9471 #include "clang/AST/TypeNodes.inc"
9472 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
9475 case Type::DeducedTemplateSpecialization:
9476 case Type::LValueReference:
9477 case Type::RValueReference:
9478 case Type::MemberPointer:
9479 llvm_unreachable("C++ should never be in mergeTypes");
9481 case Type::ObjCInterface:
9482 case Type::IncompleteArray:
9483 case Type::VariableArray:
9484 case Type::FunctionProto:
9485 case Type::ExtVector:
9486 llvm_unreachable("Types are eliminated above");
9490 // Merge two pointer types, while trying to preserve typedef info
9491 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
9492 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
9494 LHSPointee = LHSPointee.getUnqualifiedType();
9495 RHSPointee = RHSPointee.getUnqualifiedType();
9497 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
9499 if (ResultType.isNull())
9501 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9503 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9505 return getPointerType(ResultType);
9507 case Type::BlockPointer:
9509 // Merge two block pointer types, while trying to preserve typedef info
9510 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
9511 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
9513 LHSPointee = LHSPointee.getUnqualifiedType();
9514 RHSPointee = RHSPointee.getUnqualifiedType();
9516 if (getLangOpts().OpenCL) {
9517 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
9518 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
9519 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
9520 // 6.12.5) thus the following check is asymmetric.
9521 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
9523 LHSPteeQual.removeAddressSpace();
9524 RHSPteeQual.removeAddressSpace();
9526 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
9528 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
9530 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
9532 if (ResultType.isNull())
9534 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9536 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9538 return getBlockPointerType(ResultType);
9542 // Merge two pointer types, while trying to preserve typedef info
9543 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
9544 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
9546 LHSValue = LHSValue.getUnqualifiedType();
9547 RHSValue = RHSValue.getUnqualifiedType();
9549 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
9551 if (ResultType.isNull())
9553 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9555 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9557 return getAtomicType(ResultType);
9559 case Type::ConstantArray:
9561 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9562 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9563 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
9566 QualType LHSElem = getAsArrayType(LHS)->getElementType();
9567 QualType RHSElem = getAsArrayType(RHS)->getElementType();
9569 LHSElem = LHSElem.getUnqualifiedType();
9570 RHSElem = RHSElem.getUnqualifiedType();
9573 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
9574 if (ResultType.isNull())
9577 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9578 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9580 // If either side is a variable array, and both are complete, check whether
9581 // the current dimension is definite.
9583 auto SizeFetch = [this](const VariableArrayType* VAT,
9584 const ConstantArrayType* CAT)
9585 -> std::pair<bool,llvm::APInt> {
9587 llvm::APSInt TheInt;
9588 Expr *E = VAT->getSizeExpr();
9589 if (E && E->isIntegerConstantExpr(TheInt, *this))
9590 return std::make_pair(true, TheInt);
9592 return std::make_pair(false, TheInt);
9594 return std::make_pair(true, CAT->getSize());
9596 return std::make_pair(false, llvm::APInt());
9600 bool HaveLSize, HaveRSize;
9601 llvm::APInt LSize, RSize;
9602 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9603 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9604 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9605 return {}; // Definite, but unequal, array dimension
9608 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9610 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9613 return getConstantArrayType(ResultType, LCAT->getSize(),
9614 LCAT->getSizeExpr(),
9615 ArrayType::ArraySizeModifier(), 0);
9617 return getConstantArrayType(ResultType, RCAT->getSize(),
9618 RCAT->getSizeExpr(),
9619 ArrayType::ArraySizeModifier(), 0);
9620 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9622 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9625 // FIXME: This isn't correct! But tricky to implement because
9626 // the array's size has to be the size of LHS, but the type
9627 // has to be different.
9631 // FIXME: This isn't correct! But tricky to implement because
9632 // the array's size has to be the size of RHS, but the type
9633 // has to be different.
9636 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9637 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
9638 return getIncompleteArrayType(ResultType,
9639 ArrayType::ArraySizeModifier(), 0);
9641 case Type::FunctionNoProto:
9642 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
9647 // Only exactly equal builtin types are compatible, which is tested above.
9650 // Distinct complex types are incompatible.
9653 // FIXME: The merged type should be an ExtVector!
9654 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
9655 RHSCan->castAs<VectorType>()))
9658 case Type::ConstantMatrix:
9659 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
9660 RHSCan->castAs<ConstantMatrixType>()))
9663 case Type::ObjCObject: {
9664 // Check if the types are assignment compatible.
9665 // FIXME: This should be type compatibility, e.g. whether
9666 // "LHS x; RHS x;" at global scope is legal.
9667 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
9668 RHS->castAs<ObjCObjectType>()))
9672 case Type::ObjCObjectPointer:
9673 if (OfBlockPointer) {
9674 if (canAssignObjCInterfacesInBlockPointer(
9675 LHS->castAs<ObjCObjectPointerType>(),
9676 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
9680 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
9681 RHS->castAs<ObjCObjectPointerType>()))
9685 assert(LHS != RHS &&
9686 "Equivalent pipe types should have already been handled!");
9688 case Type::ExtInt: {
9689 // Merge two ext-int types, while trying to preserve typedef info.
9690 bool LHSUnsigned = LHS->castAs<ExtIntType>()->isUnsigned();
9691 bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned();
9692 unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits();
9693 unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits();
9695 // Like unsigned/int, shouldn't have a type if they dont match.
9696 if (LHSUnsigned != RHSUnsigned)
9699 if (LHSBits != RHSBits)
9705 llvm_unreachable("Invalid Type::Class!");
9708 bool ASTContext::mergeExtParameterInfo(
9709 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9710 bool &CanUseFirst, bool &CanUseSecond,
9711 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9712 assert(NewParamInfos.empty() && "param info list not empty");
9713 CanUseFirst = CanUseSecond = true;
9714 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9715 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9717 // Fast path: if the first type doesn't have ext parameter infos,
9718 // we match if and only if the second type also doesn't have them.
9719 if (!FirstHasInfo && !SecondHasInfo)
9722 bool NeedParamInfo = false;
9723 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9724 : SecondFnType->getExtParameterInfos().size();
9726 for (size_t I = 0; I < E; ++I) {
9727 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9729 FirstParam = FirstFnType->getExtParameterInfo(I);
9731 SecondParam = SecondFnType->getExtParameterInfo(I);
9733 // Cannot merge unless everything except the noescape flag matches.
9734 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
9737 bool FirstNoEscape = FirstParam.isNoEscape();
9738 bool SecondNoEscape = SecondParam.isNoEscape();
9739 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9740 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9741 if (NewParamInfos.back().getOpaqueValue())
9742 NeedParamInfo = true;
9743 if (FirstNoEscape != IsNoEscape)
9744 CanUseFirst = false;
9745 if (SecondNoEscape != IsNoEscape)
9746 CanUseSecond = false;
9750 NewParamInfos.clear();
9755 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9756 ObjCLayouts[CD] = nullptr;
9759 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9760 /// 'RHS' attributes and returns the merged version; including for function
9762 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9763 QualType LHSCan = getCanonicalType(LHS),
9764 RHSCan = getCanonicalType(RHS);
9765 // If two types are identical, they are compatible.
9766 if (LHSCan == RHSCan)
9768 if (RHSCan->isFunctionType()) {
9769 if (!LHSCan->isFunctionType())
9771 QualType OldReturnType =
9772 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
9773 QualType NewReturnType =
9774 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
9775 QualType ResReturnType =
9776 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9777 if (ResReturnType.isNull())
9779 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9780 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9781 // In either case, use OldReturnType to build the new function type.
9782 const auto *F = LHS->castAs<FunctionType>();
9783 if (const auto *FPT = cast<FunctionProtoType>(F)) {
9784 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9785 EPI.ExtInfo = getFunctionExtInfo(LHS);
9786 QualType ResultType =
9787 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
9794 // If the qualifiers are different, the types can still be merged.
9795 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9796 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9797 if (LQuals != RQuals) {
9798 // If any of these qualifiers are different, we have a type mismatch.
9799 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9800 LQuals.getAddressSpace() != RQuals.getAddressSpace())
9803 // Exactly one GC qualifier difference is allowed: __strong is
9804 // okay if the other type has no GC qualifier but is an Objective
9805 // C object pointer (i.e. implicitly strong by default). We fix
9806 // this by pretending that the unqualified type was actually
9807 // qualified __strong.
9808 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9809 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9810 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9812 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9815 if (GC_L == Qualifiers::Strong)
9817 if (GC_R == Qualifiers::Strong)
9822 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9823 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9824 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9825 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9826 if (ResQT == LHSBaseQT)
9828 if (ResQT == RHSBaseQT)
9834 //===----------------------------------------------------------------------===//
9835 // Integer Predicates
9836 //===----------------------------------------------------------------------===//
9838 unsigned ASTContext::getIntWidth(QualType T) const {
9839 if (const auto *ET = T->getAs<EnumType>())
9840 T = ET->getDecl()->getIntegerType();
9841 if (T->isBooleanType())
9843 if(const auto *EIT = T->getAs<ExtIntType>())
9844 return EIT->getNumBits();
9845 // For builtin types, just use the standard type sizing method
9846 return (unsigned)getTypeSize(T);
9849 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
9850 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9853 // Turn <4 x signed int> -> <4 x unsigned int>
9854 if (const auto *VTy = T->getAs<VectorType>())
9855 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
9856 VTy->getNumElements(), VTy->getVectorKind());
9858 // For enums, we return the unsigned version of the base type.
9859 if (const auto *ETy = T->getAs<EnumType>())
9860 T = ETy->getDecl()->getIntegerType();
9862 switch (T->castAs<BuiltinType>()->getKind()) {
9863 case BuiltinType::Char_S:
9864 case BuiltinType::SChar:
9865 return UnsignedCharTy;
9866 case BuiltinType::Short:
9867 return UnsignedShortTy;
9868 case BuiltinType::Int:
9869 return UnsignedIntTy;
9870 case BuiltinType::Long:
9871 return UnsignedLongTy;
9872 case BuiltinType::LongLong:
9873 return UnsignedLongLongTy;
9874 case BuiltinType::Int128:
9875 return UnsignedInt128Ty;
9877 case BuiltinType::ShortAccum:
9878 return UnsignedShortAccumTy;
9879 case BuiltinType::Accum:
9880 return UnsignedAccumTy;
9881 case BuiltinType::LongAccum:
9882 return UnsignedLongAccumTy;
9883 case BuiltinType::SatShortAccum:
9884 return SatUnsignedShortAccumTy;
9885 case BuiltinType::SatAccum:
9886 return SatUnsignedAccumTy;
9887 case BuiltinType::SatLongAccum:
9888 return SatUnsignedLongAccumTy;
9889 case BuiltinType::ShortFract:
9890 return UnsignedShortFractTy;
9891 case BuiltinType::Fract:
9892 return UnsignedFractTy;
9893 case BuiltinType::LongFract:
9894 return UnsignedLongFractTy;
9895 case BuiltinType::SatShortFract:
9896 return SatUnsignedShortFractTy;
9897 case BuiltinType::SatFract:
9898 return SatUnsignedFractTy;
9899 case BuiltinType::SatLongFract:
9900 return SatUnsignedLongFractTy;
9902 llvm_unreachable("Unexpected signed integer or fixed point type");
9906 ASTMutationListener::~ASTMutationListener() = default;
9908 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9909 QualType ReturnType) {}
9911 //===----------------------------------------------------------------------===//
9912 // Builtin Type Computation
9913 //===----------------------------------------------------------------------===//
9915 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
9916 /// pointer over the consumed characters. This returns the resultant type. If
9917 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9918 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9919 /// a vector of "i*".
9921 /// RequiresICE is filled in on return to indicate whether the value is required
9922 /// to be an Integer Constant Expression.
9923 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
9924 ASTContext::GetBuiltinTypeError &Error,
9926 bool AllowTypeModifiers) {
9929 bool Signed = false, Unsigned = false;
9930 RequiresICE = false;
9932 // Read the prefixed modifiers first.
9935 bool IsSpecial = false;
9939 default: Done = true; --Str; break;
9944 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9945 assert(!Signed && "Can't use 'S' modifier multiple times!");
9949 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
9950 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
9954 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
9955 assert(HowLong <= 2 && "Can't have LLLL modifier");
9959 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9960 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9961 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
9965 if (Context.getTargetInfo().getLongWidth() == 32)
9969 // This modifier represents int64 type.
9970 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9971 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
9975 switch (Context.getTargetInfo().getInt64Type()) {
9977 llvm_unreachable("Unexpected integer type");
9978 case TargetInfo::SignedLong:
9981 case TargetInfo::SignedLongLong:
9987 // This modifier represents int32 type.
9988 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9989 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9993 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9995 llvm_unreachable("Unexpected integer type");
9996 case TargetInfo::SignedInt:
9999 case TargetInfo::SignedLong:
10002 case TargetInfo::SignedLongLong:
10008 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10009 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
10013 if (Context.getLangOpts().OpenCL)
10023 // Read the base type.
10025 default: llvm_unreachable("Unknown builtin type letter!");
10027 assert(HowLong == 0 && !Signed && !Unsigned &&
10028 "Bad modifiers used with 'y'!");
10029 Type = Context.BFloat16Ty;
10032 assert(HowLong == 0 && !Signed && !Unsigned &&
10033 "Bad modifiers used with 'v'!");
10034 Type = Context.VoidTy;
10037 assert(HowLong == 0 && !Signed && !Unsigned &&
10038 "Bad modifiers used with 'h'!");
10039 Type = Context.HalfTy;
10042 assert(HowLong == 0 && !Signed && !Unsigned &&
10043 "Bad modifiers used with 'f'!");
10044 Type = Context.FloatTy;
10047 assert(HowLong < 3 && !Signed && !Unsigned &&
10048 "Bad modifiers used with 'd'!");
10050 Type = Context.LongDoubleTy;
10051 else if (HowLong == 2)
10052 Type = Context.Float128Ty;
10054 Type = Context.DoubleTy;
10057 assert(HowLong == 0 && "Bad modifiers used with 's'!");
10059 Type = Context.UnsignedShortTy;
10061 Type = Context.ShortTy;
10065 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
10066 else if (HowLong == 2)
10067 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
10068 else if (HowLong == 1)
10069 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
10071 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
10074 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
10076 Type = Context.SignedCharTy;
10078 Type = Context.UnsignedCharTy;
10080 Type = Context.CharTy;
10082 case 'b': // boolean
10083 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
10084 Type = Context.BoolTy;
10086 case 'z': // size_t.
10087 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
10088 Type = Context.getSizeType();
10090 case 'w': // wchar_t.
10091 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
10092 Type = Context.getWideCharType();
10095 Type = Context.getCFConstantStringType();
10098 Type = Context.getObjCIdType();
10101 Type = Context.getObjCSelType();
10104 Type = Context.getObjCSuperType();
10107 Type = Context.getBuiltinVaListType();
10108 assert(!Type.isNull() && "builtin va list type not initialized!");
10111 // This is a "reference" to a va_list; however, what exactly
10112 // this means depends on how va_list is defined. There are two
10113 // different kinds of va_list: ones passed by value, and ones
10114 // passed by reference. An example of a by-value va_list is
10115 // x86, where va_list is a char*. An example of by-ref va_list
10116 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
10117 // we want this argument to be a char*&; for x86-64, we want
10118 // it to be a __va_list_tag*.
10119 Type = Context.getBuiltinVaListType();
10120 assert(!Type.isNull() && "builtin va list type not initialized!");
10121 if (Type->isArrayType())
10122 Type = Context.getArrayDecayedType(Type);
10124 Type = Context.getLValueReferenceType(Type);
10128 unsigned NumElements = strtoul(Str, &End, 10);
10129 assert(End != Str && "Missing vector size");
10132 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10133 RequiresICE, false);
10134 assert(!RequiresICE && "Can't require vector ICE");
10136 Type = Context.getScalableVectorType(ElementType, NumElements);
10141 unsigned NumElements = strtoul(Str, &End, 10);
10142 assert(End != Str && "Missing vector size");
10145 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10146 RequiresICE, false);
10147 assert(!RequiresICE && "Can't require vector ICE");
10149 // TODO: No way to make AltiVec vectors in builtins yet.
10150 Type = Context.getVectorType(ElementType, NumElements,
10151 VectorType::GenericVector);
10157 unsigned NumElements = strtoul(Str, &End, 10);
10158 assert(End != Str && "Missing vector size");
10162 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10164 Type = Context.getExtVectorType(ElementType, NumElements);
10168 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10170 assert(!RequiresICE && "Can't require complex ICE");
10171 Type = Context.getComplexType(ElementType);
10175 Type = Context.getPointerDiffType();
10178 Type = Context.getFILEType();
10179 if (Type.isNull()) {
10180 Error = ASTContext::GE_Missing_stdio;
10186 Type = Context.getsigjmp_bufType();
10188 Type = Context.getjmp_bufType();
10190 if (Type.isNull()) {
10191 Error = ASTContext::GE_Missing_setjmp;
10196 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
10197 Type = Context.getucontext_tType();
10199 if (Type.isNull()) {
10200 Error = ASTContext::GE_Missing_ucontext;
10205 Type = Context.getProcessIDType();
10209 // If there are modifiers and if we're allowed to parse them, go for it.
10210 Done = !AllowTypeModifiers;
10212 switch (char c = *Str++) {
10213 default: Done = true; --Str; break;
10216 // Both pointers and references can have their pointee types
10217 // qualified with an address space.
10219 unsigned AddrSpace = strtoul(Str, &End, 10);
10221 // Note AddrSpace == 0 is not the same as an unspecified address space.
10222 Type = Context.getAddrSpaceQualType(
10224 Context.getLangASForBuiltinAddressSpace(AddrSpace));
10228 Type = Context.getPointerType(Type);
10230 Type = Context.getLValueReferenceType(Type);
10233 // FIXME: There's no way to have a built-in with an rvalue ref arg.
10235 Type = Type.withConst();
10238 Type = Context.getVolatileType(Type);
10241 Type = Type.withRestrict();
10246 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
10247 "Integer constant 'I' type must be an integer");
10252 /// GetBuiltinType - Return the type for the specified builtin.
10253 QualType ASTContext::GetBuiltinType(unsigned Id,
10254 GetBuiltinTypeError &Error,
10255 unsigned *IntegerConstantArgs) const {
10256 const char *TypeStr = BuiltinInfo.getTypeString(Id);
10257 if (TypeStr[0] == '\0') {
10258 Error = GE_Missing_type;
10262 SmallVector<QualType, 8> ArgTypes;
10264 bool RequiresICE = false;
10266 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
10267 RequiresICE, true);
10268 if (Error != GE_None)
10271 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
10273 while (TypeStr[0] && TypeStr[0] != '.') {
10274 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
10275 if (Error != GE_None)
10278 // If this argument is required to be an IntegerConstantExpression and the
10279 // caller cares, fill in the bitmask we return.
10280 if (RequiresICE && IntegerConstantArgs)
10281 *IntegerConstantArgs |= 1 << ArgTypes.size();
10283 // Do array -> pointer decay. The builtin should use the decayed type.
10284 if (Ty->isArrayType())
10285 Ty = getArrayDecayedType(Ty);
10287 ArgTypes.push_back(Ty);
10290 if (Id == Builtin::BI__GetExceptionInfo)
10293 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
10294 "'.' should only occur at end of builtin type list!");
10296 bool Variadic = (TypeStr[0] == '.');
10298 FunctionType::ExtInfo EI(getDefaultCallingConvention(
10299 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
10300 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
10303 // We really shouldn't be making a no-proto type here.
10304 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
10305 return getFunctionNoProtoType(ResType, EI);
10307 FunctionProtoType::ExtProtoInfo EPI;
10309 EPI.Variadic = Variadic;
10310 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
10311 EPI.ExceptionSpec.Type =
10312 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
10314 return getFunctionType(ResType, ArgTypes, EPI);
10317 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
10318 const FunctionDecl *FD) {
10319 if (!FD->isExternallyVisible())
10320 return GVA_Internal;
10322 // Non-user-provided functions get emitted as weak definitions with every
10323 // use, no matter whether they've been explicitly instantiated etc.
10324 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
10325 if (!MD->isUserProvided())
10326 return GVA_DiscardableODR;
10328 GVALinkage External;
10329 switch (FD->getTemplateSpecializationKind()) {
10330 case TSK_Undeclared:
10331 case TSK_ExplicitSpecialization:
10332 External = GVA_StrongExternal;
10335 case TSK_ExplicitInstantiationDefinition:
10336 return GVA_StrongODR;
10338 // C++11 [temp.explicit]p10:
10339 // [ Note: The intent is that an inline function that is the subject of
10340 // an explicit instantiation declaration will still be implicitly
10341 // instantiated when used so that the body can be considered for
10342 // inlining, but that no out-of-line copy of the inline function would be
10343 // generated in the translation unit. -- end note ]
10344 case TSK_ExplicitInstantiationDeclaration:
10345 return GVA_AvailableExternally;
10347 case TSK_ImplicitInstantiation:
10348 External = GVA_DiscardableODR;
10352 if (!FD->isInlined())
10355 if ((!Context.getLangOpts().CPlusPlus &&
10356 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10357 !FD->hasAttr<DLLExportAttr>()) ||
10358 FD->hasAttr<GNUInlineAttr>()) {
10359 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
10361 // GNU or C99 inline semantics. Determine whether this symbol should be
10362 // externally visible.
10363 if (FD->isInlineDefinitionExternallyVisible())
10366 // C99 inline semantics, where the symbol is not externally visible.
10367 return GVA_AvailableExternally;
10370 // Functions specified with extern and inline in -fms-compatibility mode
10371 // forcibly get emitted. While the body of the function cannot be later
10372 // replaced, the function definition cannot be discarded.
10373 if (FD->isMSExternInline())
10374 return GVA_StrongODR;
10376 return GVA_DiscardableODR;
10379 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
10380 const Decl *D, GVALinkage L) {
10381 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
10382 // dllexport/dllimport on inline functions.
10383 if (D->hasAttr<DLLImportAttr>()) {
10384 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
10385 return GVA_AvailableExternally;
10386 } else if (D->hasAttr<DLLExportAttr>()) {
10387 if (L == GVA_DiscardableODR)
10388 return GVA_StrongODR;
10389 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
10390 D->hasAttr<CUDAGlobalAttr>()) {
10391 // Device-side functions with __global__ attribute must always be
10392 // visible externally so they can be launched from host.
10393 if (L == GVA_DiscardableODR || L == GVA_Internal)
10394 return GVA_StrongODR;
10399 /// Adjust the GVALinkage for a declaration based on what an external AST source
10400 /// knows about whether there can be other definitions of this declaration.
10402 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
10404 ExternalASTSource *Source = Ctx.getExternalSource();
10408 switch (Source->hasExternalDefinitions(D)) {
10409 case ExternalASTSource::EK_Never:
10410 // Other translation units rely on us to provide the definition.
10411 if (L == GVA_DiscardableODR)
10412 return GVA_StrongODR;
10415 case ExternalASTSource::EK_Always:
10416 return GVA_AvailableExternally;
10418 case ExternalASTSource::EK_ReplyHazy:
10424 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
10425 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
10426 adjustGVALinkageForAttributes(*this, FD,
10427 basicGVALinkageForFunction(*this, FD)));
10430 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
10431 const VarDecl *VD) {
10432 if (!VD->isExternallyVisible())
10433 return GVA_Internal;
10435 if (VD->isStaticLocal()) {
10436 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
10437 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
10438 LexicalContext = LexicalContext->getLexicalParent();
10440 // ObjC Blocks can create local variables that don't have a FunctionDecl
10442 if (!LexicalContext)
10443 return GVA_DiscardableODR;
10445 // Otherwise, let the static local variable inherit its linkage from the
10446 // nearest enclosing function.
10447 auto StaticLocalLinkage =
10448 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
10450 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
10451 // be emitted in any object with references to the symbol for the object it
10452 // contains, whether inline or out-of-line."
10453 // Similar behavior is observed with MSVC. An alternative ABI could use
10454 // StrongODR/AvailableExternally to match the function, but none are
10455 // known/supported currently.
10456 if (StaticLocalLinkage == GVA_StrongODR ||
10457 StaticLocalLinkage == GVA_AvailableExternally)
10458 return GVA_DiscardableODR;
10459 return StaticLocalLinkage;
10462 // MSVC treats in-class initialized static data members as definitions.
10463 // By giving them non-strong linkage, out-of-line definitions won't
10464 // cause link errors.
10465 if (Context.isMSStaticDataMemberInlineDefinition(VD))
10466 return GVA_DiscardableODR;
10468 // Most non-template variables have strong linkage; inline variables are
10469 // linkonce_odr or (occasionally, for compatibility) weak_odr.
10470 GVALinkage StrongLinkage;
10471 switch (Context.getInlineVariableDefinitionKind(VD)) {
10472 case ASTContext::InlineVariableDefinitionKind::None:
10473 StrongLinkage = GVA_StrongExternal;
10475 case ASTContext::InlineVariableDefinitionKind::Weak:
10476 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
10477 StrongLinkage = GVA_DiscardableODR;
10479 case ASTContext::InlineVariableDefinitionKind::Strong:
10480 StrongLinkage = GVA_StrongODR;
10484 switch (VD->getTemplateSpecializationKind()) {
10485 case TSK_Undeclared:
10486 return StrongLinkage;
10488 case TSK_ExplicitSpecialization:
10489 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10490 VD->isStaticDataMember()
10494 case TSK_ExplicitInstantiationDefinition:
10495 return GVA_StrongODR;
10497 case TSK_ExplicitInstantiationDeclaration:
10498 return GVA_AvailableExternally;
10500 case TSK_ImplicitInstantiation:
10501 return GVA_DiscardableODR;
10504 llvm_unreachable("Invalid Linkage!");
10507 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
10508 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
10509 adjustGVALinkageForAttributes(*this, VD,
10510 basicGVALinkageForVariable(*this, VD)));
10513 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
10514 if (const auto *VD = dyn_cast<VarDecl>(D)) {
10515 if (!VD->isFileVarDecl())
10517 // Global named register variables (GNU extension) are never emitted.
10518 if (VD->getStorageClass() == SC_Register)
10520 if (VD->getDescribedVarTemplate() ||
10521 isa<VarTemplatePartialSpecializationDecl>(VD))
10523 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10524 // We never need to emit an uninstantiated function template.
10525 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10527 } else if (isa<PragmaCommentDecl>(D))
10529 else if (isa<PragmaDetectMismatchDecl>(D))
10531 else if (isa<OMPRequiresDecl>(D))
10533 else if (isa<OMPThreadPrivateDecl>(D))
10534 return !D->getDeclContext()->isDependentContext();
10535 else if (isa<OMPAllocateDecl>(D))
10536 return !D->getDeclContext()->isDependentContext();
10537 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
10538 return !D->getDeclContext()->isDependentContext();
10539 else if (isa<ImportDecl>(D))
10544 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
10545 assert(getExternalSource() && "It's from an AST file; must have a source.");
10546 // On Windows, PCH files are built together with an object file. If this
10547 // declaration comes from such a PCH and DeclMustBeEmitted would return
10548 // true, it would have returned true and the decl would have been emitted
10549 // into that object file, so it doesn't need to be emitted here.
10550 // Note that decls are still emitted if they're referenced, as usual;
10551 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
10552 // if it's not referenced.
10554 // Explicit template instantiation definitions are tricky. If there was an
10555 // explicit template instantiation decl in the PCH before, it will look like
10556 // the definition comes from there, even if that was just the declaration.
10557 // (Explicit instantiation defs of variable templates always get emitted.)
10558 bool IsExpInstDef =
10559 isa<FunctionDecl>(D) &&
10560 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
10561 TSK_ExplicitInstantiationDefinition;
10563 // Implicit member function definitions, such as operator= might not be
10564 // marked as template specializations, since they're not coming from a
10565 // template but synthesized directly on the class.
10567 isa<CXXMethodDecl>(D) &&
10568 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
10569 TSK_ExplicitInstantiationDefinition;
10571 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
10575 // If this is a member of a class template, we do not need to emit it.
10576 if (D->getDeclContext()->isDependentContext())
10579 // Weak references don't produce any output by themselves.
10580 if (D->hasAttr<WeakRefAttr>())
10583 // Aliases and used decls are required.
10584 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
10587 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10588 // Forward declarations aren't required.
10589 if (!FD->doesThisDeclarationHaveABody())
10590 return FD->doesDeclarationForceExternallyVisibleDefinition();
10592 // Constructors and destructors are required.
10593 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10596 // The key function for a class is required. This rule only comes
10597 // into play when inline functions can be key functions, though.
10598 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
10599 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10600 const CXXRecordDecl *RD = MD->getParent();
10601 if (MD->isOutOfLine() && RD->isDynamicClass()) {
10602 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10603 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10609 GVALinkage Linkage = GetGVALinkageForFunction(FD);
10611 // static, static inline, always_inline, and extern inline functions can
10612 // always be deferred. Normal inline functions can be deferred in C99/C++.
10613 // Implicit template instantiations can also be deferred in C++.
10614 return !isDiscardableGVALinkage(Linkage);
10617 const auto *VD = cast<VarDecl>(D);
10618 assert(VD->isFileVarDecl() && "Expected file scoped var");
10620 // If the decl is marked as `declare target to`, it should be emitted for the
10621 // host and for the device.
10622 if (LangOpts.OpenMP &&
10623 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10626 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10627 !isMSStaticDataMemberInlineDefinition(VD))
10630 // Variables that can be needed in other TUs are required.
10631 auto Linkage = GetGVALinkageForVariable(VD);
10632 if (!isDiscardableGVALinkage(Linkage))
10635 // We never need to emit a variable that is available in another TU.
10636 if (Linkage == GVA_AvailableExternally)
10639 // Variables that have destruction with side-effects are required.
10640 if (VD->needsDestruction(*this))
10643 // Variables that have initialization with side-effects are required.
10644 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
10645 // We can get a value-dependent initializer during error recovery.
10646 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
10649 // Likewise, variables with tuple-like bindings are required if their
10650 // bindings have side-effects.
10651 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10652 for (const auto *BD : DD->bindings())
10653 if (const auto *BindingVD = BD->getHoldingVar())
10654 if (DeclMustBeEmitted(BindingVD))
10660 void ASTContext::forEachMultiversionedFunctionVersion(
10661 const FunctionDecl *FD,
10662 llvm::function_ref<void(FunctionDecl *)> Pred) const {
10663 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10664 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
10665 FD = FD->getMostRecentDecl();
10666 for (auto *CurDecl :
10667 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
10668 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
10669 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10670 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10671 SeenDecls.insert(CurFD);
10677 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
10679 bool IsBuiltin) const {
10680 // Pass through to the C++ ABI object
10682 return ABI->getDefaultMethodCallConv(IsVariadic);
10684 // Builtins ignore user-specified default calling convention and remain the
10685 // Target's default calling convention.
10687 switch (LangOpts.getDefaultCallingConv()) {
10688 case LangOptions::DCC_None:
10690 case LangOptions::DCC_CDecl:
10692 case LangOptions::DCC_FastCall:
10693 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10694 return CC_X86FastCall;
10696 case LangOptions::DCC_StdCall:
10698 return CC_X86StdCall;
10700 case LangOptions::DCC_VectorCall:
10701 // __vectorcall cannot be applied to variadic functions.
10703 return CC_X86VectorCall;
10705 case LangOptions::DCC_RegCall:
10706 // __regcall cannot be applied to variadic functions.
10708 return CC_X86RegCall;
10712 return Target->getDefaultCallingConv();
10715 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
10716 // Pass through to the C++ ABI object
10717 return ABI->isNearlyEmpty(RD);
10720 VTableContextBase *ASTContext::getVTableContext() {
10721 if (!VTContext.get()) {
10722 auto ABI = Target->getCXXABI();
10723 if (ABI.isMicrosoft())
10724 VTContext.reset(new MicrosoftVTableContext(*this));
10726 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
10727 ? ItaniumVTableContext::Relative
10728 : ItaniumVTableContext::Pointer;
10729 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
10732 return VTContext.get();
10735 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10738 switch (T->getCXXABI().getKind()) {
10739 case TargetCXXABI::Fuchsia:
10740 case TargetCXXABI::GenericAArch64:
10741 case TargetCXXABI::GenericItanium:
10742 case TargetCXXABI::GenericARM:
10743 case TargetCXXABI::GenericMIPS:
10744 case TargetCXXABI::iOS:
10745 case TargetCXXABI::iOS64:
10746 case TargetCXXABI::WebAssembly:
10747 case TargetCXXABI::WatchOS:
10748 case TargetCXXABI::XL:
10749 return ItaniumMangleContext::create(*this, getDiagnostics());
10750 case TargetCXXABI::Microsoft:
10751 return MicrosoftMangleContext::create(*this, getDiagnostics());
10753 llvm_unreachable("Unsupported ABI");
10756 CXXABI::~CXXABI() = default;
10758 size_t ASTContext::getSideTableAllocatedMemory() const {
10759 return ASTRecordLayouts.getMemorySize() +
10760 llvm::capacity_in_bytes(ObjCLayouts) +
10761 llvm::capacity_in_bytes(KeyFunctions) +
10762 llvm::capacity_in_bytes(ObjCImpls) +
10763 llvm::capacity_in_bytes(BlockVarCopyInits) +
10764 llvm::capacity_in_bytes(DeclAttrs) +
10765 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10766 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10767 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10768 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10769 llvm::capacity_in_bytes(OverriddenMethods) +
10770 llvm::capacity_in_bytes(Types) +
10771 llvm::capacity_in_bytes(VariableArrayTypes);
10774 /// getIntTypeForBitwidth -
10775 /// sets integer QualTy according to specified details:
10776 /// bitwidth, signed/unsigned.
10777 /// Returns empty type if there is no appropriate target types.
10778 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10779 unsigned Signed) const {
10780 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10781 CanQualType QualTy = getFromTargetType(Ty);
10782 if (!QualTy && DestWidth == 128)
10783 return Signed ? Int128Ty : UnsignedInt128Ty;
10787 /// getRealTypeForBitwidth -
10788 /// sets floating point QualTy according to specified bitwidth.
10789 /// Returns empty type if there is no appropriate target types.
10790 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
10791 bool ExplicitIEEE) const {
10792 TargetInfo::RealType Ty =
10793 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE);
10795 case TargetInfo::Float:
10797 case TargetInfo::Double:
10799 case TargetInfo::LongDouble:
10800 return LongDoubleTy;
10801 case TargetInfo::Float128:
10803 case TargetInfo::NoFloat:
10807 llvm_unreachable("Unhandled TargetInfo::RealType value");
10810 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10812 MangleNumbers[ND] = Number;
10815 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
10816 auto I = MangleNumbers.find(ND);
10817 return I != MangleNumbers.end() ? I->second : 1;
10820 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10822 StaticLocalNumbers[VD] = Number;
10825 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
10826 auto I = StaticLocalNumbers.find(VD);
10827 return I != StaticLocalNumbers.end() ? I->second : 1;
10830 MangleNumberingContext &
10831 ASTContext::getManglingNumberContext(const DeclContext *DC) {
10832 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10833 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
10835 MCtx = createMangleNumberingContext();
10839 MangleNumberingContext &
10840 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
10841 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10842 std::unique_ptr<MangleNumberingContext> &MCtx =
10843 ExtraMangleNumberingContexts[D];
10845 MCtx = createMangleNumberingContext();
10849 std::unique_ptr<MangleNumberingContext>
10850 ASTContext::createMangleNumberingContext() const {
10851 return ABI->createMangleNumberingContext();
10854 const CXXConstructorDecl *
10855 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10856 return ABI->getCopyConstructorForExceptionObject(
10857 cast<CXXRecordDecl>(RD->getFirstDecl()));
10860 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10861 CXXConstructorDecl *CD) {
10862 return ABI->addCopyConstructorForExceptionObject(
10863 cast<CXXRecordDecl>(RD->getFirstDecl()),
10864 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10867 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10868 TypedefNameDecl *DD) {
10869 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10873 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10874 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10877 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10878 DeclaratorDecl *DD) {
10879 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10882 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10883 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10886 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10887 ParamIndices[D] = index;
10890 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10891 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
10892 assert(I != ParamIndices.end() &&
10893 "ParmIndices lacks entry set by ParmVarDecl");
10897 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
10898 unsigned Length) const {
10899 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10900 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10901 EltTy = EltTy.withConst();
10903 EltTy = adjustStringLiteralBaseType(EltTy);
10905 // Get an array type for the string, according to C99 6.4.5. This includes
10906 // the null terminator character.
10907 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
10908 ArrayType::Normal, /*IndexTypeQuals*/ 0);
10912 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
10913 StringLiteral *&Result = StringLiteralCache[Key];
10915 Result = StringLiteral::Create(
10916 *this, Key, StringLiteral::Ascii,
10917 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10923 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
10924 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
10926 llvm::FoldingSetNodeID ID;
10927 MSGuidDecl::Profile(ID, Parts);
10930 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
10933 QualType GUIDType = getMSGuidType().withConst();
10934 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
10935 MSGuidDecls.InsertNode(New, InsertPos);
10939 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10940 const llvm::Triple &T = getTargetInfo().getTriple();
10941 if (!T.isOSDarwin())
10944 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10945 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10948 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10949 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10950 uint64_t Size = sizeChars.getQuantity();
10951 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10952 unsigned Align = alignChars.getQuantity();
10953 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10954 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10958 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10959 const ObjCMethodDecl *MethodImpl) {
10960 // No point trying to match an unavailable/deprecated mothod.
10961 if (MethodDecl->hasAttr<UnavailableAttr>()
10962 || MethodDecl->hasAttr<DeprecatedAttr>())
10964 if (MethodDecl->getObjCDeclQualifier() !=
10965 MethodImpl->getObjCDeclQualifier())
10967 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
10970 if (MethodDecl->param_size() != MethodImpl->param_size())
10973 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10974 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10975 EF = MethodDecl->param_end();
10976 IM != EM && IF != EF; ++IM, ++IF) {
10977 const ParmVarDecl *DeclVar = (*IF);
10978 const ParmVarDecl *ImplVar = (*IM);
10979 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10981 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10985 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
10988 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
10990 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
10991 AS = LangAS::Default;
10993 AS = QT->getPointeeType().getAddressSpace();
10995 return getTargetInfo().getNullPointerValue(AS);
10998 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10999 if (isTargetAddressSpace(AS))
11000 return toTargetAddressSpace(AS);
11002 return (*AddrSpaceMap)[(unsigned)AS];
11005 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
11006 assert(Ty->isFixedPointType());
11008 if (Ty->isSaturatedFixedPointType()) return Ty;
11010 switch (Ty->castAs<BuiltinType>()->getKind()) {
11012 llvm_unreachable("Not a fixed point type!");
11013 case BuiltinType::ShortAccum:
11014 return SatShortAccumTy;
11015 case BuiltinType::Accum:
11017 case BuiltinType::LongAccum:
11018 return SatLongAccumTy;
11019 case BuiltinType::UShortAccum:
11020 return SatUnsignedShortAccumTy;
11021 case BuiltinType::UAccum:
11022 return SatUnsignedAccumTy;
11023 case BuiltinType::ULongAccum:
11024 return SatUnsignedLongAccumTy;
11025 case BuiltinType::ShortFract:
11026 return SatShortFractTy;
11027 case BuiltinType::Fract:
11029 case BuiltinType::LongFract:
11030 return SatLongFractTy;
11031 case BuiltinType::UShortFract:
11032 return SatUnsignedShortFractTy;
11033 case BuiltinType::UFract:
11034 return SatUnsignedFractTy;
11035 case BuiltinType::ULongFract:
11036 return SatUnsignedLongFractTy;
11040 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
11041 if (LangOpts.OpenCL)
11042 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
11045 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
11047 return getLangASFromTargetAS(AS);
11050 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
11051 // doesn't include ASTContext.h
11053 clang::LazyGenerationalUpdatePtr<
11054 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
11055 clang::LazyGenerationalUpdatePtr<
11056 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
11057 const clang::ASTContext &Ctx, Decl *Value);
11059 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
11060 assert(Ty->isFixedPointType());
11062 const TargetInfo &Target = getTargetInfo();
11063 switch (Ty->castAs<BuiltinType>()->getKind()) {
11065 llvm_unreachable("Not a fixed point type!");
11066 case BuiltinType::ShortAccum:
11067 case BuiltinType::SatShortAccum:
11068 return Target.getShortAccumScale();
11069 case BuiltinType::Accum:
11070 case BuiltinType::SatAccum:
11071 return Target.getAccumScale();
11072 case BuiltinType::LongAccum:
11073 case BuiltinType::SatLongAccum:
11074 return Target.getLongAccumScale();
11075 case BuiltinType::UShortAccum:
11076 case BuiltinType::SatUShortAccum:
11077 return Target.getUnsignedShortAccumScale();
11078 case BuiltinType::UAccum:
11079 case BuiltinType::SatUAccum:
11080 return Target.getUnsignedAccumScale();
11081 case BuiltinType::ULongAccum:
11082 case BuiltinType::SatULongAccum:
11083 return Target.getUnsignedLongAccumScale();
11084 case BuiltinType::ShortFract:
11085 case BuiltinType::SatShortFract:
11086 return Target.getShortFractScale();
11087 case BuiltinType::Fract:
11088 case BuiltinType::SatFract:
11089 return Target.getFractScale();
11090 case BuiltinType::LongFract:
11091 case BuiltinType::SatLongFract:
11092 return Target.getLongFractScale();
11093 case BuiltinType::UShortFract:
11094 case BuiltinType::SatUShortFract:
11095 return Target.getUnsignedShortFractScale();
11096 case BuiltinType::UFract:
11097 case BuiltinType::SatUFract:
11098 return Target.getUnsignedFractScale();
11099 case BuiltinType::ULongFract:
11100 case BuiltinType::SatULongFract:
11101 return Target.getUnsignedLongFractScale();
11105 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
11106 assert(Ty->isFixedPointType());
11108 const TargetInfo &Target = getTargetInfo();
11109 switch (Ty->castAs<BuiltinType>()->getKind()) {
11111 llvm_unreachable("Not a fixed point type!");
11112 case BuiltinType::ShortAccum:
11113 case BuiltinType::SatShortAccum:
11114 return Target.getShortAccumIBits();
11115 case BuiltinType::Accum:
11116 case BuiltinType::SatAccum:
11117 return Target.getAccumIBits();
11118 case BuiltinType::LongAccum:
11119 case BuiltinType::SatLongAccum:
11120 return Target.getLongAccumIBits();
11121 case BuiltinType::UShortAccum:
11122 case BuiltinType::SatUShortAccum:
11123 return Target.getUnsignedShortAccumIBits();
11124 case BuiltinType::UAccum:
11125 case BuiltinType::SatUAccum:
11126 return Target.getUnsignedAccumIBits();
11127 case BuiltinType::ULongAccum:
11128 case BuiltinType::SatULongAccum:
11129 return Target.getUnsignedLongAccumIBits();
11130 case BuiltinType::ShortFract:
11131 case BuiltinType::SatShortFract:
11132 case BuiltinType::Fract:
11133 case BuiltinType::SatFract:
11134 case BuiltinType::LongFract:
11135 case BuiltinType::SatLongFract:
11136 case BuiltinType::UShortFract:
11137 case BuiltinType::SatUShortFract:
11138 case BuiltinType::UFract:
11139 case BuiltinType::SatUFract:
11140 case BuiltinType::ULongFract:
11141 case BuiltinType::SatULongFract:
11146 FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
11147 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
11148 "Can only get the fixed point semantics for a "
11149 "fixed point or integer type.");
11150 if (Ty->isIntegerType())
11151 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
11152 Ty->isSignedIntegerType());
11154 bool isSigned = Ty->isSignedFixedPointType();
11155 return FixedPointSemantics(
11156 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
11157 Ty->isSaturatedFixedPointType(),
11158 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
11161 APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
11162 assert(Ty->isFixedPointType());
11163 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
11166 APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
11167 assert(Ty->isFixedPointType());
11168 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
11171 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
11172 assert(Ty->isUnsignedFixedPointType() &&
11173 "Expected unsigned fixed point type");
11175 switch (Ty->castAs<BuiltinType>()->getKind()) {
11176 case BuiltinType::UShortAccum:
11177 return ShortAccumTy;
11178 case BuiltinType::UAccum:
11180 case BuiltinType::ULongAccum:
11181 return LongAccumTy;
11182 case BuiltinType::SatUShortAccum:
11183 return SatShortAccumTy;
11184 case BuiltinType::SatUAccum:
11186 case BuiltinType::SatULongAccum:
11187 return SatLongAccumTy;
11188 case BuiltinType::UShortFract:
11189 return ShortFractTy;
11190 case BuiltinType::UFract:
11192 case BuiltinType::ULongFract:
11193 return LongFractTy;
11194 case BuiltinType::SatUShortFract:
11195 return SatShortFractTy;
11196 case BuiltinType::SatUFract:
11198 case BuiltinType::SatULongFract:
11199 return SatLongFractTy;
11201 llvm_unreachable("Unexpected unsigned fixed point type");
11206 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
11207 assert(TD != nullptr);
11208 ParsedTargetAttr ParsedAttr = TD->parse();
11210 ParsedAttr.Features.erase(
11211 llvm::remove_if(ParsedAttr.Features,
11212 [&](const std::string &Feat) {
11213 return !Target->isValidFeatureName(
11214 StringRef{Feat}.substr(1));
11216 ParsedAttr.Features.end());
11220 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11221 const FunctionDecl *FD) const {
11223 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
11225 Target->initFeatureMap(FeatureMap, getDiagnostics(),
11226 Target->getTargetOpts().CPU,
11227 Target->getTargetOpts().Features);
11230 // Fills in the supplied string map with the set of target features for the
11231 // passed in function.
11232 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11233 GlobalDecl GD) const {
11234 StringRef TargetCPU = Target->getTargetOpts().CPU;
11235 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
11236 if (const auto *TD = FD->getAttr<TargetAttr>()) {
11237 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
11239 // Make a copy of the features as passed on the command line into the
11240 // beginning of the additional features from the function to override.
11241 ParsedAttr.Features.insert(
11242 ParsedAttr.Features.begin(),
11243 Target->getTargetOpts().FeaturesAsWritten.begin(),
11244 Target->getTargetOpts().FeaturesAsWritten.end());
11246 if (ParsedAttr.Architecture != "" &&
11247 Target->isValidCPUName(ParsedAttr.Architecture))
11248 TargetCPU = ParsedAttr.Architecture;
11250 // Now populate the feature map, first with the TargetCPU which is either
11251 // the default or a new one from the target attribute string. Then we'll use
11252 // the passed in features (FeaturesAsWritten) along with the new ones from
11254 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
11255 ParsedAttr.Features);
11256 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
11257 llvm::SmallVector<StringRef, 32> FeaturesTmp;
11258 Target->getCPUSpecificCPUDispatchFeatures(
11259 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
11260 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
11261 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
11263 FeatureMap = Target->getTargetOpts().FeatureMap;
11267 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
11268 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
11269 return *OMPTraitInfoVector.back();
11272 const DiagnosticBuilder &
11273 clang::operator<<(const DiagnosticBuilder &DB,
11274 const ASTContext::SectionInfo &Section) {
11276 return DB << Section.Decl;
11277 return DB << "a prior #pragma section";