clang 20.0.0git
ASTContext.cpp
Go to the documentation of this file.
1//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTContext interface.
10//
11//===----------------------------------------------------------------------===//
12
14#include "CXXABI.h"
15#include "Interp/Context.h"
16#include "clang/AST/APValue.h"
20#include "clang/AST/Attr.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"
28#include "clang/AST/DeclObjC.h"
33#include "clang/AST/Expr.h"
34#include "clang/AST/ExprCXX.h"
37#include "clang/AST/Mangle.h"
43#include "clang/AST/Stmt.h"
47#include "clang/AST/Type.h"
48#include "clang/AST/TypeLoc.h"
56#include "clang/Basic/LLVM.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
69#include "llvm/ADT/APFixedPoint.h"
70#include "llvm/ADT/APInt.h"
71#include "llvm/ADT/APSInt.h"
72#include "llvm/ADT/ArrayRef.h"
73#include "llvm/ADT/DenseMap.h"
74#include "llvm/ADT/DenseSet.h"
75#include "llvm/ADT/FoldingSet.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/Frontend/OpenMP/OMPIRBuilder.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/MD5.h"
88#include "llvm/Support/MathExtras.h"
89#include "llvm/Support/SipHash.h"
90#include "llvm/Support/raw_ostream.h"
91#include "llvm/TargetParser/AArch64TargetParser.h"
92#include "llvm/TargetParser/Triple.h"
93#include <algorithm>
94#include <cassert>
95#include <cstddef>
96#include <cstdint>
97#include <cstdlib>
98#include <map>
99#include <memory>
100#include <optional>
101#include <string>
102#include <tuple>
103#include <utility>
104
105using namespace clang;
106
117
118/// \returns The locations that are relevant when searching for Doc comments
119/// related to \p D.
122 assert(D);
123
124 // User can not attach documentation to implicit declarations.
125 if (D->isImplicit())
126 return {};
127
128 // User can not attach documentation to implicit instantiations.
129 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
130 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
131 return {};
132 }
133
134 if (const auto *VD = dyn_cast<VarDecl>(D)) {
135 if (VD->isStaticDataMember() &&
136 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
137 return {};
138 }
139
140 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
141 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
142 return {};
143 }
144
145 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
146 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
147 if (TSK == TSK_ImplicitInstantiation ||
148 TSK == TSK_Undeclared)
149 return {};
150 }
151
152 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
153 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
154 return {};
155 }
156 if (const auto *TD = dyn_cast<TagDecl>(D)) {
157 // When tag declaration (but not definition!) is part of the
158 // decl-specifier-seq of some other declaration, it doesn't get comment
159 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
160 return {};
161 }
162 // TODO: handle comments for function parameters properly.
163 if (isa<ParmVarDecl>(D))
164 return {};
165
166 // TODO: we could look up template parameter documentation in the template
167 // documentation.
168 if (isa<TemplateTypeParmDecl>(D) ||
169 isa<NonTypeTemplateParmDecl>(D) ||
170 isa<TemplateTemplateParmDecl>(D))
171 return {};
172
174 // Find declaration location.
175 // For Objective-C declarations we generally don't expect to have multiple
176 // declarators, thus use declaration starting location as the "declaration
177 // location".
178 // For all other declarations multiple declarators are used quite frequently,
179 // so we use the location of the identifier as the "declaration location".
180 SourceLocation BaseLocation;
181 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
182 isa<ObjCPropertyDecl>(D) || isa<RedeclarableTemplateDecl>(D) ||
183 isa<ClassTemplateSpecializationDecl>(D) ||
184 // Allow association with Y across {} in `typedef struct X {} Y`.
185 isa<TypedefDecl>(D))
186 BaseLocation = D->getBeginLoc();
187 else
188 BaseLocation = D->getLocation();
189
190 if (!D->getLocation().isMacroID()) {
191 Locations.emplace_back(BaseLocation);
192 } else {
193 const auto *DeclCtx = D->getDeclContext();
194
195 // When encountering definitions generated from a macro (that are not
196 // contained by another declaration in the macro) we need to try and find
197 // the comment at the location of the expansion but if there is no comment
198 // there we should retry to see if there is a comment inside the macro as
199 // well. To this end we return first BaseLocation to first look at the
200 // expansion site, the second value is the spelling location of the
201 // beginning of the declaration defined inside the macro.
202 if (!(DeclCtx &&
203 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
204 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
205 }
206
207 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
208 // we don't refer to the macro argument location at the expansion site (this
209 // can happen if the name's spelling is provided via macro argument), and
210 // always to the declaration itself.
211 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
212 }
213
214 return Locations;
215}
216
218 const Decl *D, const SourceLocation RepresentativeLocForDecl,
219 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
220 // If the declaration doesn't map directly to a location in a file, we
221 // can't find the comment.
222 if (RepresentativeLocForDecl.isInvalid() ||
223 !RepresentativeLocForDecl.isFileID())
224 return nullptr;
225
226 // If there are no comments anywhere, we won't find anything.
227 if (CommentsInTheFile.empty())
228 return nullptr;
229
230 // Decompose the location for the declaration and find the beginning of the
231 // file buffer.
232 const std::pair<FileID, unsigned> DeclLocDecomp =
233 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
234
235 // Slow path.
236 auto OffsetCommentBehindDecl =
237 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
238
239 // First check whether we have a trailing comment.
240 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
241 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
242 if ((CommentBehindDecl->isDocumentation() ||
243 LangOpts.CommentOpts.ParseAllComments) &&
244 CommentBehindDecl->isTrailingComment() &&
245 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
246 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
247
248 // Check that Doxygen trailing comment comes after the declaration, starts
249 // on the same line and in the same file as the declaration.
250 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
251 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
252 OffsetCommentBehindDecl->first)) {
253 return CommentBehindDecl;
254 }
255 }
256 }
257
258 // The comment just after the declaration was not a trailing comment.
259 // Let's look at the previous comment.
260 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
261 return nullptr;
262
263 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
264 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
265
266 // Check that we actually have a non-member Doxygen comment.
267 if (!(CommentBeforeDecl->isDocumentation() ||
268 LangOpts.CommentOpts.ParseAllComments) ||
269 CommentBeforeDecl->isTrailingComment())
270 return nullptr;
271
272 // Decompose the end of the comment.
273 const unsigned CommentEndOffset =
274 Comments.getCommentEndOffset(CommentBeforeDecl);
275
276 // Get the corresponding buffer.
277 bool Invalid = false;
278 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
279 &Invalid).data();
280 if (Invalid)
281 return nullptr;
282
283 // Extract text between the comment and declaration.
284 StringRef Text(Buffer + CommentEndOffset,
285 DeclLocDecomp.second - CommentEndOffset);
286
287 // There should be no other declarations or preprocessor directives between
288 // comment and declaration.
289 if (Text.find_last_of(";{}#@") != StringRef::npos)
290 return nullptr;
291
292 return CommentBeforeDecl;
293}
294
296 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
297
298 for (const auto DeclLoc : DeclLocs) {
299 // If the declaration doesn't map directly to a location in a file, we
300 // can't find the comment.
301 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
302 continue;
303
306 CommentsLoaded = true;
307 }
308
309 if (Comments.empty())
310 continue;
311
312 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
313 if (!File.isValid())
314 continue;
315
316 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
317 if (!CommentsInThisFile || CommentsInThisFile->empty())
318 continue;
319
320 if (RawComment *Comment =
321 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
322 return Comment;
323 }
324
325 return nullptr;
326}
327
329 assert(LangOpts.RetainCommentsFromSystemHeaders ||
330 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
331 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
332}
333
334/// If we have a 'templated' declaration for a template, adjust 'D' to
335/// refer to the actual template.
336/// If we have an implicit instantiation, adjust 'D' to refer to template.
337static const Decl &adjustDeclToTemplate(const Decl &D) {
338 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
339 // Is this function declaration part of a function template?
340 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
341 return *FTD;
342
343 // Nothing to do if function is not an implicit instantiation.
344 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
345 return D;
346
347 // Function is an implicit instantiation of a function template?
348 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
349 return *FTD;
350
351 // Function is instantiated from a member definition of a class template?
352 if (const FunctionDecl *MemberDecl =
354 return *MemberDecl;
355
356 return D;
357 }
358 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
359 // Static data member is instantiated from a member definition of a class
360 // template?
361 if (VD->isStaticDataMember())
362 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
363 return *MemberDecl;
364
365 return D;
366 }
367 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
368 // Is this class declaration part of a class template?
369 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
370 return *CTD;
371
372 // Class is an implicit instantiation of a class template or partial
373 // specialization?
374 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
375 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
376 return D;
377 llvm::PointerUnion<ClassTemplateDecl *,
380 return PU.is<ClassTemplateDecl *>()
381 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
382 : *static_cast<const Decl *>(
384 }
385
386 // Class is instantiated from a member definition of a class template?
387 if (const MemberSpecializationInfo *Info =
388 CRD->getMemberSpecializationInfo())
389 return *Info->getInstantiatedFrom();
390
391 return D;
392 }
393 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
394 // Enum is instantiated from a member definition of a class template?
395 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
396 return *MemberDecl;
397
398 return D;
399 }
400 // FIXME: Adjust alias templates?
401 return D;
402}
403
405 const Decl *D,
406 const Decl **OriginalDecl) const {
407 if (!D) {
408 if (OriginalDecl)
409 OriginalDecl = nullptr;
410 return nullptr;
411 }
412
414
415 // Any comment directly attached to D?
416 {
417 auto DeclComment = DeclRawComments.find(D);
418 if (DeclComment != DeclRawComments.end()) {
419 if (OriginalDecl)
420 *OriginalDecl = D;
421 return DeclComment->second;
422 }
423 }
424
425 // Any comment attached to any redeclaration of D?
426 const Decl *CanonicalD = D->getCanonicalDecl();
427 if (!CanonicalD)
428 return nullptr;
429
430 {
431 auto RedeclComment = RedeclChainComments.find(CanonicalD);
432 if (RedeclComment != RedeclChainComments.end()) {
433 if (OriginalDecl)
434 *OriginalDecl = RedeclComment->second;
435 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
436 assert(CommentAtRedecl != DeclRawComments.end() &&
437 "This decl is supposed to have comment attached.");
438 return CommentAtRedecl->second;
439 }
440 }
441
442 // Any redeclarations of D that we haven't checked for comments yet?
443 // We can't use DenseMap::iterator directly since it'd get invalid.
444 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
445 return CommentlessRedeclChains.lookup(CanonicalD);
446 }();
447
448 for (const auto Redecl : D->redecls()) {
449 assert(Redecl);
450 // Skip all redeclarations that have been checked previously.
451 if (LastCheckedRedecl) {
452 if (LastCheckedRedecl == Redecl) {
453 LastCheckedRedecl = nullptr;
454 }
455 continue;
456 }
457 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
458 if (RedeclComment) {
459 cacheRawCommentForDecl(*Redecl, *RedeclComment);
460 if (OriginalDecl)
461 *OriginalDecl = Redecl;
462 return RedeclComment;
463 }
464 CommentlessRedeclChains[CanonicalD] = Redecl;
465 }
466
467 if (OriginalDecl)
468 *OriginalDecl = nullptr;
469 return nullptr;
470}
471
473 const RawComment &Comment) const {
474 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
475 DeclRawComments.try_emplace(&OriginalD, &Comment);
476 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
477 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
478 CommentlessRedeclChains.erase(CanonicalDecl);
479}
480
481static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
483 const DeclContext *DC = ObjCMethod->getDeclContext();
484 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
485 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
486 if (!ID)
487 return;
488 // Add redeclared method here.
489 for (const auto *Ext : ID->known_extensions()) {
490 if (ObjCMethodDecl *RedeclaredMethod =
491 Ext->getMethod(ObjCMethod->getSelector(),
492 ObjCMethod->isInstanceMethod()))
493 Redeclared.push_back(RedeclaredMethod);
494 }
495 }
496}
497
499 const Preprocessor *PP) {
500 if (Comments.empty() || Decls.empty())
501 return;
502
503 FileID File;
504 for (const Decl *D : Decls) {
505 if (D->isInvalidDecl())
506 continue;
507
510 if (Loc.isValid()) {
511 // See if there are any new comments that are not attached to a decl.
512 // The location doesn't have to be precise - we care only about the file.
513 File = SourceMgr.getDecomposedLoc(Loc).first;
514 break;
515 }
516 }
517
518 if (File.isInvalid())
519 return;
520
521 auto CommentsInThisFile = Comments.getCommentsInFile(File);
522 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
523 CommentsInThisFile->rbegin()->second->isAttached())
524 return;
525
526 // There is at least one comment not attached to a decl.
527 // Maybe it should be attached to one of Decls?
528 //
529 // Note that this way we pick up not only comments that precede the
530 // declaration, but also comments that *follow* the declaration -- thanks to
531 // the lookahead in the lexer: we've consumed the semicolon and looked
532 // ahead through comments.
533 for (const Decl *D : Decls) {
534 assert(D);
535 if (D->isInvalidDecl())
536 continue;
537
539
540 if (DeclRawComments.count(D) > 0)
541 continue;
542
543 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
544
545 for (const auto DeclLoc : DeclLocs) {
546 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
547 continue;
548
549 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
550 D, DeclLoc, *CommentsInThisFile)) {
551 cacheRawCommentForDecl(*D, *DocComment);
552 comments::FullComment *FC = DocComment->parse(*this, PP, D);
554 break;
555 }
556 }
557 }
558}
559
561 const Decl *D) const {
562 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
563 ThisDeclInfo->CommentDecl = D;
564 ThisDeclInfo->IsFilled = false;
565 ThisDeclInfo->fill();
566 ThisDeclInfo->CommentDecl = FC->getDecl();
567 if (!ThisDeclInfo->TemplateParameters)
568 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
570 new (*this) comments::FullComment(FC->getBlocks(),
571 ThisDeclInfo);
572 return CFC;
573}
574
577 return RC ? RC->parse(*this, nullptr, D) : nullptr;
578}
579
581 const Decl *D,
582 const Preprocessor *PP) const {
583 if (!D || D->isInvalidDecl())
584 return nullptr;
586
587 const Decl *Canonical = D->getCanonicalDecl();
588 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
589 ParsedComments.find(Canonical);
590
591 if (Pos != ParsedComments.end()) {
592 if (Canonical != D) {
593 comments::FullComment *FC = Pos->second;
595 return CFC;
596 }
597 return Pos->second;
598 }
599
600 const Decl *OriginalDecl = nullptr;
601
602 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
603 if (!RC) {
604 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
606 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
607 if (OMD && OMD->isPropertyAccessor())
608 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
609 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
610 return cloneFullComment(FC, D);
611 if (OMD)
612 addRedeclaredMethods(OMD, Overridden);
613 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
614 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
615 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
616 return cloneFullComment(FC, D);
617 }
618 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
619 // Attach any tag type's documentation to its typedef if latter
620 // does not have one of its own.
621 QualType QT = TD->getUnderlyingType();
622 if (const auto *TT = QT->getAs<TagType>())
623 if (const Decl *TD = TT->getDecl())
625 return cloneFullComment(FC, D);
626 }
627 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
628 while (IC->getSuperClass()) {
629 IC = IC->getSuperClass();
631 return cloneFullComment(FC, D);
632 }
633 }
634 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
635 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
637 return cloneFullComment(FC, D);
638 }
639 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
640 if (!(RD = RD->getDefinition()))
641 return nullptr;
642 // Check non-virtual bases.
643 for (const auto &I : RD->bases()) {
644 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
645 continue;
646 QualType Ty = I.getType();
647 if (Ty.isNull())
648 continue;
650 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
651 continue;
652
654 return cloneFullComment(FC, D);
655 }
656 }
657 // Check virtual bases.
658 for (const auto &I : RD->vbases()) {
659 if (I.getAccessSpecifier() != AS_public)
660 continue;
661 QualType Ty = I.getType();
662 if (Ty.isNull())
663 continue;
664 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
665 if (!(VirtualBase= VirtualBase->getDefinition()))
666 continue;
668 return cloneFullComment(FC, D);
669 }
670 }
671 }
672 return nullptr;
673 }
674
675 // If the RawComment was attached to other redeclaration of this Decl, we
676 // should parse the comment in context of that other Decl. This is important
677 // because comments can contain references to parameter names which can be
678 // different across redeclarations.
679 if (D != OriginalDecl && OriginalDecl)
680 return getCommentForDecl(OriginalDecl, PP);
681
682 comments::FullComment *FC = RC->parse(*this, PP, D);
683 ParsedComments[Canonical] = FC;
684 return FC;
685}
686
687void
688ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
689 const ASTContext &C,
691 ID.AddInteger(Parm->getDepth());
692 ID.AddInteger(Parm->getPosition());
693 ID.AddBoolean(Parm->isParameterPack());
694
696 ID.AddInteger(Params->size());
698 PEnd = Params->end();
699 P != PEnd; ++P) {
700 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
701 ID.AddInteger(0);
702 ID.AddBoolean(TTP->isParameterPack());
703 if (TTP->isExpandedParameterPack()) {
704 ID.AddBoolean(true);
705 ID.AddInteger(TTP->getNumExpansionParameters());
706 } else
707 ID.AddBoolean(false);
708 continue;
709 }
710
711 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
712 ID.AddInteger(1);
713 ID.AddBoolean(NTTP->isParameterPack());
714 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
715 .getAsOpaquePtr());
716 if (NTTP->isExpandedParameterPack()) {
717 ID.AddBoolean(true);
718 ID.AddInteger(NTTP->getNumExpansionTypes());
719 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
720 QualType T = NTTP->getExpansionType(I);
721 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
722 }
723 } else
724 ID.AddBoolean(false);
725 continue;
726 }
727
728 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
729 ID.AddInteger(2);
730 Profile(ID, C, TTP);
731 }
732}
733
735ASTContext::getCanonicalTemplateTemplateParmDecl(
736 TemplateTemplateParmDecl *TTP) const {
737 // Check if we already have a canonical template template parameter.
738 llvm::FoldingSetNodeID ID;
739 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
740 void *InsertPos = nullptr;
741 CanonicalTemplateTemplateParm *Canonical
742 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
743 if (Canonical)
744 return Canonical->getParam();
745
746 // Build a canonical template parameter list.
748 SmallVector<NamedDecl *, 4> CanonParams;
749 CanonParams.reserve(Params->size());
751 PEnd = Params->end();
752 P != PEnd; ++P) {
753 // Note that, per C++20 [temp.over.link]/6, when determining whether
754 // template-parameters are equivalent, constraints are ignored.
755 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
758 TTP->getDepth(), TTP->getIndex(), nullptr, false,
759 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
761 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
762 : std::nullopt);
763 CanonParams.push_back(NewTTP);
764 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
768 if (NTTP->isExpandedParameterPack()) {
769 SmallVector<QualType, 2> ExpandedTypes;
771 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
772 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
773 ExpandedTInfos.push_back(
774 getTrivialTypeSourceInfo(ExpandedTypes.back()));
775 }
776
780 NTTP->getDepth(),
781 NTTP->getPosition(), nullptr,
782 T,
783 TInfo,
784 ExpandedTypes,
785 ExpandedTInfos);
786 } else {
790 NTTP->getDepth(),
791 NTTP->getPosition(), nullptr,
792 T,
793 NTTP->isParameterPack(),
794 TInfo);
795 }
796 CanonParams.push_back(Param);
797 } else
798 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
799 cast<TemplateTemplateParmDecl>(*P)));
800 }
801
804 TTP->getPosition(), TTP->isParameterPack(), nullptr, /*Typename=*/false,
806 CanonParams, SourceLocation(),
807 /*RequiresClause=*/nullptr));
808
809 // Get the new insert position for the node we care about.
810 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
811 assert(!Canonical && "Shouldn't be in the map!");
812 (void)Canonical;
813
814 // Create the canonical template template parameter entry.
815 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
816 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
817 return CanonTTP;
818}
819
821 auto Kind = getTargetInfo().getCXXABI().getKind();
822 return getLangOpts().CXXABI.value_or(Kind);
823}
824
825CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
826 if (!LangOpts.CPlusPlus) return nullptr;
827
828 switch (getCXXABIKind()) {
829 case TargetCXXABI::AppleARM64:
830 case TargetCXXABI::Fuchsia:
831 case TargetCXXABI::GenericARM: // Same as Itanium at this level
832 case TargetCXXABI::iOS:
833 case TargetCXXABI::WatchOS:
834 case TargetCXXABI::GenericAArch64:
835 case TargetCXXABI::GenericMIPS:
836 case TargetCXXABI::GenericItanium:
837 case TargetCXXABI::WebAssembly:
838 case TargetCXXABI::XL:
839 return CreateItaniumCXXABI(*this);
840 case TargetCXXABI::Microsoft:
841 return CreateMicrosoftCXXABI(*this);
842 }
843 llvm_unreachable("Invalid CXXABI type!");
844}
845
847 if (!InterpContext) {
848 InterpContext.reset(new interp::Context(*this));
849 }
850 return *InterpContext.get();
851}
852
854 if (!ParentMapCtx)
855 ParentMapCtx.reset(new ParentMapContext(*this));
856 return *ParentMapCtx.get();
857}
858
860 const LangOptions &LangOpts) {
861 switch (LangOpts.getAddressSpaceMapMangling()) {
863 return TI.useAddressSpaceMapMangling();
865 return true;
867 return false;
868 }
869 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
870}
871
873 IdentifierTable &idents, SelectorTable &sels,
874 Builtin::Context &builtins, TranslationUnitKind TUKind)
875 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
876 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
877 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
878 DependentSizedMatrixTypes(this_()),
879 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
880 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
881 TemplateSpecializationTypes(this_()),
882 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
883 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
884 ArrayParameterTypes(this_()), CanonTemplateTemplateParms(this_()),
885 SourceMgr(SM), LangOpts(LOpts),
886 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
887 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
888 LangOpts.XRayNeverInstrumentFiles,
889 LangOpts.XRayAttrListFiles, SM)),
890 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
891 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
892 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
893 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
894 CompCategories(this_()), LastSDM(nullptr, 0) {
896}
897
899 // Release the DenseMaps associated with DeclContext objects.
900 // FIXME: Is this the ideal solution?
901 ReleaseDeclContextMaps();
902
903 // Call all of the deallocation functions on all of their targets.
904 for (auto &Pair : Deallocations)
905 (Pair.first)(Pair.second);
906 Deallocations.clear();
907
908 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
909 // because they can contain DenseMaps.
910 for (llvm::DenseMap<const ObjCContainerDecl*,
911 const ASTRecordLayout*>::iterator
912 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
913 // Increment in loop to prevent using deallocated memory.
914 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
915 R->Destroy(*this);
916 ObjCLayouts.clear();
917
918 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
919 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
920 // Increment in loop to prevent using deallocated memory.
921 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
922 R->Destroy(*this);
923 }
924 ASTRecordLayouts.clear();
925
926 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
927 AEnd = DeclAttrs.end();
928 A != AEnd; ++A)
929 A->second->~AttrVec();
930 DeclAttrs.clear();
931
932 for (const auto &Value : ModuleInitializers)
933 Value.second->~PerModuleInitializers();
934 ModuleInitializers.clear();
935}
936
938
939void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
940 TraversalScope = TopLevelDecls;
942}
943
944void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
945 Deallocations.push_back({Callback, Data});
946}
947
948void
950 ExternalSource = std::move(Source);
951}
952
954 llvm::errs() << "\n*** AST Context Stats:\n";
955 llvm::errs() << " " << Types.size() << " types total.\n";
956
957 unsigned counts[] = {
958#define TYPE(Name, Parent) 0,
959#define ABSTRACT_TYPE(Name, Parent)
960#include "clang/AST/TypeNodes.inc"
961 0 // Extra
962 };
963
964 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
965 Type *T = Types[i];
966 counts[(unsigned)T->getTypeClass()]++;
967 }
968
969 unsigned Idx = 0;
970 unsigned TotalBytes = 0;
971#define TYPE(Name, Parent) \
972 if (counts[Idx]) \
973 llvm::errs() << " " << counts[Idx] << " " << #Name \
974 << " types, " << sizeof(Name##Type) << " each " \
975 << "(" << counts[Idx] * sizeof(Name##Type) \
976 << " bytes)\n"; \
977 TotalBytes += counts[Idx] * sizeof(Name##Type); \
978 ++Idx;
979#define ABSTRACT_TYPE(Name, Parent)
980#include "clang/AST/TypeNodes.inc"
981
982 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
983
984 // Implicit special member functions.
985 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
987 << " implicit default constructors created\n";
988 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
990 << " implicit copy constructors created\n";
992 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
994 << " implicit move constructors created\n";
995 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
997 << " implicit copy assignment operators created\n";
999 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1001 << " implicit move assignment operators created\n";
1002 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1004 << " implicit destructors created\n";
1005
1006 if (ExternalSource) {
1007 llvm::errs() << "\n";
1009 }
1010
1011 BumpAlloc.PrintStats();
1012}
1013
1015 bool NotifyListeners) {
1016 if (NotifyListeners)
1017 if (auto *Listener = getASTMutationListener())
1019
1020 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1021}
1022
1024 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1025 if (It == MergedDefModules.end())
1026 return;
1027
1028 auto &Merged = It->second;
1030 for (Module *&M : Merged)
1031 if (!Found.insert(M).second)
1032 M = nullptr;
1033 llvm::erase(Merged, nullptr);
1034}
1035
1038 auto MergedIt =
1039 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1040 if (MergedIt == MergedDefModules.end())
1041 return std::nullopt;
1042 return MergedIt->second;
1043}
1044
1045void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1046 if (LazyInitializers.empty())
1047 return;
1048
1049 auto *Source = Ctx.getExternalSource();
1050 assert(Source && "lazy initializers but no external source");
1051
1052 auto LazyInits = std::move(LazyInitializers);
1053 LazyInitializers.clear();
1054
1055 for (auto ID : LazyInits)
1056 Initializers.push_back(Source->GetExternalDecl(ID));
1057
1058 assert(LazyInitializers.empty() &&
1059 "GetExternalDecl for lazy module initializer added more inits");
1060}
1061
1063 // One special case: if we add a module initializer that imports another
1064 // module, and that module's only initializer is an ImportDecl, simplify.
1065 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1066 auto It = ModuleInitializers.find(ID->getImportedModule());
1067
1068 // Maybe the ImportDecl does nothing at all. (Common case.)
1069 if (It == ModuleInitializers.end())
1070 return;
1071
1072 // Maybe the ImportDecl only imports another ImportDecl.
1073 auto &Imported = *It->second;
1074 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1075 Imported.resolve(*this);
1076 auto *OnlyDecl = Imported.Initializers.front();
1077 if (isa<ImportDecl>(OnlyDecl))
1078 D = OnlyDecl;
1079 }
1080 }
1081
1082 auto *&Inits = ModuleInitializers[M];
1083 if (!Inits)
1084 Inits = new (*this) PerModuleInitializers;
1085 Inits->Initializers.push_back(D);
1086}
1087
1090 auto *&Inits = ModuleInitializers[M];
1091 if (!Inits)
1092 Inits = new (*this) PerModuleInitializers;
1093 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1094 IDs.begin(), IDs.end());
1095}
1096
1098 auto It = ModuleInitializers.find(M);
1099 if (It == ModuleInitializers.end())
1100 return std::nullopt;
1101
1102 auto *Inits = It->second;
1103 Inits->resolve(*this);
1104 return Inits->Initializers;
1105}
1106
1108 assert(M->isNamedModule());
1109 assert(!CurrentCXXNamedModule &&
1110 "We should set named module for ASTContext for only once");
1111 CurrentCXXNamedModule = M;
1112}
1113
1114bool ASTContext::isInSameModule(const Module *M1, const Module *M2) {
1115 if (!M1 != !M2)
1116 return false;
1117
1118 /// Get the representative module for M. The representative module is the
1119 /// first module unit for a specific primary module name. So that the module
1120 /// units have the same representative module belongs to the same module.
1121 ///
1122 /// The process is helpful to reduce the expensive string operations.
1123 auto GetRepresentativeModule = [this](const Module *M) {
1124 auto Iter = SameModuleLookupSet.find(M);
1125 if (Iter != SameModuleLookupSet.end())
1126 return Iter->second;
1127
1128 const Module *RepresentativeModule =
1129 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1130 .first->second;
1131 SameModuleLookupSet[M] = RepresentativeModule;
1132 return RepresentativeModule;
1133 };
1134
1135 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1136 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1137}
1138
1140 if (!ExternCContext)
1141 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1142
1143 return ExternCContext;
1144}
1145
1148 const IdentifierInfo *II) const {
1149 auto *BuiltinTemplate =
1151 BuiltinTemplate->setImplicit();
1152 getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1153
1154 return BuiltinTemplate;
1155}
1156
1159 if (!MakeIntegerSeqDecl)
1162 return MakeIntegerSeqDecl;
1163}
1164
1167 if (!TypePackElementDecl)
1170 return TypePackElementDecl;
1171}
1172
1174 RecordDecl::TagKind TK) const {
1176 RecordDecl *NewDecl;
1177 if (getLangOpts().CPlusPlus)
1178 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1179 Loc, &Idents.get(Name));
1180 else
1181 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1182 &Idents.get(Name));
1183 NewDecl->setImplicit();
1184 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1185 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1186 return NewDecl;
1187}
1188
1190 StringRef Name) const {
1193 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1194 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1195 NewDecl->setImplicit();
1196 return NewDecl;
1197}
1198
1200 if (!Int128Decl)
1201 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1202 return Int128Decl;
1203}
1204
1206 if (!UInt128Decl)
1207 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1208 return UInt128Decl;
1209}
1210
1211void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1212 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1214 Types.push_back(Ty);
1215}
1216
1218 const TargetInfo *AuxTarget) {
1219 assert((!this->Target || this->Target == &Target) &&
1220 "Incorrect target reinitialization");
1221 assert(VoidTy.isNull() && "Context reinitialized?");
1222
1223 this->Target = &Target;
1224 this->AuxTarget = AuxTarget;
1225
1226 ABI.reset(createCXXABI(Target));
1227 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1228
1229 // C99 6.2.5p19.
1230 InitBuiltinType(VoidTy, BuiltinType::Void);
1231
1232 // C99 6.2.5p2.
1233 InitBuiltinType(BoolTy, BuiltinType::Bool);
1234 // C99 6.2.5p3.
1235 if (LangOpts.CharIsSigned)
1236 InitBuiltinType(CharTy, BuiltinType::Char_S);
1237 else
1238 InitBuiltinType(CharTy, BuiltinType::Char_U);
1239 // C99 6.2.5p4.
1240 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1241 InitBuiltinType(ShortTy, BuiltinType::Short);
1242 InitBuiltinType(IntTy, BuiltinType::Int);
1243 InitBuiltinType(LongTy, BuiltinType::Long);
1244 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1245
1246 // C99 6.2.5p6.
1247 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1248 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1249 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1250 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1251 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1252
1253 // C99 6.2.5p10.
1254 InitBuiltinType(FloatTy, BuiltinType::Float);
1255 InitBuiltinType(DoubleTy, BuiltinType::Double);
1256 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1257
1258 // GNU extension, __float128 for IEEE quadruple precision
1259 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1260
1261 // __ibm128 for IBM extended precision
1262 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1263
1264 // C11 extension ISO/IEC TS 18661-3
1265 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1266
1267 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1268 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1269 InitBuiltinType(AccumTy, BuiltinType::Accum);
1270 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1271 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1272 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1273 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1274 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1275 InitBuiltinType(FractTy, BuiltinType::Fract);
1276 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1277 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1278 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1279 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1280 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1281 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1282 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1283 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1284 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1285 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1286 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1287 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1288 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1289 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1290 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1291 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1292
1293 // GNU extension, 128-bit integers.
1294 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1295 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1296
1297 // C++ 3.9.1p5
1298 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1299 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1300 else // -fshort-wchar makes wchar_t be unsigned.
1301 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1302 if (LangOpts.CPlusPlus && LangOpts.WChar)
1304 else {
1305 // C99 (or C++ using -fno-wchar).
1306 WideCharTy = getFromTargetType(Target.getWCharType());
1307 }
1308
1309 WIntTy = getFromTargetType(Target.getWIntType());
1310
1311 // C++20 (proposed)
1312 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1313
1314 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1315 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1316 else // C99
1317 Char16Ty = getFromTargetType(Target.getChar16Type());
1318
1319 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1320 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1321 else // C99
1322 Char32Ty = getFromTargetType(Target.getChar32Type());
1323
1324 // Placeholder type for type-dependent expressions whose type is
1325 // completely unknown. No code should ever check a type against
1326 // DependentTy and users should never see it; however, it is here to
1327 // help diagnose failures to properly check for type-dependent
1328 // expressions.
1329 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1330
1331 // Placeholder type for functions.
1332 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1333
1334 // Placeholder type for bound members.
1335 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1336
1337 // Placeholder type for unresolved templates.
1338 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1339
1340 // Placeholder type for pseudo-objects.
1341 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1342
1343 // "any" type; useful for debugger-like clients.
1344 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1345
1346 // Placeholder type for unbridged ARC casts.
1347 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1348
1349 // Placeholder type for builtin functions.
1350 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1351
1352 // Placeholder type for OMP array sections.
1353 if (LangOpts.OpenMP) {
1354 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1355 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1356 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1357 }
1358 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1359 // don't bother, as we're just using the same type as OMP.
1360 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1361 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1362 }
1363 if (LangOpts.MatrixTypes)
1364 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1365
1366 // Builtin types for 'id', 'Class', and 'SEL'.
1367 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1368 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1369 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1370
1371 if (LangOpts.OpenCL) {
1372#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1373 InitBuiltinType(SingletonId, BuiltinType::Id);
1374#include "clang/Basic/OpenCLImageTypes.def"
1375
1376 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1377 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1378 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1379 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1380 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1381
1382#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1383 InitBuiltinType(Id##Ty, BuiltinType::Id);
1384#include "clang/Basic/OpenCLExtensionTypes.def"
1385 }
1386
1387 if (Target.hasAArch64SVETypes() ||
1388 (AuxTarget && AuxTarget->hasAArch64SVETypes())) {
1389#define SVE_TYPE(Name, Id, SingletonId) \
1390 InitBuiltinType(SingletonId, BuiltinType::Id);
1391#include "clang/Basic/AArch64SVEACLETypes.def"
1392 }
1393
1394 if (Target.getTriple().isPPC64()) {
1395#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1396 InitBuiltinType(Id##Ty, BuiltinType::Id);
1397#include "clang/Basic/PPCTypes.def"
1398#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1399 InitBuiltinType(Id##Ty, BuiltinType::Id);
1400#include "clang/Basic/PPCTypes.def"
1401 }
1402
1403 if (Target.hasRISCVVTypes()) {
1404#define RVV_TYPE(Name, Id, SingletonId) \
1405 InitBuiltinType(SingletonId, BuiltinType::Id);
1406#include "clang/Basic/RISCVVTypes.def"
1407 }
1408
1409 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1410#define WASM_TYPE(Name, Id, SingletonId) \
1411 InitBuiltinType(SingletonId, BuiltinType::Id);
1412#include "clang/Basic/WebAssemblyReferenceTypes.def"
1413 }
1414
1415 if (Target.getTriple().isAMDGPU() ||
1416 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) {
1417#define AMDGPU_TYPE(Name, Id, SingletonId) \
1418 InitBuiltinType(SingletonId, BuiltinType::Id);
1419#include "clang/Basic/AMDGPUTypes.def"
1420 }
1421
1422 // Builtin type for __objc_yes and __objc_no
1423 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1425
1426 ObjCConstantStringType = QualType();
1427
1428 ObjCSuperType = QualType();
1429
1430 // void * type
1431 if (LangOpts.OpenCLGenericAddressSpace) {
1432 auto Q = VoidTy.getQualifiers();
1436 } else {
1438 }
1439
1440 // nullptr type (C++0x 2.14.7)
1441 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1442
1443 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1444 InitBuiltinType(HalfTy, BuiltinType::Half);
1445
1446 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1447
1448 // Builtin type used to help define __builtin_va_list.
1449 VaListTagDecl = nullptr;
1450
1451 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1452 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1455 }
1456}
1457
1459 return SourceMgr.getDiagnostics();
1460}
1461
1463 AttrVec *&Result = DeclAttrs[D];
1464 if (!Result) {
1465 void *Mem = Allocate(sizeof(AttrVec));
1466 Result = new (Mem) AttrVec;
1467 }
1468
1469 return *Result;
1470}
1471
1472/// Erase the attributes corresponding to the given declaration.
1474 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1475 if (Pos != DeclAttrs.end()) {
1476 Pos->second->~AttrVec();
1477 DeclAttrs.erase(Pos);
1478 }
1479}
1480
1481// FIXME: Remove ?
1484 assert(Var->isStaticDataMember() && "Not a static data member");
1486 .dyn_cast<MemberSpecializationInfo *>();
1487}
1488
1491 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1492 TemplateOrInstantiation.find(Var);
1493 if (Pos == TemplateOrInstantiation.end())
1494 return {};
1495
1496 return Pos->second;
1497}
1498
1499void
1502 SourceLocation PointOfInstantiation) {
1503 assert(Inst->isStaticDataMember() && "Not a static data member");
1504 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1506 Tmpl, TSK, PointOfInstantiation));
1507}
1508
1509void
1512 assert(!TemplateOrInstantiation[Inst] &&
1513 "Already noted what the variable was instantiated from");
1514 TemplateOrInstantiation[Inst] = TSI;
1515}
1516
1517NamedDecl *
1519 return InstantiatedFromUsingDecl.lookup(UUD);
1520}
1521
1522void
1524 assert((isa<UsingDecl>(Pattern) ||
1525 isa<UnresolvedUsingValueDecl>(Pattern) ||
1526 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1527 "pattern decl is not a using decl");
1528 assert((isa<UsingDecl>(Inst) ||
1529 isa<UnresolvedUsingValueDecl>(Inst) ||
1530 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1531 "instantiation did not produce a using decl");
1532 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1533 InstantiatedFromUsingDecl[Inst] = Pattern;
1534}
1535
1538 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1539}
1540
1542 UsingEnumDecl *Pattern) {
1543 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1544 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1545}
1546
1549 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1550}
1551
1552void
1554 UsingShadowDecl *Pattern) {
1555 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1556 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1557}
1558
1560 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1561}
1562
1564 FieldDecl *Tmpl) {
1565 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1566 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1567 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1568 "Already noted what unnamed field was instantiated from");
1569
1570 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1571}
1572
1575 return overridden_methods(Method).begin();
1576}
1577
1580 return overridden_methods(Method).end();
1581}
1582
1583unsigned
1585 auto Range = overridden_methods(Method);
1586 return Range.end() - Range.begin();
1587}
1588
1591 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1592 OverriddenMethods.find(Method->getCanonicalDecl());
1593 if (Pos == OverriddenMethods.end())
1594 return overridden_method_range(nullptr, nullptr);
1595 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1596}
1597
1599 const CXXMethodDecl *Overridden) {
1600 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1601 OverriddenMethods[Method].push_back(Overridden);
1602}
1603
1605 const NamedDecl *D,
1606 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1607 assert(D);
1608
1609 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1610 Overridden.append(overridden_methods_begin(CXXMethod),
1611 overridden_methods_end(CXXMethod));
1612 return;
1613 }
1614
1615 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1616 if (!Method)
1617 return;
1618
1620 Method->getOverriddenMethods(OverDecls);
1621 Overridden.append(OverDecls.begin(), OverDecls.end());
1622}
1623
1625 assert(!Import->getNextLocalImport() &&
1626 "Import declaration already in the chain");
1627 assert(!Import->isFromASTFile() && "Non-local import declaration");
1628 if (!FirstLocalImport) {
1629 FirstLocalImport = Import;
1630 LastLocalImport = Import;
1631 return;
1632 }
1633
1634 LastLocalImport->setNextLocalImport(Import);
1635 LastLocalImport = Import;
1636}
1637
1638//===----------------------------------------------------------------------===//
1639// Type Sizing and Analysis
1640//===----------------------------------------------------------------------===//
1641
1642/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1643/// scalar floating point type.
1644const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1645 switch (T->castAs<BuiltinType>()->getKind()) {
1646 default:
1647 llvm_unreachable("Not a floating point type!");
1648 case BuiltinType::BFloat16:
1649 return Target->getBFloat16Format();
1650 case BuiltinType::Float16:
1651 return Target->getHalfFormat();
1652 case BuiltinType::Half:
1653 return Target->getHalfFormat();
1654 case BuiltinType::Float: return Target->getFloatFormat();
1655 case BuiltinType::Double: return Target->getDoubleFormat();
1656 case BuiltinType::Ibm128:
1657 return Target->getIbm128Format();
1658 case BuiltinType::LongDouble:
1659 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1660 return AuxTarget->getLongDoubleFormat();
1661 return Target->getLongDoubleFormat();
1662 case BuiltinType::Float128:
1663 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1664 return AuxTarget->getFloat128Format();
1665 return Target->getFloat128Format();
1666 }
1667}
1668
1669CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1670 unsigned Align = Target->getCharWidth();
1671
1672 const unsigned AlignFromAttr = D->getMaxAlignment();
1673 if (AlignFromAttr)
1674 Align = AlignFromAttr;
1675
1676 // __attribute__((aligned)) can increase or decrease alignment
1677 // *except* on a struct or struct member, where it only increases
1678 // alignment unless 'packed' is also specified.
1679 //
1680 // It is an error for alignas to decrease alignment, so we can
1681 // ignore that possibility; Sema should diagnose it.
1682 bool UseAlignAttrOnly;
1683 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1684 UseAlignAttrOnly =
1685 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1686 else
1687 UseAlignAttrOnly = AlignFromAttr != 0;
1688 // If we're using the align attribute only, just ignore everything
1689 // else about the declaration and its type.
1690 if (UseAlignAttrOnly) {
1691 // do nothing
1692 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1693 QualType T = VD->getType();
1694 if (const auto *RT = T->getAs<ReferenceType>()) {
1695 if (ForAlignof)
1696 T = RT->getPointeeType();
1697 else
1698 T = getPointerType(RT->getPointeeType());
1699 }
1700 QualType BaseT = getBaseElementType(T);
1701 if (T->isFunctionType())
1702 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1703 else if (!BaseT->isIncompleteType()) {
1704 // Adjust alignments of declarations with array type by the
1705 // large-array alignment on the target.
1706 if (const ArrayType *arrayType = getAsArrayType(T)) {
1707 unsigned MinWidth = Target->getLargeArrayMinWidth();
1708 if (!ForAlignof && MinWidth) {
1709 if (isa<VariableArrayType>(arrayType))
1710 Align = std::max(Align, Target->getLargeArrayAlign());
1711 else if (isa<ConstantArrayType>(arrayType) &&
1712 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1713 Align = std::max(Align, Target->getLargeArrayAlign());
1714 }
1715 }
1716 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1717 if (BaseT.getQualifiers().hasUnaligned())
1718 Align = Target->getCharWidth();
1719 }
1720
1721 // Ensure miminum alignment for global variables.
1722 if (const auto *VD = dyn_cast<VarDecl>(D))
1723 if (VD->hasGlobalStorage() && !ForAlignof) {
1724 uint64_t TypeSize =
1725 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1726 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1727 }
1728
1729 // Fields can be subject to extra alignment constraints, like if
1730 // the field is packed, the struct is packed, or the struct has a
1731 // a max-field-alignment constraint (#pragma pack). So calculate
1732 // the actual alignment of the field within the struct, and then
1733 // (as we're expected to) constrain that by the alignment of the type.
1734 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1735 const RecordDecl *Parent = Field->getParent();
1736 // We can only produce a sensible answer if the record is valid.
1737 if (!Parent->isInvalidDecl()) {
1738 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1739
1740 // Start with the record's overall alignment.
1741 unsigned FieldAlign = toBits(Layout.getAlignment());
1742
1743 // Use the GCD of that and the offset within the record.
1744 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1745 if (Offset > 0) {
1746 // Alignment is always a power of 2, so the GCD will be a power of 2,
1747 // which means we get to do this crazy thing instead of Euclid's.
1748 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1749 if (LowBitOfOffset < FieldAlign)
1750 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1751 }
1752
1753 Align = std::min(Align, FieldAlign);
1754 }
1755 }
1756 }
1757
1758 // Some targets have hard limitation on the maximum requestable alignment in
1759 // aligned attribute for static variables.
1760 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1761 const auto *VD = dyn_cast<VarDecl>(D);
1762 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1763 Align = std::min(Align, MaxAlignedAttr);
1764
1765 return toCharUnitsFromBits(Align);
1766}
1767
1769 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1770}
1771
1772// getTypeInfoDataSizeInChars - Return the size of a type, in
1773// chars. If the type is a record, its data size is returned. This is
1774// the size of the memcpy that's performed when assigning this type
1775// using a trivial copy/move assignment operator.
1778
1779 // In C++, objects can sometimes be allocated into the tail padding
1780 // of a base-class subobject. We decide whether that's possible
1781 // during class layout, so here we can just trust the layout results.
1782 if (getLangOpts().CPlusPlus) {
1783 if (const auto *RT = T->getAs<RecordType>();
1784 RT && !RT->getDecl()->isInvalidDecl()) {
1785 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1786 Info.Width = layout.getDataSize();
1787 }
1788 }
1789
1790 return Info;
1791}
1792
1793/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1794/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1797 const ConstantArrayType *CAT) {
1798 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1799 uint64_t Size = CAT->getZExtSize();
1800 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1801 (uint64_t)(-1)/Size) &&
1802 "Overflow in array type char size evaluation");
1803 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1804 unsigned Align = EltInfo.Align.getQuantity();
1805 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1807 Width = llvm::alignTo(Width, Align);
1810 EltInfo.AlignRequirement);
1811}
1812
1814 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1815 return getConstantArrayInfoInChars(*this, CAT);
1816 TypeInfo Info = getTypeInfo(T);
1819}
1820
1822 return getTypeInfoInChars(T.getTypePtr());
1823}
1824
1826 // HLSL doesn't promote all small integer types to int, it
1827 // just uses the rank-based promotion rules for all types.
1828 if (getLangOpts().HLSL)
1829 return false;
1830
1831 if (const auto *BT = T->getAs<BuiltinType>())
1832 switch (BT->getKind()) {
1833 case BuiltinType::Bool:
1834 case BuiltinType::Char_S:
1835 case BuiltinType::Char_U:
1836 case BuiltinType::SChar:
1837 case BuiltinType::UChar:
1838 case BuiltinType::Short:
1839 case BuiltinType::UShort:
1840 case BuiltinType::WChar_S:
1841 case BuiltinType::WChar_U:
1842 case BuiltinType::Char8:
1843 case BuiltinType::Char16:
1844 case BuiltinType::Char32:
1845 return true;
1846 default:
1847 return false;
1848 }
1849
1850 // Enumerated types are promotable to their compatible integer types
1851 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1852 if (const auto *ET = T->getAs<EnumType>()) {
1853 if (T->isDependentType() || ET->getDecl()->getPromotionType().isNull() ||
1854 ET->getDecl()->isScoped())
1855 return false;
1856
1857 return true;
1858 }
1859
1860 return false;
1861}
1862
1865}
1866
1868 return isAlignmentRequired(T.getTypePtr());
1869}
1870
1872 bool NeedsPreferredAlignment) const {
1873 // An alignment on a typedef overrides anything else.
1874 if (const auto *TT = T->getAs<TypedefType>())
1875 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1876 return Align;
1877
1878 // If we have an (array of) complete type, we're done.
1880 if (!T->isIncompleteType())
1881 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1882
1883 // If we had an array type, its element type might be a typedef
1884 // type with an alignment attribute.
1885 if (const auto *TT = T->getAs<TypedefType>())
1886 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1887 return Align;
1888
1889 // Otherwise, see if the declaration of the type had an attribute.
1890 if (const auto *TT = T->getAs<TagType>())
1891 return TT->getDecl()->getMaxAlignment();
1892
1893 return 0;
1894}
1895
1897 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1898 if (I != MemoizedTypeInfo.end())
1899 return I->second;
1900
1901 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1902 TypeInfo TI = getTypeInfoImpl(T);
1903 MemoizedTypeInfo[T] = TI;
1904 return TI;
1905}
1906
1907/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1908/// method does not work on incomplete types.
1909///
1910/// FIXME: Pointers into different addr spaces could have different sizes and
1911/// alignment requirements: getPointerInfo should take an AddrSpace, this
1912/// should take a QualType, &c.
1913TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1914 uint64_t Width = 0;
1915 unsigned Align = 8;
1918 switch (T->getTypeClass()) {
1919#define TYPE(Class, Base)
1920#define ABSTRACT_TYPE(Class, Base)
1921#define NON_CANONICAL_TYPE(Class, Base)
1922#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1923#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1924 case Type::Class: \
1925 assert(!T->isDependentType() && "should not see dependent types here"); \
1926 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1927#include "clang/AST/TypeNodes.inc"
1928 llvm_unreachable("Should not see dependent types");
1929
1930 case Type::FunctionNoProto:
1931 case Type::FunctionProto:
1932 // GCC extension: alignof(function) = 32 bits
1933 Width = 0;
1934 Align = 32;
1935 break;
1936
1937 case Type::IncompleteArray:
1938 case Type::VariableArray:
1939 case Type::ConstantArray:
1940 case Type::ArrayParameter: {
1941 // Model non-constant sized arrays as size zero, but track the alignment.
1942 uint64_t Size = 0;
1943 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1944 Size = CAT->getZExtSize();
1945
1946 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1947 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1948 "Overflow in array type bit size evaluation");
1949 Width = EltInfo.Width * Size;
1950 Align = EltInfo.Align;
1951 AlignRequirement = EltInfo.AlignRequirement;
1952 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1953 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1954 Width = llvm::alignTo(Width, Align);
1955 break;
1956 }
1957
1958 case Type::ExtVector:
1959 case Type::Vector: {
1960 const auto *VT = cast<VectorType>(T);
1961 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1962 Width = VT->isExtVectorBoolType() ? VT->getNumElements()
1963 : EltInfo.Width * VT->getNumElements();
1964 // Enforce at least byte size and alignment.
1965 Width = std::max<unsigned>(8, Width);
1966 Align = std::max<unsigned>(8, Width);
1967
1968 // If the alignment is not a power of 2, round up to the next power of 2.
1969 // This happens for non-power-of-2 length vectors.
1970 if (Align & (Align-1)) {
1971 Align = llvm::bit_ceil(Align);
1972 Width = llvm::alignTo(Width, Align);
1973 }
1974 // Adjust the alignment based on the target max.
1975 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1976 if (TargetVectorAlign && TargetVectorAlign < Align)
1977 Align = TargetVectorAlign;
1978 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
1979 // Adjust the alignment for fixed-length SVE vectors. This is important
1980 // for non-power-of-2 vector lengths.
1981 Align = 128;
1982 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
1983 // Adjust the alignment for fixed-length SVE predicates.
1984 Align = 16;
1985 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
1986 VT->getVectorKind() == VectorKind::RVVFixedLengthMask)
1987 // Adjust the alignment for fixed-length RVV vectors.
1988 Align = std::min<unsigned>(64, Width);
1989 break;
1990 }
1991
1992 case Type::ConstantMatrix: {
1993 const auto *MT = cast<ConstantMatrixType>(T);
1994 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1995 // The internal layout of a matrix value is implementation defined.
1996 // Initially be ABI compatible with arrays with respect to alignment and
1997 // size.
1998 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1999 Align = ElementInfo.Align;
2000 break;
2001 }
2002
2003 case Type::Builtin:
2004 switch (cast<BuiltinType>(T)->getKind()) {
2005 default: llvm_unreachable("Unknown builtin type!");
2006 case BuiltinType::Void:
2007 // GCC extension: alignof(void) = 8 bits.
2008 Width = 0;
2009 Align = 8;
2010 break;
2011 case BuiltinType::Bool:
2012 Width = Target->getBoolWidth();
2013 Align = Target->getBoolAlign();
2014 break;
2015 case BuiltinType::Char_S:
2016 case BuiltinType::Char_U:
2017 case BuiltinType::UChar:
2018 case BuiltinType::SChar:
2019 case BuiltinType::Char8:
2020 Width = Target->getCharWidth();
2021 Align = Target->getCharAlign();
2022 break;
2023 case BuiltinType::WChar_S:
2024 case BuiltinType::WChar_U:
2025 Width = Target->getWCharWidth();
2026 Align = Target->getWCharAlign();
2027 break;
2028 case BuiltinType::Char16:
2029 Width = Target->getChar16Width();
2030 Align = Target->getChar16Align();
2031 break;
2032 case BuiltinType::Char32:
2033 Width = Target->getChar32Width();
2034 Align = Target->getChar32Align();
2035 break;
2036 case BuiltinType::UShort:
2037 case BuiltinType::Short:
2038 Width = Target->getShortWidth();
2039 Align = Target->getShortAlign();
2040 break;
2041 case BuiltinType::UInt:
2042 case BuiltinType::Int:
2043 Width = Target->getIntWidth();
2044 Align = Target->getIntAlign();
2045 break;
2046 case BuiltinType::ULong:
2047 case BuiltinType::Long:
2048 Width = Target->getLongWidth();
2049 Align = Target->getLongAlign();
2050 break;
2051 case BuiltinType::ULongLong:
2052 case BuiltinType::LongLong:
2053 Width = Target->getLongLongWidth();
2054 Align = Target->getLongLongAlign();
2055 break;
2056 case BuiltinType::Int128:
2057 case BuiltinType::UInt128:
2058 Width = 128;
2059 Align = Target->getInt128Align();
2060 break;
2061 case BuiltinType::ShortAccum:
2062 case BuiltinType::UShortAccum:
2063 case BuiltinType::SatShortAccum:
2064 case BuiltinType::SatUShortAccum:
2065 Width = Target->getShortAccumWidth();
2066 Align = Target->getShortAccumAlign();
2067 break;
2068 case BuiltinType::Accum:
2069 case BuiltinType::UAccum:
2070 case BuiltinType::SatAccum:
2071 case BuiltinType::SatUAccum:
2072 Width = Target->getAccumWidth();
2073 Align = Target->getAccumAlign();
2074 break;
2075 case BuiltinType::LongAccum:
2076 case BuiltinType::ULongAccum:
2077 case BuiltinType::SatLongAccum:
2078 case BuiltinType::SatULongAccum:
2079 Width = Target->getLongAccumWidth();
2080 Align = Target->getLongAccumAlign();
2081 break;
2082 case BuiltinType::ShortFract:
2083 case BuiltinType::UShortFract:
2084 case BuiltinType::SatShortFract:
2085 case BuiltinType::SatUShortFract:
2086 Width = Target->getShortFractWidth();
2087 Align = Target->getShortFractAlign();
2088 break;
2089 case BuiltinType::Fract:
2090 case BuiltinType::UFract:
2091 case BuiltinType::SatFract:
2092 case BuiltinType::SatUFract:
2093 Width = Target->getFractWidth();
2094 Align = Target->getFractAlign();
2095 break;
2096 case BuiltinType::LongFract:
2097 case BuiltinType::ULongFract:
2098 case BuiltinType::SatLongFract:
2099 case BuiltinType::SatULongFract:
2100 Width = Target->getLongFractWidth();
2101 Align = Target->getLongFractAlign();
2102 break;
2103 case BuiltinType::BFloat16:
2104 if (Target->hasBFloat16Type()) {
2105 Width = Target->getBFloat16Width();
2106 Align = Target->getBFloat16Align();
2107 } else if ((getLangOpts().SYCLIsDevice ||
2108 (getLangOpts().OpenMP &&
2109 getLangOpts().OpenMPIsTargetDevice)) &&
2110 AuxTarget->hasBFloat16Type()) {
2111 Width = AuxTarget->getBFloat16Width();
2112 Align = AuxTarget->getBFloat16Align();
2113 }
2114 break;
2115 case BuiltinType::Float16:
2116 case BuiltinType::Half:
2117 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2118 !getLangOpts().OpenMPIsTargetDevice) {
2119 Width = Target->getHalfWidth();
2120 Align = Target->getHalfAlign();
2121 } else {
2122 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2123 "Expected OpenMP device compilation.");
2124 Width = AuxTarget->getHalfWidth();
2125 Align = AuxTarget->getHalfAlign();
2126 }
2127 break;
2128 case BuiltinType::Float:
2129 Width = Target->getFloatWidth();
2130 Align = Target->getFloatAlign();
2131 break;
2132 case BuiltinType::Double:
2133 Width = Target->getDoubleWidth();
2134 Align = Target->getDoubleAlign();
2135 break;
2136 case BuiltinType::Ibm128:
2137 Width = Target->getIbm128Width();
2138 Align = Target->getIbm128Align();
2139 break;
2140 case BuiltinType::LongDouble:
2141 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2142 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2143 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2144 Width = AuxTarget->getLongDoubleWidth();
2145 Align = AuxTarget->getLongDoubleAlign();
2146 } else {
2147 Width = Target->getLongDoubleWidth();
2148 Align = Target->getLongDoubleAlign();
2149 }
2150 break;
2151 case BuiltinType::Float128:
2152 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2153 !getLangOpts().OpenMPIsTargetDevice) {
2154 Width = Target->getFloat128Width();
2155 Align = Target->getFloat128Align();
2156 } else {
2157 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2158 "Expected OpenMP device compilation.");
2159 Width = AuxTarget->getFloat128Width();
2160 Align = AuxTarget->getFloat128Align();
2161 }
2162 break;
2163 case BuiltinType::NullPtr:
2164 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2165 Width = Target->getPointerWidth(LangAS::Default);
2166 Align = Target->getPointerAlign(LangAS::Default);
2167 break;
2168 case BuiltinType::ObjCId:
2169 case BuiltinType::ObjCClass:
2170 case BuiltinType::ObjCSel:
2171 Width = Target->getPointerWidth(LangAS::Default);
2172 Align = Target->getPointerAlign(LangAS::Default);
2173 break;
2174 case BuiltinType::OCLSampler:
2175 case BuiltinType::OCLEvent:
2176 case BuiltinType::OCLClkEvent:
2177 case BuiltinType::OCLQueue:
2178 case BuiltinType::OCLReserveID:
2179#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2180 case BuiltinType::Id:
2181#include "clang/Basic/OpenCLImageTypes.def"
2182#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2183 case BuiltinType::Id:
2184#include "clang/Basic/OpenCLExtensionTypes.def"
2185 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2186 Width = Target->getPointerWidth(AS);
2187 Align = Target->getPointerAlign(AS);
2188 break;
2189 // The SVE types are effectively target-specific. The length of an
2190 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2191 // of 128 bits. There is one predicate bit for each vector byte, so the
2192 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2193 //
2194 // Because the length is only known at runtime, we use a dummy value
2195 // of 0 for the static length. The alignment values are those defined
2196 // by the Procedure Call Standard for the Arm Architecture.
2197#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
2198 IsSigned, IsFP, IsBF) \
2199 case BuiltinType::Id: \
2200 Width = 0; \
2201 Align = 128; \
2202 break;
2203#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
2204 case BuiltinType::Id: \
2205 Width = 0; \
2206 Align = 16; \
2207 break;
2208#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2209 case BuiltinType::Id: \
2210 Width = 0; \
2211 Align = 16; \
2212 break;
2213#include "clang/Basic/AArch64SVEACLETypes.def"
2214#define PPC_VECTOR_TYPE(Name, Id, Size) \
2215 case BuiltinType::Id: \
2216 Width = Size; \
2217 Align = Size; \
2218 break;
2219#include "clang/Basic/PPCTypes.def"
2220#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2221 IsFP, IsBF) \
2222 case BuiltinType::Id: \
2223 Width = 0; \
2224 Align = ElBits; \
2225 break;
2226#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2227 case BuiltinType::Id: \
2228 Width = 0; \
2229 Align = 8; \
2230 break;
2231#include "clang/Basic/RISCVVTypes.def"
2232#define WASM_TYPE(Name, Id, SingletonId) \
2233 case BuiltinType::Id: \
2234 Width = 0; \
2235 Align = 8; \
2236 break;
2237#include "clang/Basic/WebAssemblyReferenceTypes.def"
2238#define AMDGPU_OPAQUE_PTR_TYPE(NAME, MANGLEDNAME, AS, WIDTH, ALIGN, ID, \
2239 SINGLETONID) \
2240 case BuiltinType::ID: \
2241 Width = WIDTH; \
2242 Align = ALIGN; \
2243 break;
2244#include "clang/Basic/AMDGPUTypes.def"
2245 }
2246 break;
2247 case Type::ObjCObjectPointer:
2248 Width = Target->getPointerWidth(LangAS::Default);
2249 Align = Target->getPointerAlign(LangAS::Default);
2250 break;
2251 case Type::BlockPointer:
2252 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2253 Width = Target->getPointerWidth(AS);
2254 Align = Target->getPointerAlign(AS);
2255 break;
2256 case Type::LValueReference:
2257 case Type::RValueReference:
2258 // alignof and sizeof should never enter this code path here, so we go
2259 // the pointer route.
2260 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2261 Width = Target->getPointerWidth(AS);
2262 Align = Target->getPointerAlign(AS);
2263 break;
2264 case Type::Pointer:
2265 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2266 Width = Target->getPointerWidth(AS);
2267 Align = Target->getPointerAlign(AS);
2268 break;
2269 case Type::MemberPointer: {
2270 const auto *MPT = cast<MemberPointerType>(T);
2271 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2272 Width = MPI.Width;
2273 Align = MPI.Align;
2274 break;
2275 }
2276 case Type::Complex: {
2277 // Complex types have the same alignment as their elements, but twice the
2278 // size.
2279 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2280 Width = EltInfo.Width * 2;
2281 Align = EltInfo.Align;
2282 break;
2283 }
2284 case Type::ObjCObject:
2285 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2286 case Type::Adjusted:
2287 case Type::Decayed:
2288 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2289 case Type::ObjCInterface: {
2290 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2291 if (ObjCI->getDecl()->isInvalidDecl()) {
2292 Width = 8;
2293 Align = 8;
2294 break;
2295 }
2296 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2297 Width = toBits(Layout.getSize());
2298 Align = toBits(Layout.getAlignment());
2299 break;
2300 }
2301 case Type::BitInt: {
2302 const auto *EIT = cast<BitIntType>(T);
2303 Align = Target->getBitIntAlign(EIT->getNumBits());
2304 Width = Target->getBitIntWidth(EIT->getNumBits());
2305 break;
2306 }
2307 case Type::Record:
2308 case Type::Enum: {
2309 const auto *TT = cast<TagType>(T);
2310
2311 if (TT->getDecl()->isInvalidDecl()) {
2312 Width = 8;
2313 Align = 8;
2314 break;
2315 }
2316
2317 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2318 const EnumDecl *ED = ET->getDecl();
2319 TypeInfo Info =
2321 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2322 Info.Align = AttrAlign;
2324 }
2325 return Info;
2326 }
2327
2328 const auto *RT = cast<RecordType>(TT);
2329 const RecordDecl *RD = RT->getDecl();
2330 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2331 Width = toBits(Layout.getSize());
2332 Align = toBits(Layout.getAlignment());
2333 AlignRequirement = RD->hasAttr<AlignedAttr>()
2336 break;
2337 }
2338
2339 case Type::SubstTemplateTypeParm:
2340 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2341 getReplacementType().getTypePtr());
2342
2343 case Type::Auto:
2344 case Type::DeducedTemplateSpecialization: {
2345 const auto *A = cast<DeducedType>(T);
2346 assert(!A->getDeducedType().isNull() &&
2347 "cannot request the size of an undeduced or dependent auto type");
2348 return getTypeInfo(A->getDeducedType().getTypePtr());
2349 }
2350
2351 case Type::Paren:
2352 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2353
2354 case Type::MacroQualified:
2355 return getTypeInfo(
2356 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2357
2358 case Type::ObjCTypeParam:
2359 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2360
2361 case Type::Using:
2362 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2363
2364 case Type::Typedef: {
2365 const auto *TT = cast<TypedefType>(T);
2366 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2367 // If the typedef has an aligned attribute on it, it overrides any computed
2368 // alignment we have. This violates the GCC documentation (which says that
2369 // attribute(aligned) can only round up) but matches its implementation.
2370 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2371 Align = AttrAlign;
2372 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2373 } else {
2374 Align = Info.Align;
2375 AlignRequirement = Info.AlignRequirement;
2376 }
2377 Width = Info.Width;
2378 break;
2379 }
2380
2381 case Type::Elaborated:
2382 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2383
2384 case Type::Attributed:
2385 return getTypeInfo(
2386 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2387
2388 case Type::CountAttributed:
2389 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2390
2391 case Type::BTFTagAttributed:
2392 return getTypeInfo(
2393 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2394
2395 case Type::Atomic: {
2396 // Start with the base type information.
2397 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2398 Width = Info.Width;
2399 Align = Info.Align;
2400
2401 if (!Width) {
2402 // An otherwise zero-sized type should still generate an
2403 // atomic operation.
2404 Width = Target->getCharWidth();
2405 assert(Align);
2406 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2407 // If the size of the type doesn't exceed the platform's max
2408 // atomic promotion width, make the size and alignment more
2409 // favorable to atomic operations:
2410
2411 // Round the size up to a power of 2.
2412 Width = llvm::bit_ceil(Width);
2413
2414 // Set the alignment equal to the size.
2415 Align = static_cast<unsigned>(Width);
2416 }
2417 }
2418 break;
2419
2420 case Type::Pipe:
2421 Width = Target->getPointerWidth(LangAS::opencl_global);
2422 Align = Target->getPointerAlign(LangAS::opencl_global);
2423 break;
2424 }
2425
2426 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2427 return TypeInfo(Width, Align, AlignRequirement);
2428}
2429
2431 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2432 if (I != MemoizedUnadjustedAlign.end())
2433 return I->second;
2434
2435 unsigned UnadjustedAlign;
2436 if (const auto *RT = T->getAs<RecordType>()) {
2437 const RecordDecl *RD = RT->getDecl();
2438 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2439 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2440 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2441 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2442 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2443 } else {
2444 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2445 }
2446
2447 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2448 return UnadjustedAlign;
2449}
2450
2452 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2453 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2454 return SimdAlign;
2455}
2456
2457/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2459 return CharUnits::fromQuantity(BitSize / getCharWidth());
2460}
2461
2462/// toBits - Convert a size in characters to a size in characters.
2463int64_t ASTContext::toBits(CharUnits CharSize) const {
2464 return CharSize.getQuantity() * getCharWidth();
2465}
2466
2467/// getTypeSizeInChars - Return the size of the specified type, in characters.
2468/// This method does not work on incomplete types.
2470 return getTypeInfoInChars(T).Width;
2471}
2473 return getTypeInfoInChars(T).Width;
2474}
2475
2476/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2477/// characters. This method does not work on incomplete types.
2480}
2483}
2484
2485/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2486/// type, in characters, before alignment adjustments. This method does
2487/// not work on incomplete types.
2490}
2493}
2494
2495/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2496/// type for the current target in bits. This can be different than the ABI
2497/// alignment in cases where it is beneficial for performance or backwards
2498/// compatibility preserving to overalign a data type. (Note: despite the name,
2499/// the preferred alignment is ABI-impacting, and not an optimization.)
2501 TypeInfo TI = getTypeInfo(T);
2502 unsigned ABIAlign = TI.Align;
2503
2505
2506 // The preferred alignment of member pointers is that of a pointer.
2507 if (T->isMemberPointerType())
2508 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2509
2510 if (!Target->allowsLargerPreferedTypeAlignment())
2511 return ABIAlign;
2512
2513 if (const auto *RT = T->getAs<RecordType>()) {
2514 const RecordDecl *RD = RT->getDecl();
2515
2516 // When used as part of a typedef, or together with a 'packed' attribute,
2517 // the 'aligned' attribute can be used to decrease alignment. Note that the
2518 // 'packed' case is already taken into consideration when computing the
2519 // alignment, we only need to handle the typedef case here.
2521 RD->isInvalidDecl())
2522 return ABIAlign;
2523
2524 unsigned PreferredAlign = static_cast<unsigned>(
2525 toBits(getASTRecordLayout(RD).PreferredAlignment));
2526 assert(PreferredAlign >= ABIAlign &&
2527 "PreferredAlign should be at least as large as ABIAlign.");
2528 return PreferredAlign;
2529 }
2530
2531 // Double (and, for targets supporting AIX `power` alignment, long double) and
2532 // long long should be naturally aligned (despite requiring less alignment) if
2533 // possible.
2534 if (const auto *CT = T->getAs<ComplexType>())
2535 T = CT->getElementType().getTypePtr();
2536 if (const auto *ET = T->getAs<EnumType>())
2537 T = ET->getDecl()->getIntegerType().getTypePtr();
2538 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2539 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2540 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2541 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2542 Target->defaultsToAIXPowerAlignment()))
2543 // Don't increase the alignment if an alignment attribute was specified on a
2544 // typedef declaration.
2545 if (!TI.isAlignRequired())
2546 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2547
2548 return ABIAlign;
2549}
2550
2551/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2552/// for __attribute__((aligned)) on this target, to be used if no alignment
2553/// value is specified.
2556}
2557
2558/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2559/// to a global variable of the specified type.
2561 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2562 return std::max(getPreferredTypeAlign(T),
2563 getMinGlobalAlignOfVar(TypeSize, VD));
2564}
2565
2566/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2567/// should be given to a global variable of the specified type.
2569 const VarDecl *VD) const {
2571}
2572
2574 const VarDecl *VD) const {
2575 // Make the default handling as that of a non-weak definition in the
2576 // current translation unit.
2577 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2578 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2579}
2580
2582 CharUnits Offset = CharUnits::Zero();
2583 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2584 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2585 Offset += Layout->getBaseClassOffset(Base);
2586 Layout = &getASTRecordLayout(Base);
2587 }
2588 return Offset;
2589}
2590
2592 const ValueDecl *MPD = MP.getMemberPointerDecl();
2595 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2596 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2597 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2598 const CXXRecordDecl *Base = RD;
2599 const CXXRecordDecl *Derived = Path[I];
2600 if (DerivedMember)
2601 std::swap(Base, Derived);
2603 RD = Path[I];
2604 }
2605 if (DerivedMember)
2607 return ThisAdjustment;
2608}
2609
2610/// DeepCollectObjCIvars -
2611/// This routine first collects all declared, but not synthesized, ivars in
2612/// super class and then collects all ivars, including those synthesized for
2613/// current class. This routine is used for implementation of current class
2614/// when all ivars, declared and synthesized are known.
2616 bool leafClass,
2618 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2619 DeepCollectObjCIvars(SuperClass, false, Ivars);
2620 if (!leafClass) {
2621 llvm::append_range(Ivars, OI->ivars());
2622 } else {
2623 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2624 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2625 Iv= Iv->getNextIvar())
2626 Ivars.push_back(Iv);
2627 }
2628}
2629
2630/// CollectInheritedProtocols - Collect all protocols in current class and
2631/// those inherited by it.
2634 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2635 // We can use protocol_iterator here instead of
2636 // all_referenced_protocol_iterator since we are walking all categories.
2637 for (auto *Proto : OI->all_referenced_protocols()) {
2638 CollectInheritedProtocols(Proto, Protocols);
2639 }
2640
2641 // Categories of this Interface.
2642 for (const auto *Cat : OI->visible_categories())
2643 CollectInheritedProtocols(Cat, Protocols);
2644
2645 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2646 while (SD) {
2647 CollectInheritedProtocols(SD, Protocols);
2648 SD = SD->getSuperClass();
2649 }
2650 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2651 for (auto *Proto : OC->protocols()) {
2652 CollectInheritedProtocols(Proto, Protocols);
2653 }
2654 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2655 // Insert the protocol.
2656 if (!Protocols.insert(
2657 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2658 return;
2659
2660 for (auto *Proto : OP->protocols())
2661 CollectInheritedProtocols(Proto, Protocols);
2662 }
2663}
2664
2666 const RecordDecl *RD,
2667 bool CheckIfTriviallyCopyable) {
2668 assert(RD->isUnion() && "Must be union type");
2669 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2670
2671 for (const auto *Field : RD->fields()) {
2672 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2673 CheckIfTriviallyCopyable))
2674 return false;
2675 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2676 if (FieldSize != UnionSize)
2677 return false;
2678 }
2679 return !RD->field_empty();
2680}
2681
2682static int64_t getSubobjectOffset(const FieldDecl *Field,
2683 const ASTContext &Context,
2684 const clang::ASTRecordLayout & /*Layout*/) {
2685 return Context.getFieldOffset(Field);
2686}
2687
2688static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2689 const ASTContext &Context,
2690 const clang::ASTRecordLayout &Layout) {
2691 return Context.toBits(Layout.getBaseClassOffset(RD));
2692}
2693
2694static std::optional<int64_t>
2696 const RecordDecl *RD,
2697 bool CheckIfTriviallyCopyable);
2698
2699static std::optional<int64_t>
2700getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2701 bool CheckIfTriviallyCopyable) {
2702 if (Field->getType()->isRecordType()) {
2703 const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2704 if (!RD->isUnion())
2705 return structHasUniqueObjectRepresentations(Context, RD,
2706 CheckIfTriviallyCopyable);
2707 }
2708
2709 // A _BitInt type may not be unique if it has padding bits
2710 // but if it is a bitfield the padding bits are not used.
2711 bool IsBitIntType = Field->getType()->isBitIntType();
2712 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2713 !Context.hasUniqueObjectRepresentations(Field->getType(),
2714 CheckIfTriviallyCopyable))
2715 return std::nullopt;
2716
2717 int64_t FieldSizeInBits =
2718 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2719 if (Field->isBitField()) {
2720 // If we have explicit padding bits, they don't contribute bits
2721 // to the actual object representation, so return 0.
2722 if (Field->isUnnamedBitField())
2723 return 0;
2724
2725 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2726 if (IsBitIntType) {
2727 if ((unsigned)BitfieldSize >
2728 cast<BitIntType>(Field->getType())->getNumBits())
2729 return std::nullopt;
2730 } else if (BitfieldSize > FieldSizeInBits) {
2731 return std::nullopt;
2732 }
2733 FieldSizeInBits = BitfieldSize;
2734 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2735 Field->getType(), CheckIfTriviallyCopyable)) {
2736 return std::nullopt;
2737 }
2738 return FieldSizeInBits;
2739}
2740
2741static std::optional<int64_t>
2743 bool CheckIfTriviallyCopyable) {
2744 return structHasUniqueObjectRepresentations(Context, RD,
2745 CheckIfTriviallyCopyable);
2746}
2747
2748template <typename RangeT>
2750 const RangeT &Subobjects, int64_t CurOffsetInBits,
2751 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2752 bool CheckIfTriviallyCopyable) {
2753 for (const auto *Subobject : Subobjects) {
2754 std::optional<int64_t> SizeInBits =
2755 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2756 if (!SizeInBits)
2757 return std::nullopt;
2758 if (*SizeInBits != 0) {
2759 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2760 if (Offset != CurOffsetInBits)
2761 return std::nullopt;
2762 CurOffsetInBits += *SizeInBits;
2763 }
2764 }
2765 return CurOffsetInBits;
2766}
2767
2768static std::optional<int64_t>
2770 const RecordDecl *RD,
2771 bool CheckIfTriviallyCopyable) {
2772 assert(!RD->isUnion() && "Must be struct/class type");
2773 const auto &Layout = Context.getASTRecordLayout(RD);
2774
2775 int64_t CurOffsetInBits = 0;
2776 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2777 if (ClassDecl->isDynamicClass())
2778 return std::nullopt;
2779
2781 for (const auto &Base : ClassDecl->bases()) {
2782 // Empty types can be inherited from, and non-empty types can potentially
2783 // have tail padding, so just make sure there isn't an error.
2784 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2785 }
2786
2787 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2788 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2789 });
2790
2791 std::optional<int64_t> OffsetAfterBases =
2793 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2794 if (!OffsetAfterBases)
2795 return std::nullopt;
2796 CurOffsetInBits = *OffsetAfterBases;
2797 }
2798
2799 std::optional<int64_t> OffsetAfterFields =
2801 RD->fields(), CurOffsetInBits, Context, Layout,
2802 CheckIfTriviallyCopyable);
2803 if (!OffsetAfterFields)
2804 return std::nullopt;
2805 CurOffsetInBits = *OffsetAfterFields;
2806
2807 return CurOffsetInBits;
2808}
2809
2811 QualType Ty, bool CheckIfTriviallyCopyable) const {
2812 // C++17 [meta.unary.prop]:
2813 // The predicate condition for a template specialization
2814 // has_unique_object_representations<T> shall be satisfied if and only if:
2815 // (9.1) - T is trivially copyable, and
2816 // (9.2) - any two objects of type T with the same value have the same
2817 // object representation, where:
2818 // - two objects of array or non-union class type are considered to have
2819 // the same value if their respective sequences of direct subobjects
2820 // have the same values, and
2821 // - two objects of union type are considered to have the same value if
2822 // they have the same active member and the corresponding members have
2823 // the same value.
2824 // The set of scalar types for which this condition holds is
2825 // implementation-defined. [ Note: If a type has padding bits, the condition
2826 // does not hold; otherwise, the condition holds true for unsigned integral
2827 // types. -- end note ]
2828 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2829
2830 // Arrays are unique only if their element type is unique.
2831 if (Ty->isArrayType())
2833 CheckIfTriviallyCopyable);
2834
2835 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2836 "hasUniqueObjectRepresentations should not be called with an "
2837 "incomplete type");
2838
2839 // (9.1) - T is trivially copyable...
2840 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2841 return false;
2842
2843 // All integrals and enums are unique.
2844 if (Ty->isIntegralOrEnumerationType()) {
2845 // Except _BitInt types that have padding bits.
2846 if (const auto *BIT = Ty->getAs<BitIntType>())
2847 return getTypeSize(BIT) == BIT->getNumBits();
2848
2849 return true;
2850 }
2851
2852 // All other pointers are unique.
2853 if (Ty->isPointerType())
2854 return true;
2855
2856 if (const auto *MPT = Ty->getAs<MemberPointerType>())
2857 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2858
2859 if (Ty->isRecordType()) {
2860 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2861
2862 if (Record->isInvalidDecl())
2863 return false;
2864
2865 if (Record->isUnion())
2867 CheckIfTriviallyCopyable);
2868
2869 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2870 *this, Record, CheckIfTriviallyCopyable);
2871
2872 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2873 }
2874
2875 // FIXME: More cases to handle here (list by rsmith):
2876 // vectors (careful about, eg, vector of 3 foo)
2877 // _Complex int and friends
2878 // _Atomic T
2879 // Obj-C block pointers
2880 // Obj-C object pointers
2881 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2882 // clk_event_t, queue_t, reserve_id_t)
2883 // There're also Obj-C class types and the Obj-C selector type, but I think it
2884 // makes sense for those to return false here.
2885
2886 return false;
2887}
2888
2890 unsigned count = 0;
2891 // Count ivars declared in class extension.
2892 for (const auto *Ext : OI->known_extensions())
2893 count += Ext->ivar_size();
2894
2895 // Count ivar defined in this class's implementation. This
2896 // includes synthesized ivars.
2897 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2898 count += ImplDecl->ivar_size();
2899
2900 return count;
2901}
2902
2904 if (!E)
2905 return false;
2906
2907 // nullptr_t is always treated as null.
2908 if (E->getType()->isNullPtrType()) return true;
2909
2910 if (E->getType()->isAnyPointerType() &&
2913 return true;
2914
2915 // Unfortunately, __null has type 'int'.
2916 if (isa<GNUNullExpr>(E)) return true;
2917
2918 return false;
2919}
2920
2921/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2922/// exists.
2924 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2925 I = ObjCImpls.find(D);
2926 if (I != ObjCImpls.end())
2927 return cast<ObjCImplementationDecl>(I->second);
2928 return nullptr;
2929}
2930
2931/// Get the implementation of ObjCCategoryDecl, or nullptr if none
2932/// exists.
2934 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2935 I = ObjCImpls.find(D);
2936 if (I != ObjCImpls.end())
2937 return cast<ObjCCategoryImplDecl>(I->second);
2938 return nullptr;
2939}
2940
2941/// Set the implementation of ObjCInterfaceDecl.
2943 ObjCImplementationDecl *ImplD) {
2944 assert(IFaceD && ImplD && "Passed null params");
2945 ObjCImpls[IFaceD] = ImplD;
2946}
2947
2948/// Set the implementation of ObjCCategoryDecl.
2950 ObjCCategoryImplDecl *ImplD) {
2951 assert(CatD && ImplD && "Passed null params");
2952 ObjCImpls[CatD] = ImplD;
2953}
2954
2955const ObjCMethodDecl *
2957 return ObjCMethodRedecls.lookup(MD);
2958}
2959
2961 const ObjCMethodDecl *Redecl) {
2962 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2963 ObjCMethodRedecls[MD] = Redecl;
2964}
2965
2967 const NamedDecl *ND) const {
2968 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2969 return ID;
2970 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2971 return CD->getClassInterface();
2972 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2973 return IMD->getClassInterface();
2974
2975 return nullptr;
2976}
2977
2978/// Get the copy initialization expression of VarDecl, or nullptr if
2979/// none exists.
2981 assert(VD && "Passed null params");
2982 assert(VD->hasAttr<BlocksAttr>() &&
2983 "getBlockVarCopyInits - not __block var");
2984 auto I = BlockVarCopyInits.find(VD);
2985 if (I != BlockVarCopyInits.end())
2986 return I->second;
2987 return {nullptr, false};
2988}
2989
2990/// Set the copy initialization expression of a block var decl.
2992 bool CanThrow) {
2993 assert(VD && CopyExpr && "Passed null params");
2994 assert(VD->hasAttr<BlocksAttr>() &&
2995 "setBlockVarCopyInits - not __block var");
2996 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2997}
2998
3000 unsigned DataSize) const {
3001 if (!DataSize)
3003 else
3004 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3005 "incorrect data size provided to CreateTypeSourceInfo!");
3006
3007 auto *TInfo =
3008 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3009 new (TInfo) TypeSourceInfo(T, DataSize);
3010 return TInfo;
3011}
3012
3014 SourceLocation L) const {
3016 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3017 return DI;
3018}
3019
3020const ASTRecordLayout &
3022 return getObjCLayout(D, nullptr);
3023}
3024
3025const ASTRecordLayout &
3027 const ObjCImplementationDecl *D) const {
3028 return getObjCLayout(D->getClassInterface(), D);
3029}
3030
3033 bool &AnyNonCanonArgs) {
3034 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3035 for (auto &Arg : CanonArgs) {
3036 TemplateArgument OrigArg = Arg;
3037 Arg = C.getCanonicalTemplateArgument(Arg);
3038 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3039 }
3040 return CanonArgs;
3041}
3042
3043//===----------------------------------------------------------------------===//
3044// Type creation/memoization methods
3045//===----------------------------------------------------------------------===//
3046
3048ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3049 unsigned fastQuals = quals.getFastQualifiers();
3050 quals.removeFastQualifiers();
3051
3052 // Check if we've already instantiated this type.
3053 llvm::FoldingSetNodeID ID;
3054 ExtQuals::Profile(ID, baseType, quals);
3055 void *insertPos = nullptr;
3056 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3057 assert(eq->getQualifiers() == quals);
3058 return QualType(eq, fastQuals);
3059 }
3060
3061 // If the base type is not canonical, make the appropriate canonical type.
3062 QualType canon;
3063 if (!baseType->isCanonicalUnqualified()) {
3064 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3065 canonSplit.Quals.addConsistentQualifiers(quals);
3066 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3067
3068 // Re-find the insert position.
3069 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3070 }
3071
3072 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3073 ExtQualNodes.InsertNode(eq, insertPos);
3074 return QualType(eq, fastQuals);
3075}
3076
3078 LangAS AddressSpace) const {
3079 QualType CanT = getCanonicalType(T);
3080 if (CanT.getAddressSpace() == AddressSpace)
3081 return T;
3082
3083 // If we are composing extended qualifiers together, merge together
3084 // into one ExtQuals node.
3085 QualifierCollector Quals;
3086 const Type *TypeNode = Quals.strip(T);
3087
3088 // If this type already has an address space specified, it cannot get
3089 // another one.
3090 assert(!Quals.hasAddressSpace() &&
3091 "Type cannot be in multiple addr spaces!");
3092 Quals.addAddressSpace(AddressSpace);
3093
3094 return getExtQualType(TypeNode, Quals);
3095}
3096
3098 // If the type is not qualified with an address space, just return it
3099 // immediately.
3100 if (!T.hasAddressSpace())
3101 return T;
3102
3103 QualifierCollector Quals;
3104 const Type *TypeNode;
3105 // For arrays, strip the qualifier off the element type, then reconstruct the
3106 // array type
3107 if (T.getTypePtr()->isArrayType()) {
3108 T = getUnqualifiedArrayType(T, Quals);
3109 TypeNode = T.getTypePtr();
3110 } else {
3111 // If we are composing extended qualifiers together, merge together
3112 // into one ExtQuals node.
3113 while (T.hasAddressSpace()) {
3114 TypeNode = Quals.strip(T);
3115
3116 // If the type no longer has an address space after stripping qualifiers,
3117 // jump out.
3118 if (!QualType(TypeNode, 0).hasAddressSpace())
3119 break;
3120
3121 // There might be sugar in the way. Strip it and try again.
3122 T = T.getSingleStepDesugaredType(*this);
3123 }
3124 }
3125
3126 Quals.removeAddressSpace();
3127
3128 // Removal of the address space can mean there are no longer any
3129 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3130 // or required.
3131 if (Quals.hasNonFastQualifiers())
3132 return getExtQualType(TypeNode, Quals);
3133 else
3134 return QualType(TypeNode, Quals.getFastQualifiers());
3135}
3136
3137uint16_t
3139 assert(RD->isPolymorphic() &&
3140 "Attempted to get vtable pointer discriminator on a monomorphic type");
3141 std::unique_ptr<MangleContext> MC(createMangleContext());
3142 SmallString<256> Str;
3143 llvm::raw_svector_ostream Out(Str);
3144 MC->mangleCXXVTable(RD, Out);
3145 return llvm::getPointerAuthStableSipHash(Str);
3146}
3147
3148/// Encode a function type for use in the discriminator of a function pointer
3149/// type. We can't use the itanium scheme for this since C has quite permissive
3150/// rules for type compatibility that we need to be compatible with.
3151///
3152/// Formally, this function associates every function pointer type T with an
3153/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3154/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3155/// compatibility requires equivalent treatment under the ABI, so
3156/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3157/// a subset of ~. Crucially, however, it must be a proper subset because
3158/// CCompatible is not an equivalence relation: for example, int[] is compatible
3159/// with both int[1] and int[2], but the latter are not compatible with each
3160/// other. Therefore this encoding function must be careful to only distinguish
3161/// types if there is no third type with which they are both required to be
3162/// compatible.
3164 raw_ostream &OS, QualType QT) {
3165 // FIXME: Consider address space qualifiers.
3166 const Type *T = QT.getCanonicalType().getTypePtr();
3167
3168 // FIXME: Consider using the C++ type mangling when we encounter a construct
3169 // that is incompatible with C.
3170
3171 switch (T->getTypeClass()) {
3172 case Type::Atomic:
3174 Ctx, OS, cast<AtomicType>(T)->getValueType());
3175
3176 case Type::LValueReference:
3177 OS << "R";
3179 cast<ReferenceType>(T)->getPointeeType());
3180 return;
3181 case Type::RValueReference:
3182 OS << "O";
3184 cast<ReferenceType>(T)->getPointeeType());
3185 return;
3186
3187 case Type::Pointer:
3188 // C11 6.7.6.1p2:
3189 // For two pointer types to be compatible, both shall be identically
3190 // qualified and both shall be pointers to compatible types.
3191 // FIXME: we should also consider pointee types.
3192 OS << "P";
3193 return;
3194
3195 case Type::ObjCObjectPointer:
3196 case Type::BlockPointer:
3197 OS << "P";
3198 return;
3199
3200 case Type::Complex:
3201 OS << "C";
3203 Ctx, OS, cast<ComplexType>(T)->getElementType());
3204
3205 case Type::VariableArray:
3206 case Type::ConstantArray:
3207 case Type::IncompleteArray:
3208 case Type::ArrayParameter:
3209 // C11 6.7.6.2p6:
3210 // For two array types to be compatible, both shall have compatible
3211 // element types, and if both size specifiers are present, and are integer
3212 // constant expressions, then both size specifiers shall have the same
3213 // constant value [...]
3214 //
3215 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3216 // width of the array.
3217 OS << "A";
3219 Ctx, OS, cast<ArrayType>(T)->getElementType());
3220
3221 case Type::ObjCInterface:
3222 case Type::ObjCObject:
3223 OS << "<objc_object>";
3224 return;
3225
3226 case Type::Enum: {
3227 // C11 6.7.2.2p4:
3228 // Each enumerated type shall be compatible with char, a signed integer
3229 // type, or an unsigned integer type.
3230 //
3231 // So we have to treat enum types as integers.
3232 QualType UnderlyingType = cast<EnumType>(T)->getDecl()->getIntegerType();
3234 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3235 }
3236
3237 case Type::FunctionNoProto:
3238 case Type::FunctionProto: {
3239 // C11 6.7.6.3p15:
3240 // For two function types to be compatible, both shall specify compatible
3241 // return types. Moreover, the parameter type lists, if both are present,
3242 // shall agree in the number of parameters and in the use of the ellipsis
3243 // terminator; corresponding parameters shall have compatible types.
3244 //
3245 // That paragraph goes on to describe how unprototyped functions are to be
3246 // handled, which we ignore here. Unprototyped function pointers are hashed
3247 // as though they were prototyped nullary functions since thats probably
3248 // what the user meant. This behavior is non-conforming.
3249 // FIXME: If we add a "custom discriminator" function type attribute we
3250 // should encode functions as their discriminators.
3251 OS << "F";
3252 const auto *FuncType = cast<FunctionType>(T);
3253 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3254 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3255 for (QualType Param : FPT->param_types()) {
3256 Param = Ctx.getSignatureParameterType(Param);
3257 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3258 }
3259 if (FPT->isVariadic())
3260 OS << "z";
3261 }
3262 OS << "E";
3263 return;
3264 }
3265
3266 case Type::MemberPointer: {
3267 OS << "M";
3268 const auto *MPT = T->getAs<MemberPointerType>();
3269 encodeTypeForFunctionPointerAuth(Ctx, OS, QualType(MPT->getClass(), 0));
3270 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3271 return;
3272 }
3273 case Type::ExtVector:
3274 case Type::Vector:
3275 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3276 break;
3277
3278 // Don't bother discriminating based on these types.
3279 case Type::Pipe:
3280 case Type::BitInt:
3281 case Type::ConstantMatrix:
3282 OS << "?";
3283 return;
3284
3285 case Type::Builtin: {
3286 const auto *BTy = T->getAs<BuiltinType>();
3287 switch (BTy->getKind()) {
3288#define SIGNED_TYPE(Id, SingletonId) \
3289 case BuiltinType::Id: \
3290 OS << "i"; \
3291 return;
3292#define UNSIGNED_TYPE(Id, SingletonId) \
3293 case BuiltinType::Id: \
3294 OS << "i"; \
3295 return;
3296#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3297#define BUILTIN_TYPE(Id, SingletonId)
3298#include "clang/AST/BuiltinTypes.def"
3299 llvm_unreachable("placeholder types should not appear here.");
3300
3301 case BuiltinType::Half:
3302 OS << "Dh";
3303 return;
3304 case BuiltinType::Float:
3305 OS << "f";
3306 return;
3307 case BuiltinType::Double:
3308 OS << "d";
3309 return;
3310 case BuiltinType::LongDouble:
3311 OS << "e";
3312 return;
3313 case BuiltinType::Float16:
3314 OS << "DF16_";
3315 return;
3316 case BuiltinType::Float128:
3317 OS << "g";
3318 return;
3319
3320 case BuiltinType::Void:
3321 OS << "v";
3322 return;
3323
3324 case BuiltinType::ObjCId:
3325 case BuiltinType::ObjCClass:
3326 case BuiltinType::ObjCSel:
3327 case BuiltinType::NullPtr:
3328 OS << "P";
3329 return;
3330
3331 // Don't bother discriminating based on OpenCL types.
3332 case BuiltinType::OCLSampler:
3333 case BuiltinType::OCLEvent:
3334 case BuiltinType::OCLClkEvent:
3335 case BuiltinType::OCLQueue:
3336 case BuiltinType::OCLReserveID:
3337 case BuiltinType::BFloat16:
3338 case BuiltinType::VectorQuad:
3339 case BuiltinType::VectorPair:
3340 OS << "?";
3341 return;
3342
3343 // Don't bother discriminating based on these seldom-used types.
3344 case BuiltinType::Ibm128:
3345 return;
3346#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3347 case BuiltinType::Id: \
3348 return;
3349#include "clang/Basic/OpenCLImageTypes.def"
3350#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3351 case BuiltinType::Id: \
3352 return;
3353#include "clang/Basic/OpenCLExtensionTypes.def"
3354#define SVE_TYPE(Name, Id, SingletonId) \
3355 case BuiltinType::Id: \
3356 return;
3357#include "clang/Basic/AArch64SVEACLETypes.def"
3358 case BuiltinType::Dependent:
3359 llvm_unreachable("should never get here");
3360 case BuiltinType::AMDGPUBufferRsrc:
3361 case BuiltinType::WasmExternRef:
3362#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3363#include "clang/Basic/RISCVVTypes.def"
3364 llvm_unreachable("not yet implemented");
3365 }
3366 llvm_unreachable("should never get here");
3367 }
3368 case Type::Record: {
3369 const RecordDecl *RD = T->getAs<RecordType>()->getDecl();
3370 const IdentifierInfo *II = RD->getIdentifier();
3371
3372 // In C++, an immediate typedef of an anonymous struct or union
3373 // is considered to name it for ODR purposes, but C's specification
3374 // of type compatibility does not have a similar rule. Using the typedef
3375 // name in function type discriminators anyway, as we do here,
3376 // therefore technically violates the C standard: two function pointer
3377 // types defined in terms of two typedef'd anonymous structs with
3378 // different names are formally still compatible, but we are assigning
3379 // them different discriminators and therefore incompatible ABIs.
3380 //
3381 // This is a relatively minor violation that significantly improves
3382 // discrimination in some cases and has not caused problems in
3383 // practice. Regardless, it is now part of the ABI in places where
3384 // function type discrimination is used, and it can no longer be
3385 // changed except on new platforms.
3386
3387 if (!II)
3388 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3389 II = Typedef->getDeclName().getAsIdentifierInfo();
3390
3391 if (!II) {
3392 OS << "<anonymous_record>";
3393 return;
3394 }
3395 OS << II->getLength() << II->getName();
3396 return;
3397 }
3398 case Type::DeducedTemplateSpecialization:
3399 case Type::Auto:
3400#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3401#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3402#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3403#define ABSTRACT_TYPE(Class, Base)
3404#define TYPE(Class, Base)
3405#include "clang/AST/TypeNodes.inc"
3406 llvm_unreachable("unexpected non-canonical or dependent type!");
3407 return;
3408 }
3409}
3410
3412 assert(!T->isDependentType() &&
3413 "cannot compute type discriminator of a dependent type");
3414
3415 SmallString<256> Str;
3416 llvm::raw_svector_ostream Out(Str);
3417
3419 T = T->getPointeeType();
3420
3421 if (T->isFunctionType()) {
3423 } else {
3424 T = T.getUnqualifiedType();
3425 std::unique_ptr<MangleContext> MC(createMangleContext());
3426 MC->mangleCanonicalTypeName(T, Out);
3427 }
3428
3429 return llvm::getPointerAuthStableSipHash(Str);
3430}
3431
3433 Qualifiers::GC GCAttr) const {
3434 QualType CanT = getCanonicalType(T);
3435 if (CanT.getObjCGCAttr() == GCAttr)
3436 return T;
3437
3438 if (const auto *ptr = T->getAs<PointerType>()) {
3439 QualType Pointee = ptr->getPointeeType();
3440 if (Pointee->isAnyPointerType()) {
3441 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3442 return getPointerType(ResultType);
3443 }
3444 }
3445
3446 // If we are composing extended qualifiers together, merge together
3447 // into one ExtQuals node.
3448 QualifierCollector Quals;
3449 const Type *TypeNode = Quals.strip(T);
3450
3451 // If this type already has an ObjCGC specified, it cannot get
3452 // another one.
3453 assert(!Quals.hasObjCGCAttr() &&
3454 "Type cannot have multiple ObjCGCs!");
3455 Quals.addObjCGCAttr(GCAttr);
3456
3457 return getExtQualType(TypeNode, Quals);
3458}
3459
3461 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3462 QualType Pointee = Ptr->getPointeeType();
3463 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3464 return getPointerType(removeAddrSpaceQualType(Pointee));
3465 }
3466 }
3467 return T;
3468}
3469
3471 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3472 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3473 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3474
3475 llvm::FoldingSetNodeID ID;
3476 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3477
3478 void *InsertPos = nullptr;
3479 CountAttributedType *CATy =
3480 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3481 if (CATy)
3482 return QualType(CATy, 0);
3483
3484 QualType CanonTy = getCanonicalType(WrappedTy);
3485 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3486 DependentDecls.size());
3488 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3489 OrNull, DependentDecls);
3490 Types.push_back(CATy);
3491 CountAttributedTypes.InsertNode(CATy, InsertPos);
3492
3493 return QualType(CATy, 0);
3494}
3495
3497 FunctionType::ExtInfo Info) {
3498 if (T->getExtInfo() == Info)
3499 return T;
3500
3502 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3503 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3504 } else {
3505 const auto *FPT = cast<FunctionProtoType>(T);
3506 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3507 EPI.ExtInfo = Info;
3508 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3509 }
3510
3511 return cast<FunctionType>(Result.getTypePtr());
3512}
3513
3515 QualType ResultType) {
3516 FD = FD->getMostRecentDecl();
3517 while (true) {
3518 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3519 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3520 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3521 if (FunctionDecl *Next = FD->getPreviousDecl())
3522 FD = Next;
3523 else
3524 break;
3525 }
3527 L->DeducedReturnType(FD, ResultType);
3528}
3529
3530/// Get a function type and produce the equivalent function type with the
3531/// specified exception specification. Type sugar that can be present on a
3532/// declaration of a function with an exception specification is permitted
3533/// and preserved. Other type sugar (for instance, typedefs) is not.
3535 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3536 // Might have some parens.
3537 if (const auto *PT = dyn_cast<ParenType>(Orig))
3538 return getParenType(
3539 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3540
3541 // Might be wrapped in a macro qualified type.
3542 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3543 return getMacroQualifiedType(
3544 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3545 MQT->getMacroIdentifier());
3546
3547 // Might have a calling-convention attribute.
3548 if (const auto *AT = dyn_cast<AttributedType>(Orig))
3549 return getAttributedType(
3550 AT->getAttrKind(),
3551 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3552 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3553
3554 // Anything else must be a function type. Rebuild it with the new exception
3555 // specification.
3556 const auto *Proto = Orig->castAs<FunctionProtoType>();
3557 return getFunctionType(
3558 Proto->getReturnType(), Proto->getParamTypes(),
3559 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3560}
3561
3563 QualType U) const {
3564 return hasSameType(T, U) ||
3565 (getLangOpts().CPlusPlus17 &&
3568}
3569
3571 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3572 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3573 SmallVector<QualType, 16> Args(Proto->param_types().size());
3574 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3575 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3576 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3577 }
3578
3579 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3580 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3581 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3582 }
3583
3584 return T;
3585}
3586
3588 return hasSameType(T, U) ||
3591}
3592
3595 bool AsWritten) {
3596 // Update the type.
3597 QualType Updated =
3599 FD->setType(Updated);
3600
3601 if (!AsWritten)
3602 return;
3603
3604 // Update the type in the type source information too.
3605 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3606 // If the type and the type-as-written differ, we may need to update
3607 // the type-as-written too.
3608 if (TSInfo->getType() != FD->getType())
3609 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3610
3611 // FIXME: When we get proper type location information for exceptions,
3612 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3613 // up the TypeSourceInfo;
3614 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3615 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3616 "TypeLoc size mismatch from updating exception specification");
3617 TSInfo->overrideType(Updated);
3618 }
3619}
3620
3621/// getComplexType - Return the uniqued reference to the type for a complex
3622/// number with the specified element type.
3624 // Unique pointers, to guarantee there is only one pointer of a particular
3625 // structure.
3626 llvm::FoldingSetNodeID ID;
3628
3629 void *InsertPos = nullptr;
3630 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3631 return QualType(CT, 0);
3632
3633 // If the pointee type isn't canonical, this won't be a canonical type either,
3634 // so fill in the canonical type field.
3635 QualType Canonical;
3636 if (!T.isCanonical()) {
3637 Canonical = getComplexType(getCanonicalType(T));
3638
3639 // Get the new insert position for the node we care about.
3640 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3641 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3642 }
3643 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3644 Types.push_back(New);
3645 ComplexTypes.InsertNode(New, InsertPos);
3646 return QualType(New, 0);
3647}
3648
3649/// getPointerType - Return the uniqued reference to the type for a pointer to
3650/// the specified type.
3652 // Unique pointers, to guarantee there is only one pointer of a particular
3653 // structure.
3654 llvm::FoldingSetNodeID ID;
3656
3657 void *InsertPos = nullptr;
3658 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3659 return QualType(PT, 0);
3660
3661 // If the pointee type isn't canonical, this won't be a canonical type either,
3662 // so fill in the canonical type field.
3663 QualType Canonical;
3664 if (!T.isCanonical()) {
3665 Canonical = getPointerType(getCanonicalType(T));
3666
3667 // Get the new insert position for the node we care about.
3668 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3669 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3670 }
3671 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3672 Types.push_back(New);
3673 PointerTypes.InsertNode(New, InsertPos);
3674 return QualType(New, 0);
3675}
3676
3678 llvm::FoldingSetNodeID ID;
3679 AdjustedType::Profile(ID, Orig, New);
3680 void *InsertPos = nullptr;
3681 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3682 if (AT)
3683 return QualType(AT, 0);
3684
3685 QualType Canonical = getCanonicalType(New);
3686
3687 // Get the new insert position for the node we care about.
3688 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3689 assert(!AT && "Shouldn't be in the map!");
3690
3691 AT = new (*this, alignof(AdjustedType))
3692 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3693 Types.push_back(AT);
3694 AdjustedTypes.InsertNode(AT, InsertPos);
3695 return QualType(AT, 0);
3696}
3697
3699 llvm::FoldingSetNodeID ID;
3700 AdjustedType::Profile(ID, Orig, Decayed);
3701 void *InsertPos = nullptr;
3702 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3703 if (AT)
3704 return QualType(AT, 0);
3705
3706 QualType Canonical = getCanonicalType(Decayed);
3707
3708 // Get the new insert position for the node we care about.
3709 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3710 assert(!AT && "Shouldn't be in the map!");
3711
3712 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3713 Types.push_back(AT);
3714 AdjustedTypes.InsertNode(AT, InsertPos);
3715 return QualType(AT, 0);
3716}
3717
3719 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3720
3721 QualType Decayed;
3722
3723 // C99 6.7.5.3p7:
3724 // A declaration of a parameter as "array of type" shall be
3725 // adjusted to "qualified pointer to type", where the type
3726 // qualifiers (if any) are those specified within the [ and ] of
3727 // the array type derivation.
3728 if (T->isArrayType())
3729 Decayed = getArrayDecayedType(T);
3730
3731 // C99 6.7.5.3p8:
3732 // A declaration of a parameter as "function returning type"
3733 // shall be adjusted to "pointer to function returning type", as
3734 // in 6.3.2.1.
3735 if (T->isFunctionType())
3736 Decayed = getPointerType(T);
3737
3738 return getDecayedType(T, Decayed);
3739}
3740
3742 if (Ty->isArrayParameterType())
3743 return Ty;
3744 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3745 const auto *ATy = cast<ConstantArrayType>(Ty);
3746 llvm::FoldingSetNodeID ID;
3747 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3748 ATy->getSizeExpr(), ATy->getSizeModifier(),
3749 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3750 void *InsertPos = nullptr;
3751 ArrayParameterType *AT =
3752 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3753 if (AT)
3754 return QualType(AT, 0);
3755
3756 QualType Canonical;
3757 if (!Ty.isCanonical()) {
3758 Canonical = getArrayParameterType(getCanonicalType(Ty));
3759
3760 // Get the new insert position for the node we care about.
3761 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3762 assert(!AT && "Shouldn't be in the map!");
3763 }
3764
3765 AT = new (*this, alignof(ArrayParameterType))
3766 ArrayParameterType(ATy, Canonical);
3767 Types.push_back(AT);
3768 ArrayParameterTypes.InsertNode(AT, InsertPos);
3769 return QualType(AT, 0);
3770}
3771
3772/// getBlockPointerType - Return the uniqued reference to the type for
3773/// a pointer to the specified block.
3775 assert(T->isFunctionType() && "block of function types only");
3776 // Unique pointers, to guarantee there is only one block of a particular
3777 // structure.
3778 llvm::FoldingSetNodeID ID;
3780
3781 void *InsertPos = nullptr;
3782 if (BlockPointerType *PT =
3783 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3784 return QualType(PT, 0);
3785
3786 // If the block pointee type isn't canonical, this won't be a canonical
3787 // type either so fill in the canonical type field.
3788 QualType Canonical;
3789 if (!T.isCanonical()) {
3791
3792 // Get the new insert position for the node we care about.
3793 BlockPointerType *NewIP =
3794 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3795 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3796 }
3797 auto *New =
3798 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3799 Types.push_back(New);
3800 BlockPointerTypes.InsertNode(New, InsertPos);
3801 return QualType(New, 0);
3802}
3803
3804/// getLValueReferenceType - Return the uniqued reference to the type for an
3805/// lvalue reference to the specified type.
3807ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3808 assert((!T->isPlaceholderType() ||
3809 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3810 "Unresolved placeholder type");
3811
3812 // Unique pointers, to guarantee there is only one pointer of a particular
3813 // structure.
3814 llvm::FoldingSetNodeID ID;
3815 ReferenceType::Profile(ID, T, SpelledAsLValue);
3816
3817 void *InsertPos = nullptr;
3818 if (LValueReferenceType *RT =
3819 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3820 return QualType(RT, 0);
3821
3822 const auto *InnerRef = T->getAs<ReferenceType>();
3823
3824 // If the referencee type isn't canonical, this won't be a canonical type
3825 // either, so fill in the canonical type field.
3826 QualType Canonical;
3827 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3828 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3829 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3830
3831 // Get the new insert position for the node we care about.
3832 LValueReferenceType *NewIP =
3833 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3834 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3835 }
3836
3837 auto *New = new (*this, alignof(LValueReferenceType))
3838 LValueReferenceType(T, Canonical, SpelledAsLValue);
3839 Types.push_back(New);
3840 LValueReferenceTypes.InsertNode(New, InsertPos);
3841
3842 return QualType(New, 0);
3843}
3844
3845/// getRValueReferenceType - Return the uniqued reference to the type for an
3846/// rvalue reference to the specified type.
3848 assert((!T->isPlaceholderType() ||
3849 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3850 "Unresolved placeholder type");
3851
3852 // Unique pointers, to guarantee there is only one pointer of a particular
3853 // structure.
3854 llvm::FoldingSetNodeID ID;
3855 ReferenceType::Profile(ID, T, false);
3856
3857 void *InsertPos = nullptr;
3858 if (RValueReferenceType *RT =
3859 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3860 return QualType(RT, 0);
3861
3862 const auto *InnerRef = T->getAs<ReferenceType>();
3863
3864 // If the referencee type isn't canonical, this won't be a canonical type
3865 // either, so fill in the canonical type field.
3866 QualType Canonical;
3867 if (InnerRef || !T.isCanonical()) {
3868 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3869 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3870
3871 // Get the new insert position for the node we care about.
3872 RValueReferenceType *NewIP =
3873 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3874 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3875 }
3876
3877 auto *New = new (*this, alignof(RValueReferenceType))
3878 RValueReferenceType(T, Canonical);
3879 Types.push_back(New);
3880 RValueReferenceTypes.InsertNode(New, InsertPos);
3881 return QualType(New, 0);
3882}
3883
3884/// getMemberPointerType - Return the uniqued reference to the type for a
3885/// member pointer to the specified type, in the specified class.
3887 // Unique pointers, to guarantee there is only one pointer of a particular
3888 // structure.
3889 llvm::FoldingSetNodeID ID;
3890 MemberPointerType::Profile(ID, T, Cls);
3891
3892 void *InsertPos = nullptr;
3893 if (MemberPointerType *PT =
3894 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3895 return QualType(PT, 0);
3896
3897 // If the pointee or class type isn't canonical, this won't be a canonical
3898 // type either, so fill in the canonical type field.
3899 QualType Canonical;
3900 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3902
3903 // Get the new insert position for the node we care about.
3904 MemberPointerType *NewIP =
3905 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3906 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3907 }
3908 auto *New = new (*this, alignof(MemberPointerType))
3909 MemberPointerType(T, Cls, Canonical);
3910 Types.push_back(New);
3911 MemberPointerTypes.InsertNode(New, InsertPos);
3912 return QualType(New, 0);
3913}
3914
3915/// getConstantArrayType - Return the unique reference to the type for an
3916/// array of the specified element type.
3918 const llvm::APInt &ArySizeIn,
3919 const Expr *SizeExpr,
3921 unsigned IndexTypeQuals) const {
3922 assert((EltTy->isDependentType() ||
3923 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3924 "Constant array of VLAs is illegal!");
3925
3926 // We only need the size as part of the type if it's instantiation-dependent.
3927 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3928 SizeExpr = nullptr;
3929
3930 // Convert the array size into a canonical width matching the pointer size for
3931 // the target.
3932 llvm::APInt ArySize(ArySizeIn);
3933 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3934
3935 llvm::FoldingSetNodeID ID;
3936 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
3937 ASM, IndexTypeQuals);
3938
3939 void *InsertPos = nullptr;
3940 if (ConstantArrayType *ATP =
3941 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3942 return QualType(ATP, 0);
3943
3944 // If the element type isn't canonical or has qualifiers, or the array bound
3945 // is instantiation-dependent, this won't be a canonical type either, so fill
3946 // in the canonical type field.
3947 QualType Canon;
3948 // FIXME: Check below should look for qualifiers behind sugar.
3949 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3950 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3951 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3952 ASM, IndexTypeQuals);
3953 Canon = getQualifiedType(Canon, canonSplit.Quals);
3954
3955 // Get the new insert position for the node we care about.
3956 ConstantArrayType *NewIP =
3957 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3958 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3959 }
3960
3961 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
3962 ASM, IndexTypeQuals);
3963 ConstantArrayTypes.InsertNode(New, InsertPos);
3964 Types.push_back(New);
3965 return QualType(New, 0);
3966}
3967
3968/// getVariableArrayDecayedType - Turns the given type, which may be
3969/// variably-modified, into the corresponding type with all the known
3970/// sizes replaced with [*].
3972 // Vastly most common case.
3973 if (!type->isVariablyModifiedType()) return type;
3974
3975 QualType result;
3976
3977 SplitQualType split = type.getSplitDesugaredType();
3978 const Type *ty = split.Ty;
3979 switch (ty->getTypeClass()) {
3980#define TYPE(Class, Base)
3981#define ABSTRACT_TYPE(Class, Base)
3982#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3983#include "clang/AST/TypeNodes.inc"
3984 llvm_unreachable("didn't desugar past all non-canonical types?");
3985
3986 // These types should never be variably-modified.
3987 case Type::Builtin:
3988 case Type::Complex:
3989 case Type::Vector:
3990 case Type::DependentVector:
3991 case Type::ExtVector:
3992 case Type::DependentSizedExtVector:
3993 case Type::ConstantMatrix:
3994 case Type::DependentSizedMatrix:
3995 case Type::DependentAddressSpace:
3996 case Type::ObjCObject:
3997 case Type::ObjCInterface:
3998 case Type::ObjCObjectPointer:
3999 case Type::Record:
4000 case Type::Enum:
4001 case Type::UnresolvedUsing:
4002 case Type::TypeOfExpr:
4003 case Type::TypeOf:
4004 case Type::Decltype:
4005 case Type::UnaryTransform:
4006 case Type::DependentName:
4007 case Type::InjectedClassName:
4008 case Type::TemplateSpecialization:
4009 case Type::DependentTemplateSpecialization:
4010 case Type::TemplateTypeParm:
4011 case Type::SubstTemplateTypeParmPack:
4012 case Type::Auto:
4013 case Type::DeducedTemplateSpecialization:
4014 case Type::PackExpansion:
4015 case Type::PackIndexing:
4016 case Type::BitInt:
4017 case Type::DependentBitInt:
4018 case Type::ArrayParameter:
4019 llvm_unreachable("type should never be variably-modified");
4020
4021 // These types can be variably-modified but should never need to
4022 // further decay.
4023 case Type::FunctionNoProto:
4024 case Type::FunctionProto:
4025 case Type::BlockPointer:
4026 case Type::MemberPointer:
4027 case Type::Pipe:
4028 return type;
4029
4030 // These types can be variably-modified. All these modifications
4031 // preserve structure except as noted by comments.
4032 // TODO: if we ever care about optimizing VLAs, there are no-op
4033 // optimizations available here.
4034 case Type::Pointer:
4036 cast<PointerType>(ty)->getPointeeType()));
4037 break;
4038
4039 case Type::LValueReference: {
4040 const auto *lv = cast<LValueReferenceType>(ty);
4041 result = getLValueReferenceType(
4042 getVariableArrayDecayedType(lv->getPointeeType()),
4043 lv->isSpelledAsLValue());
4044 break;
4045 }
4046
4047 case Type::RValueReference: {
4048 const auto *lv = cast<RValueReferenceType>(ty);
4049 result = getRValueReferenceType(
4050 getVariableArrayDecayedType(lv->getPointeeType()));
4051 break;
4052 }
4053
4054 case Type::Atomic: {
4055 const auto *at = cast<AtomicType>(ty);
4056 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4057 break;
4058 }
4059
4060 case Type::ConstantArray: {
4061 const auto *cat = cast<ConstantArrayType>(ty);
4062 result = getConstantArrayType(
4063 getVariableArrayDecayedType(cat->getElementType()),
4064 cat->getSize(),
4065 cat->getSizeExpr(),
4066 cat->getSizeModifier(),
4067 cat->getIndexTypeCVRQualifiers());
4068 break;
4069 }
4070
4071 case Type::DependentSizedArray: {
4072 const auto *dat = cast<DependentSizedArrayType>(ty);
4074 getVariableArrayDecayedType(dat->getElementType()),
4075 dat->getSizeExpr(),
4076 dat->getSizeModifier(),
4077 dat->getIndexTypeCVRQualifiers(),
4078 dat->getBracketsRange());
4079 break;
4080 }
4081
4082 // Turn incomplete types into [*] types.
4083 case Type::IncompleteArray: {
4084 const auto *iat = cast<IncompleteArrayType>(ty);
4085 result =
4087 /*size*/ nullptr, ArraySizeModifier::Normal,
4088 iat->getIndexTypeCVRQualifiers(), SourceRange());
4089 break;
4090 }
4091
4092 // Turn VLA types into [*] types.
4093 case Type::VariableArray: {
4094 const auto *vat = cast<VariableArrayType>(ty);
4095 result = getVariableArrayType(
4096 getVariableArrayDecayedType(vat->getElementType()),
4097 /*size*/ nullptr, ArraySizeModifier::Star,
4098 vat->getIndexTypeCVRQualifiers(), vat->getBracketsRange());
4099 break;
4100 }
4101 }
4102
4103 // Apply the top-level qualifiers from the original.
4104 return getQualifiedType(result, split.Quals);
4105}
4106
4107/// getVariableArrayType - Returns a non-unique reference to the type for a
4108/// variable array of the specified element type.
4111 unsigned IndexTypeQuals,
4112 SourceRange Brackets) const {
4113 // Since we don't unique expressions, it isn't possible to unique VLA's
4114 // that have an expression provided for their size.
4115 QualType Canon;
4116
4117 // Be sure to pull qualifiers off the element type.
4118 // FIXME: Check below should look for qualifiers behind sugar.
4119 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4120 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4121 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4122 IndexTypeQuals, Brackets);
4123 Canon = getQualifiedType(Canon, canonSplit.Quals);
4124 }
4125
4126 auto *New = new (*this, alignof(VariableArrayType))
4127 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
4128
4129 VariableArrayTypes.push_back(New);
4130 Types.push_back(New);
4131 return QualType(New, 0);
4132}
4133
4134/// getDependentSizedArrayType - Returns a non-unique reference to
4135/// the type for a dependently-sized array of the specified element
4136/// type.
4138 Expr *numElements,
4140 unsigned elementTypeQuals,
4141 SourceRange brackets) const {
4142 assert((!numElements || numElements->isTypeDependent() ||
4143 numElements->isValueDependent()) &&
4144 "Size must be type- or value-dependent!");
4145
4146 SplitQualType canonElementType = getCanonicalType(elementType).split();
4147
4148 void *insertPos = nullptr;
4149 llvm::FoldingSetNodeID ID;
4151 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4152 ASM, elementTypeQuals, numElements);
4153
4154 // Look for an existing type with these properties.
4155 DependentSizedArrayType *canonTy =
4156 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4157
4158 // Dependently-sized array types that do not have a specified number
4159 // of elements will have their sizes deduced from a dependent
4160 // initializer.
4161 if (!numElements) {
4162 if (canonTy)
4163 return QualType(canonTy, 0);
4164
4165 auto *newType = new (*this, alignof(DependentSizedArrayType))
4166 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4167 elementTypeQuals, brackets);
4168 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4169 Types.push_back(newType);
4170 return QualType(newType, 0);
4171 }
4172
4173 // If we don't have one, build one.
4174 if (!canonTy) {
4175 canonTy = new (*this, alignof(DependentSizedArrayType))
4176 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4177 numElements, ASM, elementTypeQuals, brackets);
4178 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4179 Types.push_back(canonTy);
4180 }
4181
4182 // Apply qualifiers from the element type to the array.
4183 QualType canon = getQualifiedType(QualType(canonTy,0),
4184 canonElementType.Quals);
4185
4186 // If we didn't need extra canonicalization for the element type or the size
4187 // expression, then just use that as our result.
4188 if (QualType(canonElementType.Ty, 0) == elementType &&
4189 canonTy->getSizeExpr() == numElements)
4190 return canon;
4191
4192 // Otherwise, we need to build a type which follows the spelling
4193 // of the element type.
4194 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4195 DependentSizedArrayType(elementType, canon, numElements, ASM,
4196 elementTypeQuals, brackets);
4197 Types.push_back(sugaredType);
4198 return QualType(sugaredType, 0);
4199}
4200
4203 unsigned elementTypeQuals) const {
4204 llvm::FoldingSetNodeID ID;
4205 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4206
4207 void *insertPos = nullptr;
4208 if (IncompleteArrayType *iat =
4209 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4210 return QualType(iat, 0);
4211
4212 // If the element type isn't canonical, this won't be a canonical type
4213 // either, so fill in the canonical type field. We also have to pull
4214 // qualifiers off the element type.
4215 QualType canon;
4216
4217 // FIXME: Check below should look for qualifiers behind sugar.
4218 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4219 SplitQualType canonSplit = getCanonicalType(elementType).split();
4220 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4221 ASM, elementTypeQuals);
4222 canon = getQualifiedType(canon, canonSplit.Quals);
4223
4224 // Get the new insert position for the node we care about.
4225 IncompleteArrayType *existing =
4226 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4227 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4228 }
4229
4230 auto *newType = new (*this, alignof(IncompleteArrayType))
4231 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4232
4233 IncompleteArrayTypes.InsertNode(newType, insertPos);
4234 Types.push_back(newType);
4235 return QualType(newType, 0);
4236}
4237
4240#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4241 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4242 NUMVECTORS};
4243
4244#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4245 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4246
4247 switch (Ty->getKind()) {
4248 default:
4249 llvm_unreachable("Unsupported builtin vector type");
4250 case BuiltinType::SveInt8:
4251 return SVE_INT_ELTTY(8, 16, true, 1);
4252 case BuiltinType::SveUint8:
4253 return SVE_INT_ELTTY(8, 16, false, 1);
4254 case BuiltinType::SveInt8x2:
4255 return SVE_INT_ELTTY(8, 16, true, 2);
4256 case BuiltinType::SveUint8x2:
4257 return SVE_INT_ELTTY(8, 16, false, 2);
4258 case BuiltinType::SveInt8x3:
4259 return SVE_INT_ELTTY(8, 16, true, 3);
4260 case BuiltinType::SveUint8x3:
4261 return SVE_INT_ELTTY(8, 16, false, 3);
4262 case BuiltinType::SveInt8x4:
4263 return SVE_INT_ELTTY(8, 16, true, 4);
4264 case BuiltinType::SveUint8x4:
4265 return SVE_INT_ELTTY(8, 16, false, 4);
4266 case BuiltinType::SveInt16:
4267 return SVE_INT_ELTTY(16, 8, true, 1);
4268 case BuiltinType::SveUint16:
4269 return SVE_INT_ELTTY(16, 8, false, 1);
4270 case BuiltinType::SveInt16x2:
4271 return SVE_INT_ELTTY(16, 8, true, 2);
4272 case BuiltinType::SveUint16x2:
4273 return SVE_INT_ELTTY(16, 8, false, 2);
4274 case BuiltinType::SveInt16x3:
4275 return SVE_INT_ELTTY(16, 8, true, 3);
4276 case BuiltinType::SveUint16x3:
4277 return SVE_INT_ELTTY(16, 8, false, 3);
4278 case BuiltinType::SveInt16x4:
4279 return SVE_INT_ELTTY(16, 8, true, 4);
4280 case BuiltinType::SveUint16x4:
4281 return SVE_INT_ELTTY(16, 8, false, 4);
4282 case BuiltinType::SveInt32:
4283 return SVE_INT_ELTTY(32, 4, true, 1);
4284 case BuiltinType::SveUint32:
4285 return SVE_INT_ELTTY(32, 4, false, 1);
4286 case BuiltinType::SveInt32x2:
4287 return SVE_INT_ELTTY(32, 4, true, 2);
4288 case BuiltinType::SveUint32x2:
4289 return SVE_INT_ELTTY(32, 4, false, 2);
4290 case BuiltinType::SveInt32x3:
4291 return SVE_INT_ELTTY(32, 4, true, 3);
4292 case BuiltinType::SveUint32x3:
4293 return SVE_INT_ELTTY(32, 4, false, 3);
4294 case BuiltinType::SveInt32x4:
4295 return SVE_INT_ELTTY(32, 4, true, 4);
4296 case BuiltinType::SveUint32x4:
4297 return SVE_INT_ELTTY(32, 4, false, 4);
4298 case BuiltinType::SveInt64:
4299 return SVE_INT_ELTTY(64, 2, true, 1);
4300 case BuiltinType::SveUint64:
4301 return SVE_INT_ELTTY(64, 2, false, 1);
4302 case BuiltinType::SveInt64x2:
4303 return SVE_INT_ELTTY(64, 2, true, 2);
4304 case BuiltinType::SveUint64x2:
4305 return SVE_INT_ELTTY(64, 2, false, 2);
4306 case BuiltinType::SveInt64x3:
4307 return SVE_INT_ELTTY(64, 2, true, 3);
4308 case BuiltinType::SveUint64x3:
4309 return SVE_INT_ELTTY(64, 2, false, 3);
4310 case BuiltinType::SveInt64x4:
4311 return SVE_INT_ELTTY(64, 2, true, 4);
4312 case BuiltinType::SveUint64x4:
4313 return SVE_INT_ELTTY(64, 2, false, 4);
4314 case BuiltinType::SveBool:
4315 return SVE_ELTTY(BoolTy, 16, 1);
4316 case BuiltinType::SveBoolx2:
4317 return SVE_ELTTY(BoolTy, 16, 2);
4318 case BuiltinType::SveBoolx4:
4319 return SVE_ELTTY(BoolTy, 16, 4);
4320 case BuiltinType::SveFloat16:
4321 return SVE_ELTTY(HalfTy, 8, 1);
4322 case BuiltinType::SveFloat16x2:
4323 return SVE_ELTTY(HalfTy, 8, 2);
4324 case BuiltinType::SveFloat16x3:
4325 return SVE_ELTTY(HalfTy, 8, 3);
4326 case BuiltinType::SveFloat16x4:
4327 return SVE_ELTTY(HalfTy, 8, 4);
4328 case BuiltinType::SveFloat32:
4329 return SVE_ELTTY(FloatTy, 4, 1);
4330 case BuiltinType::SveFloat32x2:
4331 return SVE_ELTTY(FloatTy, 4, 2);
4332 case BuiltinType::SveFloat32x3:
4333 return SVE_ELTTY(FloatTy, 4, 3);
4334 case BuiltinType::SveFloat32x4:
4335 return SVE_ELTTY(FloatTy, 4, 4);
4336 case BuiltinType::SveFloat64:
4337 return SVE_ELTTY(DoubleTy, 2, 1);
4338 case BuiltinType::SveFloat64x2:
4339 return SVE_ELTTY(DoubleTy, 2, 2);
4340 case BuiltinType::SveFloat64x3:
4341 return SVE_ELTTY(DoubleTy, 2, 3);
4342 case BuiltinType::SveFloat64x4:
4343 return SVE_ELTTY(DoubleTy, 2, 4);
4344 case BuiltinType::SveBFloat16:
4345 return SVE_ELTTY(BFloat16Ty, 8, 1);
4346 case BuiltinType::SveBFloat16x2:
4347 return SVE_ELTTY(BFloat16Ty, 8, 2);
4348 case BuiltinType::SveBFloat16x3:
4349 return SVE_ELTTY(BFloat16Ty, 8, 3);
4350 case BuiltinType::SveBFloat16x4:
4351 return SVE_ELTTY(BFloat16Ty, 8, 4);
4352#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4353 IsSigned) \
4354 case BuiltinType::Id: \
4355 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4356 llvm::ElementCount::getScalable(NumEls), NF};
4357#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4358 case BuiltinType::Id: \
4359 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4360 llvm::ElementCount::getScalable(NumEls), NF};
4361#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4362 case BuiltinType::Id: \
4363 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4364#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4365 case BuiltinType::Id: \
4366 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4367#include "clang/Basic/RISCVVTypes.def"
4368 }
4369}
4370
4371/// getExternrefType - Return a WebAssembly externref type, which represents an
4372/// opaque reference to a host value.
4374 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4375#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4376 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4377 return SingletonId;
4378#include "clang/Basic/WebAssemblyReferenceTypes.def"
4379 }
4380 llvm_unreachable(
4381 "shouldn't try to generate type externref outside WebAssembly target");
4382}
4383
4384/// getScalableVectorType - Return the unique reference to a scalable vector
4385/// type of the specified element type and size. VectorType must be a built-in
4386/// type.
4388 unsigned NumFields) const {
4389 if (Target->hasAArch64SVETypes()) {
4390 uint64_t EltTySize = getTypeSize(EltTy);
4391#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
4392 IsSigned, IsFP, IsBF) \
4393 if (!EltTy->isBooleanType() && \
4394 ((EltTy->hasIntegerRepresentation() && \
4395 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4396 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4397 IsFP && !IsBF) || \
4398 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4399 IsBF && !IsFP)) && \
4400 EltTySize == ElBits && NumElts == NumEls) { \
4401 return SingletonId; \
4402 }
4403#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
4404 if (EltTy->isBooleanType() && NumElts == NumEls) \
4405 return SingletonId;
4406#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingleTonId)
4407#include "clang/Basic/AArch64SVEACLETypes.def"
4408 } else if (Target->hasRISCVVTypes()) {
4409 uint64_t EltTySize = getTypeSize(EltTy);
4410#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4411 IsFP, IsBF) \
4412 if (!EltTy->isBooleanType() && \
4413 ((EltTy->hasIntegerRepresentation() && \
4414 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4415 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4416 IsFP && !IsBF) || \
4417 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4418 IsBF && !IsFP)) && \
4419 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4420 return SingletonId;
4421#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4422 if (EltTy->isBooleanType() && NumElts == NumEls) \
4423 return SingletonId;
4424#include "clang/Basic/RISCVVTypes.def"
4425 }
4426 return QualType();
4427}
4428
4429/// getVectorType - Return the unique reference to a vector type of
4430/// the specified element type and size. VectorType must be a built-in type.
4432 VectorKind VecKind) const {
4433 assert(vecType->isBuiltinType() ||
4434 (vecType->isBitIntType() &&
4435 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4436 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4437 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4438
4439 // Check if we've already instantiated a vector of this type.
4440 llvm::FoldingSetNodeID ID;
4441 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4442
4443 void *InsertPos = nullptr;
4444 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4445 return QualType(VTP, 0);
4446
4447 // If the element type isn't canonical, this won't be a canonical type either,
4448 // so fill in the canonical type field.
4449 QualType Canonical;
4450 if (!vecType.isCanonical()) {
4451 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4452
4453 // Get the new insert position for the node we care about.
4454 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4455 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4456 }
4457 auto *New = new (*this, alignof(VectorType))
4458 VectorType(vecType, NumElts, Canonical, VecKind);
4459 VectorTypes.InsertNode(New, InsertPos);
4460 Types.push_back(New);
4461 return QualType(New, 0);
4462}
4463
4465 SourceLocation AttrLoc,
4466 VectorKind VecKind) const {
4467 llvm::FoldingSetNodeID ID;
4468 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4469 VecKind);
4470 void *InsertPos = nullptr;
4471 DependentVectorType *Canon =
4472 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4474
4475 if (Canon) {
4476 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4477 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4478 } else {
4479 QualType CanonVecTy = getCanonicalType(VecType);
4480 if (CanonVecTy == VecType) {
4481 New = new (*this, alignof(DependentVectorType))
4482 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4483
4484 DependentVectorType *CanonCheck =
4485 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4486 assert(!CanonCheck &&
4487 "Dependent-sized vector_size canonical type broken");
4488 (void)CanonCheck;
4489 DependentVectorTypes.InsertNode(New, InsertPos);
4490 } else {
4491 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4492 SourceLocation(), VecKind);
4493 New = new (*this, alignof(DependentVectorType))
4494 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4495 }
4496 }
4497
4498 Types.push_back(New);
4499 return QualType(New, 0);
4500}
4501
4502/// getExtVectorType - Return the unique reference to an extended vector type of
4503/// the specified element type and size. VectorType must be a built-in type.
4505 unsigned NumElts) const {
4506 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4507 (vecType->isBitIntType() &&
4508 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4509 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4510 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4511
4512 // Check if we've already instantiated a vector of this type.
4513 llvm::FoldingSetNodeID ID;
4514 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4516 void *InsertPos = nullptr;
4517 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4518 return QualType(VTP, 0);
4519
4520 // If the element type isn't canonical, this won't be a canonical type either,
4521 // so fill in the canonical type field.
4522 QualType Canonical;
4523 if (!vecType.isCanonical()) {
4524 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4525
4526 // Get the new insert position for the node we care about.
4527 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4528 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4529 }
4530 auto *New = new (*this, alignof(ExtVectorType))
4531 ExtVectorType(vecType, NumElts, Canonical);
4532 VectorTypes.InsertNode(New, InsertPos);
4533 Types.push_back(New);
4534 return QualType(New, 0);
4535}
4536
4539 Expr *SizeExpr,
4540 SourceLocation AttrLoc) const {
4541 llvm::FoldingSetNodeID ID;
4543 SizeExpr);
4544
4545 void *InsertPos = nullptr;
4547 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4549 if (Canon) {
4550 // We already have a canonical version of this array type; use it as
4551 // the canonical type for a newly-built type.
4552 New = new (*this, alignof(DependentSizedExtVectorType))
4553 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4554 AttrLoc);
4555 } else {
4556 QualType CanonVecTy = getCanonicalType(vecType);
4557 if (CanonVecTy == vecType) {
4558 New = new (*this, alignof(DependentSizedExtVectorType))
4559 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4560
4561 DependentSizedExtVectorType *CanonCheck
4562 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4563 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4564 (void)CanonCheck;
4565 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4566 } else {
4567 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4568 SourceLocation());
4569 New = new (*this, alignof(DependentSizedExtVectorType))
4570 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4571 }
4572 }
4573
4574 Types.push_back(New);
4575 return QualType(New, 0);
4576}
4577
4579 unsigned NumColumns) const {
4580 llvm::FoldingSetNodeID ID;
4581 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4582 Type::ConstantMatrix);
4583
4584 assert(MatrixType::isValidElementType(ElementTy) &&
4585 "need a valid element type");
4586 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4588 "need valid matrix dimensions");
4589 void *InsertPos = nullptr;
4590 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4591 return QualType(MTP, 0);
4592
4593 QualType Canonical;
4594 if (!ElementTy.isCanonical()) {
4595 Canonical =
4596 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4597
4598 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4599 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4600 (void)NewIP;
4601 }
4602
4603 auto *New = new (*this, alignof(ConstantMatrixType))
4604 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4605 MatrixTypes.InsertNode(New, InsertPos);
4606 Types.push_back(New);
4607 return QualType(New, 0);
4608}
4609
4611 Expr *RowExpr,
4612 Expr *ColumnExpr,
4613 SourceLocation AttrLoc) const {
4614 QualType CanonElementTy = getCanonicalType(ElementTy);
4615 llvm::FoldingSetNodeID ID;
4616 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4617 ColumnExpr);
4618
4619 void *InsertPos = nullptr;
4621 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4622
4623 if (!Canon) {
4624 Canon = new (*this, alignof(DependentSizedMatrixType))
4625 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4626 ColumnExpr, AttrLoc);
4627#ifndef NDEBUG
4628 DependentSizedMatrixType *CanonCheck =
4629 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4630 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4631#endif
4632 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4633 Types.push_back(Canon);
4634 }
4635
4636 // Already have a canonical version of the matrix type
4637 //
4638 // If it exactly matches the requested type, use it directly.
4639 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4640 Canon->getRowExpr() == ColumnExpr)
4641 return QualType(Canon, 0);
4642
4643 // Use Canon as the canonical type for newly-built type.
4644 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4645 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4646 ColumnExpr, AttrLoc);
4647 Types.push_back(New);
4648 return QualType(New, 0);
4649}
4650
4652 Expr *AddrSpaceExpr,
4653 SourceLocation AttrLoc) const {
4654 assert(AddrSpaceExpr->isInstantiationDependent());
4655
4656 QualType canonPointeeType = getCanonicalType(PointeeType);
4657
4658 void *insertPos = nullptr;
4659 llvm::FoldingSetNodeID ID;
4660 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4661 AddrSpaceExpr);
4662
4663 DependentAddressSpaceType *canonTy =
4664 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4665
4666 if (!canonTy) {
4667 canonTy = new (*this, alignof(DependentAddressSpaceType))
4668 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4669 AttrLoc);
4670 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4671 Types.push_back(canonTy);
4672 }
4673
4674 if (canonPointeeType == PointeeType &&
4675 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4676 return QualType(canonTy, 0);
4677
4678 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4679 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4680 AddrSpaceExpr, AttrLoc);
4681 Types.push_back(sugaredType);
4682 return QualType(sugaredType, 0);
4683}
4684
4685/// Determine whether \p T is canonical as the result type of a function.
4687 return T.isCanonical() &&
4688 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4689 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4690}
4691
4692/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4695 const FunctionType::ExtInfo &Info) const {
4696 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4697 // functionality creates a function without a prototype regardless of
4698 // language mode (so it makes them even in C++). Once the rewriter has been
4699 // fixed, this assertion can be enabled again.
4700 //assert(!LangOpts.requiresStrictPrototypes() &&
4701 // "strict prototypes are disabled");
4702
4703 // Unique functions, to guarantee there is only one function of a particular
4704 // structure.
4705 llvm::FoldingSetNodeID ID;
4706 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4707
4708 void *InsertPos = nullptr;
4709 if (FunctionNoProtoType *FT =
4710 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4711 return QualType(FT, 0);
4712
4713 QualType Canonical;
4714 if (!isCanonicalResultType(ResultTy)) {
4715 Canonical =
4717
4718 // Get the new insert position for the node we care about.
4719 FunctionNoProtoType *NewIP =
4720 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4721 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4722 }
4723
4724 auto *New = new (*this, alignof(FunctionNoProtoType))
4725 FunctionNoProtoType(ResultTy, Canonical, Info);
4726 Types.push_back(New);
4727 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4728 return QualType(New, 0);
4729}
4730
4733 CanQualType CanResultType = getCanonicalType(ResultType);
4734
4735 // Canonical result types do not have ARC lifetime qualifiers.
4736 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4737 Qualifiers Qs = CanResultType.getQualifiers();
4738 Qs.removeObjCLifetime();
4740 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4741 }
4742
4743 return CanResultType;
4744}
4745
4747 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4748 if (ESI.Type == EST_None)
4749 return true;
4750 if (!NoexceptInType)
4751 return false;
4752
4753 // C++17 onwards: exception specification is part of the type, as a simple
4754 // boolean "can this function type throw".
4755 if (ESI.Type == EST_BasicNoexcept)
4756 return true;
4757
4758 // A noexcept(expr) specification is (possibly) canonical if expr is
4759 // value-dependent.
4760 if (ESI.Type == EST_DependentNoexcept)
4761 return true;
4762
4763 // A dynamic exception specification is canonical if it only contains pack
4764 // expansions (so we can't tell whether it's non-throwing) and all its
4765 // contained types are canonical.
4766 if (ESI.Type == EST_Dynamic) {
4767 bool AnyPackExpansions = false;
4768 for (QualType ET : ESI.Exceptions) {
4769 if (!ET.isCanonical())
4770 return false;
4771 if (ET->getAs<PackExpansionType>())
4772 AnyPackExpansions = true;
4773 }
4774 return AnyPackExpansions;
4775 }
4776
4777 return false;
4778}
4779
4780QualType ASTContext::getFunctionTypeInternal(
4781 QualType ResultTy, ArrayRef<QualType> ArgArray,
4782 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4783 size_t NumArgs = ArgArray.size();
4784
4785 // Unique functions, to guarantee there is only one function of a particular
4786 // structure.
4787 llvm::FoldingSetNodeID ID;
4788 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4789 *this, true);
4790
4791 QualType Canonical;
4792 bool Unique = false;
4793
4794 void *InsertPos = nullptr;
4795 if (FunctionProtoType *FPT =
4796 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4797 QualType Existing = QualType(FPT, 0);
4798
4799 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4800 // it so long as our exception specification doesn't contain a dependent
4801 // noexcept expression, or we're just looking for a canonical type.
4802 // Otherwise, we're going to need to create a type
4803 // sugar node to hold the concrete expression.
4804 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4805 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4806 return Existing;
4807
4808 // We need a new type sugar node for this one, to hold the new noexcept
4809 // expression. We do no canonicalization here, but that's OK since we don't
4810 // expect to see the same noexcept expression much more than once.
4811 Canonical = getCanonicalType(Existing);
4812 Unique = true;
4813 }
4814
4815 bool NoexceptInType = getLangOpts().CPlusPlus17;
4816 bool IsCanonicalExceptionSpec =
4818
4819 // Determine whether the type being created is already canonical or not.
4820 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4821 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4822 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4823 if (!ArgArray[i].isCanonicalAsParam())
4824 isCanonical = false;
4825
4826 if (OnlyWantCanonical)
4827 assert(isCanonical &&
4828 "given non-canonical parameters constructing canonical type");
4829
4830 // If this type isn't canonical, get the canonical version of it if we don't
4831 // already have it. The exception spec is only partially part of the
4832 // canonical type, and only in C++17 onwards.
4833 if (!isCanonical && Canonical.isNull()) {
4834 SmallVector<QualType, 16> CanonicalArgs;
4835 CanonicalArgs.reserve(NumArgs);
4836 for (unsigned i = 0; i != NumArgs; ++i)
4837 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4838
4839 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4840 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4841 CanonicalEPI.HasTrailingReturn = false;
4842
4843 if (IsCanonicalExceptionSpec) {
4844 // Exception spec is already OK.
4845 } else if (NoexceptInType) {
4846 switch (EPI.ExceptionSpec.Type) {
4848 // We don't know yet. It shouldn't matter what we pick here; no-one
4849 // should ever look at this.
4850 [[fallthrough]];
4851 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4852 CanonicalEPI.ExceptionSpec.Type = EST_None;
4853 break;
4854
4855 // A dynamic exception specification is almost always "not noexcept",
4856 // with the exception that a pack expansion might expand to no types.
4857 case EST_Dynamic: {
4858 bool AnyPacks = false;
4859 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4860 if (ET->getAs<PackExpansionType>())
4861 AnyPacks = true;
4862 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4863 }
4864 if (!AnyPacks)
4865 CanonicalEPI.ExceptionSpec.Type = EST_None;
4866 else {
4867 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4868 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4869 }
4870 break;
4871 }
4872
4873 case EST_DynamicNone:
4874 case EST_BasicNoexcept:
4875 case EST_NoexceptTrue:
4876 case EST_NoThrow:
4877 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4878 break;
4879
4881 llvm_unreachable("dependent noexcept is already canonical");
4882 }
4883 } else {
4885 }
4886
4887 // Adjust the canonical function result type.
4888 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4889 Canonical =
4890 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4891
4892 // Get the new insert position for the node we care about.
4893 FunctionProtoType *NewIP =
4894 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4895 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4896 }
4897
4898 // Compute the needed size to hold this FunctionProtoType and the
4899 // various trailing objects.
4900 auto ESH = FunctionProtoType::getExceptionSpecSize(
4901 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4902 size_t Size = FunctionProtoType::totalSizeToAlloc<
4908 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
4909 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4910 EPI.ExtParameterInfos ? NumArgs : 0,
4912 EPI.FunctionEffects.conditions().size());
4913
4914 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
4916 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4917 Types.push_back(FTP);
4918 if (!Unique)
4919 FunctionProtoTypes.InsertNode(FTP, InsertPos);
4920 if (!EPI.FunctionEffects.empty())
4921 AnyFunctionEffects = true;
4922 return QualType(FTP, 0);
4923}
4924
4925QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4926 llvm::FoldingSetNodeID ID;
4927 PipeType::Profile(ID, T, ReadOnly);
4928
4929 void *InsertPos = nullptr;
4930 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4931 return QualType(PT, 0);
4932
4933 // If the pipe element type isn't canonical, this won't be a canonical type
4934 // either, so fill in the canonical type field.
4935 QualType Canonical;
4936 if (!T.isCanonical()) {
4937 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4938
4939 // Get the new insert position for the node we care about.
4940 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4941 assert(!NewIP && "Shouldn't be in the map!");
4942 (void)NewIP;
4943 }
4944 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
4945 Types.push_back(New);
4946 PipeTypes.InsertNode(New, InsertPos);
4947 return QualType(New, 0);
4948}
4949
4951 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4952 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4953 : Ty;
4954}
4955
4957 return getPipeType(T, true);
4958}
4959
4961 return getPipeType(T, false);
4962}
4963
4964QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
4965 llvm::FoldingSetNodeID ID;
4966 BitIntType::Profile(ID, IsUnsigned, NumBits);
4967
4968 void *InsertPos = nullptr;
4969 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4970 return QualType(EIT, 0);
4971
4972 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
4973 BitIntTypes.InsertNode(New, InsertPos);
4974 Types.push_back(New);
4975 return QualType(New, 0);
4976}
4977
4979 Expr *NumBitsExpr) const {
4980 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4981 llvm::FoldingSetNodeID ID;
4982 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4983
4984 void *InsertPos = nullptr;
4985 if (DependentBitIntType *Existing =
4986 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4987 return QualType(Existing, 0);
4988
4989 auto *New = new (*this, alignof(DependentBitIntType))
4990 DependentBitIntType(IsUnsigned, NumBitsExpr);
4991 DependentBitIntTypes.InsertNode(New, InsertPos);
4992
4993 Types.push_back(New);
4994 return QualType(New, 0);
4995}
4996
4997#ifndef NDEBUG
4999 if (!isa<CXXRecordDecl>(D)) return false;
5000 const auto *RD = cast<CXXRecordDecl>(D);
5001 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
5002 return true;
5003 if (RD->getDescribedClassTemplate() &&
5004 !isa<ClassTemplateSpecializationDecl>(RD))
5005 return true;
5006 return false;
5007}
5008#endif
5009
5010/// getInjectedClassNameType - Return the unique reference to the
5011/// injected class name type for the specified templated declaration.
5013 QualType TST) const {
5015 if (Decl->TypeForDecl) {
5016 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
5017 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
5018 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
5019 Decl->TypeForDecl = PrevDecl->TypeForDecl;
5020 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
5021 } else {
5022 Type *newType = new (*this, alignof(InjectedClassNameType))
5024 Decl->TypeForDecl = newType;
5025 Types.push_back(newType);
5026 }
5027 return QualType(Decl->TypeForDecl, 0);
5028}
5029
5030/// getTypeDeclType - Return the unique reference to the type for the
5031/// specified type declaration.
5032QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
5033 assert(Decl && "Passed null for Decl param");
5034 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
5035
5036 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5037 return getTypedefType(Typedef);
5038
5039 assert(!isa<TemplateTypeParmDecl>(Decl) &&
5040 "Template type parameter types are always available.");
5041
5042 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
5043 assert(Record->isFirstDecl() && "struct/union has previous declaration");
5045 return getRecordType(Record);
5046 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
5047 assert(Enum->isFirstDecl() && "enum has previous declaration");
5048 return getEnumType(Enum);
5049 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
5050 return getUnresolvedUsingType(Using);
5051 } else
5052 llvm_unreachable("TypeDecl without a type?");
5053
5054 return QualType(Decl->TypeForDecl, 0);
5055}
5056
5057/// getTypedefType - Return the unique reference to the type for the
5058/// specified typedef name decl.
5060 QualType Underlying) const {
5061 if (!Decl->TypeForDecl) {
5062 if (Underlying.isNull())
5063 Underlying = Decl->getUnderlyingType();
5064 auto *NewType = new (*this, alignof(TypedefType)) TypedefType(
5065 Type::Typedef, Decl, QualType(), getCanonicalType(Underlying));
5066 Decl->TypeForDecl = NewType;
5067 Types.push_back(NewType);
5068 return QualType(NewType, 0);
5069 }
5070 if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying)
5071 return QualType(Decl->TypeForDecl, 0);
5072 assert(hasSameType(Decl->getUnderlyingType(), Underlying));
5073
5074 llvm::FoldingSetNodeID ID;
5075 TypedefType::Profile(ID, Decl, Underlying);
5076
5077 void *InsertPos = nullptr;
5078 if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5079 assert(!T->typeMatchesDecl() &&
5080 "non-divergent case should be handled with TypeDecl");
5081 return QualType(T, 0);
5082 }
5083
5084 void *Mem = Allocate(TypedefType::totalSizeToAlloc<QualType>(true),
5085 alignof(TypedefType));
5086 auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying,
5087 getCanonicalType(Underlying));
5088 TypedefTypes.InsertNode(NewType, InsertPos);
5089 Types.push_back(NewType);
5090 return QualType(NewType, 0);
5091}
5092
5094 QualType Underlying) const {
5095 llvm::FoldingSetNodeID ID;
5096 UsingType::Profile(ID, Found, Underlying);
5097
5098 void *InsertPos = nullptr;
5099 if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5100 return QualType(T, 0);
5101
5102 const Type *TypeForDecl =
5103 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl();
5104
5105 assert(!Underlying.hasLocalQualifiers());
5106 QualType Canon = Underlying->getCanonicalTypeInternal();
5107 assert(TypeForDecl->getCanonicalTypeInternal() == Canon);
5108
5109 if (Underlying.getTypePtr() == TypeForDecl)
5110 Underlying = QualType();
5111 void *Mem =
5112 Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()),
5113 alignof(UsingType));
5114 UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon);
5115 Types.push_back(NewType);
5116 UsingTypes.InsertNode(NewType, InsertPos);
5117 return QualType(NewType, 0);
5118}
5119
5121 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
5122
5123 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
5124 if (PrevDecl->TypeForDecl)
5125 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
5126
5127 auto *newType = new (*this, alignof(RecordType)) RecordType(Decl);
5128 Decl->TypeForDecl = newType;
5129 Types.push_back(newType);
5130 return QualType(newType, 0);
5131}
5132
5134 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
5135
5136 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
5137 if (PrevDecl->TypeForDecl)
5138 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
5139
5140 auto *newType = new (*this, alignof(EnumType)) EnumType(Decl);
5141 Decl->TypeForDecl = newType;
5142 Types.push_back(newType);
5143 return QualType(newType, 0);
5144}
5145
5147 const UnresolvedUsingTypenameDecl *Decl) const {
5148 if (Decl->TypeForDecl)
5149 return QualType(Decl->TypeForDecl, 0);
5150
5151 if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
5153 if (CanonicalDecl->TypeForDecl)
5154 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
5155
5156 Type *newType =
5157 new (*this, alignof(UnresolvedUsingType)) UnresolvedUsingType(Decl);
5158 Decl->TypeForDecl = newType;
5159 Types.push_back(newType);
5160 return QualType(newType, 0);
5161}
5162
5164 QualType modifiedType,
5165 QualType equivalentType) const {
5166 llvm::FoldingSetNodeID id;
5167 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
5168
5169 void *insertPos = nullptr;
5170 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5171 if (type) return QualType(type, 0);
5172
5173 QualType canon = getCanonicalType(equivalentType);
5174 type = new (*this, alignof(AttributedType))
5175 AttributedType(canon, attrKind, modifiedType, equivalentType);
5176
5177 Types.push_back(type);
5178 AttributedTypes.InsertNode(type, insertPos);
5179
5180 return QualType(type, 0);
5181}
5182
5183QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5184 QualType Wrapped) {
5185 llvm::FoldingSetNodeID ID;
5186 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5187
5188 void *InsertPos = nullptr;
5190 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5191 if (Ty)
5192 return QualType(Ty, 0);
5193
5194 QualType Canon = getCanonicalType(Wrapped);
5195 Ty = new (*this, alignof(BTFTagAttributedType))
5196 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5197
5198 Types.push_back(Ty);
5199 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5200
5201 return QualType(Ty, 0);
5202}
5203
5204/// Retrieve a substitution-result type.
5206 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
5207 std::optional<unsigned> PackIndex) const {
5208 llvm::FoldingSetNodeID ID;
5209 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5210 PackIndex);
5211 void *InsertPos = nullptr;
5212 SubstTemplateTypeParmType *SubstParm =
5213 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5214
5215 if (!SubstParm) {
5216 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5217 !Replacement.isCanonical()),
5218 alignof(SubstTemplateTypeParmType));
5219 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5220 Index, PackIndex);
5221 Types.push_back(SubstParm);
5222 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5223 }
5224
5225 return QualType(SubstParm, 0);
5226}
5227
5228/// Retrieve a
5231 unsigned Index, bool Final,
5232 const TemplateArgument &ArgPack) {
5233#ifndef NDEBUG
5234 for (const auto &P : ArgPack.pack_elements())
5235 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5236#endif
5237
5238 llvm::FoldingSetNodeID ID;
5239 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5240 ArgPack);
5241 void *InsertPos = nullptr;
5242 if (SubstTemplateTypeParmPackType *SubstParm =
5243 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5244 return QualType(SubstParm, 0);
5245
5246 QualType Canon;
5247 {
5248 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5249 if (!AssociatedDecl->isCanonicalDecl() ||
5250 !CanonArgPack.structurallyEquals(ArgPack)) {
5252 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5253 [[maybe_unused]] const auto *Nothing =
5254 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5255 assert(!Nothing);
5256 }
5257 }
5258
5259 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5260 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5261 ArgPack);
5262 Types.push_back(SubstParm);
5263 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5264 return QualType(SubstParm, 0);
5265}
5266
5267/// Retrieve the template type parameter type for a template
5268/// parameter or parameter pack with the given depth, index, and (optionally)
5269/// name.
5270QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5271 bool ParameterPack,
5272 TemplateTypeParmDecl *TTPDecl) const {
5273 llvm::FoldingSetNodeID ID;
5274 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5275 void *InsertPos = nullptr;
5276 TemplateTypeParmType *TypeParm
5277 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5278
5279 if (TypeParm)
5280 return QualType(TypeParm, 0);
5281
5282 if (TTPDecl) {
5283 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5284 TypeParm = new (*this, alignof(TemplateTypeParmType))
5285 TemplateTypeParmType(TTPDecl, Canon);
5286
5287 TemplateTypeParmType *TypeCheck
5288 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5289 assert(!TypeCheck && "Template type parameter canonical type broken");
5290 (void)TypeCheck;
5291 } else
5292 TypeParm = new (*this, alignof(TemplateTypeParmType))
5293 TemplateTypeParmType(Depth, Index, ParameterPack);
5294
5295 Types.push_back(TypeParm);
5296 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5297
5298 return QualType(TypeParm, 0);
5299}
5300
5303 SourceLocation NameLoc,
5304 const TemplateArgumentListInfo &Args,
5305 QualType Underlying) const {
5306 assert(!Name.getAsDependentTemplateName() &&
5307 "No dependent template names here!");
5308 QualType TST =
5309 getTemplateSpecializationType(Name, Args.arguments(), Underlying);
5310
5315 TL.setTemplateNameLoc(NameLoc);
5316 TL.setLAngleLoc(Args.getLAngleLoc());
5317 TL.setRAngleLoc(Args.getRAngleLoc());
5318 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5319 TL.setArgLocInfo(i, Args[i].getLocInfo());
5320 return DI;
5321}
5322
5326 QualType Underlying) const {
5327 assert(!Template.getAsDependentTemplateName() &&
5328 "No dependent template names here!");
5329
5331 ArgVec.reserve(Args.size());
5332 for (const TemplateArgumentLoc &Arg : Args)
5333 ArgVec.push_back(Arg.getArgument());
5334
5335 return getTemplateSpecializationType(Template, ArgVec, Underlying);
5336}
5337
5338#ifndef NDEBUG
5340 for (const TemplateArgument &Arg : Args)
5341 if (Arg.isPackExpansion())
5342 return true;
5343
5344 return true;
5345}
5346#endif
5347
5351 QualType Underlying) const {
5352 assert(!Template.getAsDependentTemplateName() &&
5353 "No dependent template names here!");
5354
5355 const auto *TD = Template.getAsTemplateDecl();
5356 bool IsTypeAlias = TD && TD->isTypeAlias();
5357 QualType CanonType;
5358 if (!Underlying.isNull())
5359 CanonType = getCanonicalType(Underlying);
5360 else {
5361 // We can get here with an alias template when the specialization contains
5362 // a pack expansion that does not match up with a parameter pack.
5363 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
5364 "Caller must compute aliased type");
5365 IsTypeAlias = false;
5366 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
5367 }
5368
5369 // Allocate the (non-canonical) template specialization type, but don't
5370 // try to unique it: these types typically have location information that
5371 // we don't unique and don't want to lose.
5372 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5373 sizeof(TemplateArgument) * Args.size() +
5374 (IsTypeAlias ? sizeof(QualType) : 0),
5376 auto *Spec
5377 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
5378 IsTypeAlias ? Underlying : QualType());
5379
5380 Types.push_back(Spec);
5381 return QualType(Spec, 0);
5382}
5383
5385 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
5386 assert(!Template.getAsDependentTemplateName() &&
5387 "No dependent template names here!");
5388
5389 // Build the canonical template specialization type.
5390 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
5391 bool AnyNonCanonArgs = false;
5392 auto CanonArgs =
5393 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5394
5395 // Determine whether this canonical template specialization type already
5396 // exists.
5397 llvm::FoldingSetNodeID ID;
5398 TemplateSpecializationType::Profile(ID, CanonTemplate,
5399 CanonArgs, *this);
5400
5401 void *InsertPos = nullptr;
5403 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5404
5405 if (!Spec) {
5406 // Allocate a new canonical template specialization type.
5407 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
5408 sizeof(TemplateArgument) * CanonArgs.size()),
5410 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
5411 CanonArgs,
5412 QualType(), QualType());
5413 Types.push_back(Spec);
5414 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5415 }
5416
5417 assert(Spec->isDependentType() &&
5418 "Non-dependent template-id type must have a canonical type");
5419 return QualType(Spec, 0);
5420}
5421
5424 QualType NamedType,
5425 TagDecl *OwnedTagDecl) const {
5426 llvm::FoldingSetNodeID ID;
5427 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
5428
5429 void *InsertPos = nullptr;
5430 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5431 if (T)
5432 return QualType(T, 0);
5433
5434 QualType Canon = NamedType;
5435 if (!Canon.isCanonical()) {
5436 Canon = getCanonicalType(NamedType);
5437 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5438 assert(!CheckT && "Elaborated canonical type broken");
5439 (void)CheckT;
5440 }
5441
5442 void *Mem =
5443 Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
5444 alignof(ElaboratedType));
5445 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
5446
5447 Types.push_back(T);
5448 ElaboratedTypes.InsertNode(T, InsertPos);
5449 return QualType(T, 0);
5450}
5451
5454 llvm::FoldingSetNodeID ID;
5455 ParenType::Profile(ID, InnerType);
5456
5457 void *InsertPos = nullptr;
5458 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5459 if (T)
5460 return QualType(T, 0);
5461
5462 QualType Canon = InnerType;
5463 if (!Canon.isCanonical()) {
5464 Canon = getCanonicalType(InnerType);
5465 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5466 assert(!CheckT && "Paren canonical type broken");
5467 (void)CheckT;
5468 }
5469
5470 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
5471 Types.push_back(T);
5472 ParenTypes.InsertNode(T, InsertPos);
5473 return QualType(T, 0);
5474}
5475
5478 const IdentifierInfo *MacroII) const {
5479 QualType Canon = UnderlyingTy;
5480 if (!Canon.isCanonical())
5481 Canon = getCanonicalType(UnderlyingTy);
5482
5483 auto *newType = new (*this, alignof(MacroQualifiedType))
5484 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5485 Types.push_back(newType);
5486 return QualType(newType, 0);
5487}
5488
5491 const IdentifierInfo *Name,
5492 QualType Canon) const {
5493 if (Canon.isNull()) {
5495 if (CanonNNS != NNS)
5496 Canon = getDependentNameType(Keyword, CanonNNS, Name);
5497 }
5498
5499 llvm::FoldingSetNodeID ID;
5500 DependentNameType::Profile(ID, Keyword, NNS, Name);
5501
5502 void *InsertPos = nullptr;
5504 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5505 if (T)
5506 return QualType(T, 0);
5507
5508 T = new (*this, alignof(DependentNameType))
5509 DependentNameType(Keyword, NNS, Name, Canon);
5510 Types.push_back(T);
5511 DependentNameTypes.InsertNode(T, InsertPos);
5512 return QualType(T, 0);
5513}
5514
5517 const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const {
5518 // TODO: avoid this copy
5520 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5521 ArgCopy.push_back(Args[I].getArgument());
5522 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5523}
5524
5527 ElaboratedTypeKeyword Keyword,
5529 const IdentifierInfo *Name,
5530 ArrayRef<TemplateArgument> Args) const {
5531 assert((!NNS || NNS->isDependent()) &&
5532 "nested-name-specifier must be dependent");
5533
5534 llvm::FoldingSetNodeID ID;
5535 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5536 Name, Args);
5537
5538 void *InsertPos = nullptr;
5540 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5541 if (T)
5542 return QualType(T, 0);
5543
5545
5546 ElaboratedTypeKeyword CanonKeyword = Keyword;
5547 if (Keyword == ElaboratedTypeKeyword::None)
5548 CanonKeyword = ElaboratedTypeKeyword::Typename;
5549
5550 bool AnyNonCanonArgs = false;
5551 auto CanonArgs =
5552 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5553
5554 QualType Canon;
5555 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5556 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5557 Name,
5558 CanonArgs);
5559
5560 // Find the insert position again.
5561 [[maybe_unused]] auto *Nothing =
5562 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5563 assert(!Nothing && "canonical type broken");
5564 }
5565
5566 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5567 sizeof(TemplateArgument) * Args.size()),
5569 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5570 Name, Args, Canon);
5571 Types.push_back(T);
5572 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5573 return QualType(T, 0);
5574}
5575
5577 TemplateArgument Arg;
5578 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5579 QualType ArgType = getTypeDeclType(TTP);
5580 if (TTP->isParameterPack())
5581 ArgType = getPackExpansionType(ArgType, std::nullopt);
5582
5583 Arg = TemplateArgument(ArgType);
5584 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5585 QualType T =
5586 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5587 // For class NTTPs, ensure we include the 'const' so the type matches that
5588 // of a real template argument.
5589 // FIXME: It would be more faithful to model this as something like an
5590 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5591 if (T->isRecordType())
5592 T.addConst();
5593 Expr *E = new (*this) DeclRefExpr(
5594 *this, NTTP, /*RefersToEnclosingVariableOrCapture*/ false, T,
5595 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
5596
5597 if (NTTP->isParameterPack())
5598 E = new (*this)
5599 PackExpansionExpr(DependentTy, E, NTTP->getLocation(), std::nullopt);
5600 Arg = TemplateArgument(E);
5601 } else {
5602 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5604 nullptr, /*TemplateKeyword=*/false, TemplateName(TTP));
5605 if (TTP->isParameterPack())
5606 Arg = TemplateArgument(Name, std::optional<unsigned>());
5607 else
5608 Arg = TemplateArgument(Name);
5609 }
5610
5611 if (Param->isTemplateParameterPack())
5612 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
5613
5614 return Arg;
5615}
5616
5617void
5620 Args.reserve(Args.size() + Params->size());
5621
5622 for (NamedDecl *Param : *Params)
5623 Args.push_back(getInjectedTemplateArg(Param));
5624}
5625
5627 std::optional<unsigned> NumExpansions,
5628 bool ExpectPackInType) {
5629 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5630 "Pack expansions must expand one or more parameter packs");
5631
5632 llvm::FoldingSetNodeID ID;
5633 PackExpansionType::Profile(ID, Pattern, NumExpansions);
5634
5635 void *InsertPos = nullptr;
5636 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5637 if (T)
5638 return QualType(T, 0);
5639
5640 QualType Canon;
5641 if (!Pattern.isCanonical()) {
5642 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5643 /*ExpectPackInType=*/false);
5644
5645 // Find the insert position again, in case we inserted an element into
5646 // PackExpansionTypes and invalidated our insert position.
5647 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5648 }
5649
5650 T = new (*this, alignof(PackExpansionType))
5651 PackExpansionType(Pattern, Canon, NumExpansions);
5652 Types.push_back(T);
5653 PackExpansionTypes.InsertNode(T, InsertPos);
5654 return QualType(T, 0);
5655}
5656
5657/// CmpProtocolNames - Comparison predicate for sorting protocols
5658/// alphabetically.
5659static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5660 ObjCProtocolDecl *const *RHS) {
5661 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5662}
5663
5665 if (Protocols.empty()) return true;
5666
5667 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5668 return false;
5669
5670 for (unsigned i = 1; i != Protocols.size(); ++i)
5671 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5672 Protocols[i]->getCanonicalDecl() != Protocols[i])
5673 return false;
5674 return true;
5675}
5676
5677static void
5679 // Sort protocols, keyed by name.
5680 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5681
5682 // Canonicalize.
5683 for (ObjCProtocolDecl *&P : Protocols)
5684 P = P->getCanonicalDecl();
5685
5686 // Remove duplicates.
5687 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5688 Protocols.erase(ProtocolsEnd, Protocols.end());
5689}
5690
5692 ObjCProtocolDecl * const *Protocols,
5693 unsigned NumProtocols) const {
5694 return getObjCObjectType(BaseType, {},
5695 llvm::ArrayRef(Protocols, NumProtocols),
5696 /*isKindOf=*/false);
5697}
5698
5700 QualType baseType,
5701 ArrayRef<QualType> typeArgs,
5703 bool isKindOf) const {
5704 // If the base type is an interface and there aren't any protocols or
5705 // type arguments to add, then the interface type will do just fine.
5706 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5707 isa<ObjCInterfaceType>(baseType))
5708 return baseType;
5709
5710 // Look in the folding set for an existing type.
5711 llvm::FoldingSetNodeID ID;
5712 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5713 void *InsertPos = nullptr;
5714 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5715 return QualType(QT, 0);
5716
5717 // Determine the type arguments to be used for canonicalization,
5718 // which may be explicitly specified here or written on the base
5719 // type.
5720 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5721 if (effectiveTypeArgs.empty()) {
5722 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5723 effectiveTypeArgs = baseObject->getTypeArgs();
5724 }
5725
5726 // Build the canonical type, which has the canonical base type and a
5727 // sorted-and-uniqued list of protocols and the type arguments
5728 // canonicalized.
5729 QualType canonical;
5730 bool typeArgsAreCanonical = llvm::all_of(
5731 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5732 bool protocolsSorted = areSortedAndUniqued(protocols);
5733 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5734 // Determine the canonical type arguments.
5735 ArrayRef<QualType> canonTypeArgs;
5736 SmallVector<QualType, 4> canonTypeArgsVec;
5737 if (!typeArgsAreCanonical) {
5738 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5739 for (auto typeArg : effectiveTypeArgs)
5740 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5741 canonTypeArgs = canonTypeArgsVec;
5742 } else {
5743 canonTypeArgs = effectiveTypeArgs;
5744 }
5745
5746 ArrayRef<ObjCProtocolDecl *> canonProtocols;
5747 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5748 if (!protocolsSorted) {
5749 canonProtocolsVec.append(protocols.begin(), protocols.end());
5750 SortAndUniqueProtocols(canonProtocolsVec);
5751 canonProtocols = canonProtocolsVec;
5752 } else {
5753 canonProtocols = protocols;
5754 }
5755
5756 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5757 canonProtocols, isKindOf);
5758
5759 // Regenerate InsertPos.
5760 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5761 }
5762
5763 unsigned size = sizeof(ObjCObjectTypeImpl);
5764 size += typeArgs.size() * sizeof(QualType);
5765 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5766 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
5767 auto *T =
5768 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5769 isKindOf);
5770
5771 Types.push_back(T);
5772 ObjCObjectTypes.InsertNode(T, InsertPos);
5773 return QualType(T, 0);
5774}
5775
5776/// Apply Objective-C protocol qualifiers to the given type.
5777/// If this is for the canonical type of a type parameter, we can apply
5778/// protocol qualifiers on the ObjCObjectPointerType.
5781 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5782 bool allowOnPointerType) const {
5783 hasError = false;
5784
5785 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5786 return getObjCTypeParamType(objT->getDecl(), protocols);
5787 }
5788
5789 // Apply protocol qualifiers to ObjCObjectPointerType.
5790 if (allowOnPointerType) {
5791 if (const auto *objPtr =
5792 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5793 const ObjCObjectType *objT = objPtr->getObjectType();
5794 // Merge protocol lists and construct ObjCObjectType.
5796 protocolsVec.append(objT->qual_begin(),
5797 objT->qual_end());
5798 protocolsVec.append(protocols.begin(), protocols.end());
5799 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5801 objT->getBaseType(),
5802 objT->getTypeArgsAsWritten(),
5803 protocols,
5804 objT->isKindOfTypeAsWritten());
5806 }
5807 }
5808
5809 // Apply protocol qualifiers to ObjCObjectType.
5810 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5811 // FIXME: Check for protocols to which the class type is already
5812 // known to conform.
5813
5814 return getObjCObjectType(objT->getBaseType(),
5815 objT->getTypeArgsAsWritten(),
5816 protocols,
5817 objT->isKindOfTypeAsWritten());
5818 }
5819
5820 // If the canonical type is ObjCObjectType, ...
5821 if (type->isObjCObjectType()) {
5822 // Silently overwrite any existing protocol qualifiers.
5823 // TODO: determine whether that's the right thing to do.
5824
5825 // FIXME: Check for protocols to which the class type is already
5826 // known to conform.
5827 return getObjCObjectType(type, {}, protocols, false);
5828 }
5829
5830 // id<protocol-list>
5831 if (type->isObjCIdType()) {
5832 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5833 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5834 objPtr->isKindOfType());
5836 }
5837
5838 // Class<protocol-list>
5839 if (type->isObjCClassType()) {
5840 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5841 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5842 objPtr->isKindOfType());
5844 }
5845
5846 hasError = true;
5847 return type;
5848}
5849
5852 ArrayRef<ObjCProtocolDecl *> protocols) const {
5853 // Look in the folding set for an existing type.
5854 llvm::FoldingSetNodeID ID;
5855 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5856 void *InsertPos = nullptr;
5857 if (ObjCTypeParamType *TypeParam =
5858 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5859 return QualType(TypeParam, 0);
5860
5861 // We canonicalize to the underlying type.
5862 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5863 if (!protocols.empty()) {
5864 // Apply the protocol qualifers.
5865 bool hasError;
5867 Canonical, protocols, hasError, true /*allowOnPointerType*/));
5868 assert(!hasError && "Error when apply protocol qualifier to bound type");
5869 }
5870
5871 unsigned size = sizeof(ObjCTypeParamType);
5872 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5873 void *mem = Allocate(size, alignof(ObjCTypeParamType));
5874 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5875
5876 Types.push_back(newType);
5877 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5878 return QualType(newType, 0);
5879}
5880
5882 ObjCTypeParamDecl *New) const {
5884 // Update TypeForDecl after updating TypeSourceInfo.
5885 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5887 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5888 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5889 New->setTypeForDecl(UpdatedTy.getTypePtr());
5890}
5891
5892/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5893/// protocol list adopt all protocols in QT's qualified-id protocol
5894/// list.
5896 ObjCInterfaceDecl *IC) {
5897 if (!QT->isObjCQualifiedIdType())
5898 return false;
5899
5900 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5901 // If both the right and left sides have qualifiers.
5902 for (auto *Proto : OPT->quals()) {
5903 if (!IC->ClassImplementsProtocol(Proto, false))
5904 return false;
5905 }
5906 return true;
5907 }
5908 return false;
5909}
5910
5911/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5912/// QT's qualified-id protocol list adopt all protocols in IDecl's list
5913/// of protocols.
5915 ObjCInterfaceDecl *IDecl) {
5916 if (!QT->isObjCQualifiedIdType())
5917 return false;
5918 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5919 if (!OPT)
5920 return false;
5921 if (!IDecl->hasDefinition())
5922 return false;
5924 CollectInheritedProtocols(IDecl, InheritedProtocols);
5925 if (InheritedProtocols.empty())
5926 return false;
5927 // Check that if every protocol in list of id<plist> conforms to a protocol
5928 // of IDecl's, then bridge casting is ok.
5929 bool Conforms = false;
5930 for (auto *Proto : OPT->quals()) {
5931 Conforms = false;
5932 for (auto *PI : InheritedProtocols) {
5933 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5934 Conforms = true;
5935 break;
5936 }
5937 }
5938 if (!Conforms)
5939 break;
5940 }
5941 if (Conforms)
5942 return true;
5943
5944 for (auto *PI : InheritedProtocols) {
5945 // If both the right and left sides have qualifiers.
5946 bool Adopts = false;
5947 for (auto *Proto : OPT->quals()) {
5948 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5949 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5950 break;
5951 }
5952 if (!Adopts)
5953 return false;
5954 }
5955 return true;
5956}
5957
5958/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5959/// the given object type.
5961 llvm::FoldingSetNodeID ID;
5962 ObjCObjectPointerType::Profile(ID, ObjectT);
5963
5964 void *InsertPos = nullptr;
5965 if (ObjCObjectPointerType *QT =
5966 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5967 return QualType(QT, 0);
5968
5969 // Find the canonical object type.
5970 QualType Canonical;
5971 if (!ObjectT.isCanonical()) {
5972 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5973
5974 // Regenerate InsertPos.
5975 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5976 }
5977
5978 // No match.
5979 void *Mem =
5981 auto *QType =
5982 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5983
5984 Types.push_back(QType);
5985 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5986 return QualType(QType, 0);
5987}
5988
5989/// getObjCInterfaceType - Return the unique reference to the type for the
5990/// specified ObjC interface decl. The list of protocols is optional.
5992 ObjCInterfaceDecl *PrevDecl) const {
5993 if (Decl->TypeForDecl)
5994 return QualType(Decl->TypeForDecl, 0);
5995
5996 if (PrevDecl) {
5997 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5998 Decl->TypeForDecl = PrevDecl->TypeForDecl;
5999 return QualType(PrevDecl->TypeForDecl, 0);
6000 }
6001
6002 // Prefer the definition, if there is one.
6003 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6004 Decl = Def;
6005
6006 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6007 auto *T = new (Mem) ObjCInterfaceType(Decl);
6008 Decl->TypeForDecl = T;
6009 Types.push_back(T);
6010 return QualType(T, 0);
6011}
6012
6013/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6014/// TypeOfExprType AST's (since expression's are never shared). For example,
6015/// multiple declarations that refer to "typeof(x)" all contain different
6016/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6017/// on canonical type's (which are always unique).
6019 TypeOfExprType *toe;
6020 if (tofExpr->isTypeDependent()) {
6021 llvm::FoldingSetNodeID ID;
6022 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6023 Kind == TypeOfKind::Unqualified);
6024
6025 void *InsertPos = nullptr;
6027 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6028 if (Canon) {
6029 // We already have a "canonical" version of an identical, dependent
6030 // typeof(expr) type. Use that as our canonical type.
6031 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6032 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6033 } else {
6034 // Build a new, canonical typeof(expr) type.
6035 Canon = new (*this, alignof(DependentTypeOfExprType))
6036 DependentTypeOfExprType(*this, tofExpr, Kind);
6037 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6038 toe = Canon;
6039 }
6040 } else {
6041 QualType Canonical = getCanonicalType(tofExpr->getType());
6042 toe = new (*this, alignof(TypeOfExprType))
6043 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6044 }
6045 Types.push_back(toe);
6046 return QualType(toe, 0);
6047}
6048
6049/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6050/// TypeOfType nodes. The only motivation to unique these nodes would be
6051/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6052/// an issue. This doesn't affect the type checker, since it operates
6053/// on canonical types (which are always unique).
6055 QualType Canonical = getCanonicalType(tofType);
6056 auto *tot = new (*this, alignof(TypeOfType))
6057 TypeOfType(*this, tofType, Canonical, Kind);
6058 Types.push_back(tot);
6059 return QualType(tot, 0);
6060}
6061
6062/// getReferenceQualifiedType - Given an expr, will return the type for
6063/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6064/// and class member access into account.
6066 // C++11 [dcl.type.simple]p4:
6067 // [...]
6068 QualType T = E->getType();
6069 switch (E->getValueKind()) {
6070 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6071 // type of e;
6072 case VK_XValue:
6073 return getRValueReferenceType(T);
6074 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6075 // type of e;
6076 case VK_LValue:
6077 return getLValueReferenceType(T);
6078 // - otherwise, decltype(e) is the type of e.
6079 case VK_PRValue:
6080 return T;
6081 }
6082 llvm_unreachable("Unknown value kind");
6083}
6084
6085/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6086/// nodes. This would never be helpful, since each such type has its own
6087/// expression, and would not give a significant memory saving, since there
6088/// is an Expr tree under each such type.
6090 DecltypeType *dt;
6091
6092 // C++11 [temp.type]p2:
6093 // If an expression e involves a template parameter, decltype(e) denotes a
6094 // unique dependent type. Two such decltype-specifiers refer to the same
6095 // type only if their expressions are equivalent (14.5.6.1).
6096 if (e->isInstantiationDependent()) {
6097 llvm::FoldingSetNodeID ID;
6098 DependentDecltypeType::Profile(ID, *this, e);
6099
6100 void *InsertPos = nullptr;
6102 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
6103 if (!Canon) {
6104 // Build a new, canonical decltype(expr) type.
6105 Canon = new (*this, alignof(DependentDecltypeType))
6107 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
6108 }
6109 dt = new (*this, alignof(DecltypeType))
6110 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
6111 } else {
6112 dt = new (*this, alignof(DecltypeType))
6113 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
6114 }
6115 Types.push_back(dt);
6116 return QualType(dt, 0);
6117}
6118
6120 bool FullySubstituted,
6121 ArrayRef<QualType> Expansions,
6122 int Index) const {
6123 QualType Canonical;
6124 if (FullySubstituted && Index != -1) {
6125 Canonical = getCanonicalType(Expansions[Index]);
6126 } else {
6127 llvm::FoldingSetNodeID ID;
6128 PackIndexingType::Profile(ID, *this, Pattern, IndexExpr);
6129 void *InsertPos = nullptr;
6130 PackIndexingType *Canon =
6131 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6132 if (!Canon) {
6133 void *Mem = Allocate(
6134 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6136 Canon = new (Mem)
6137 PackIndexingType(*this, QualType(), Pattern, IndexExpr, Expansions);
6138 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6139 }
6140 Canonical = QualType(Canon, 0);
6141 }
6142
6143 void *Mem =
6144 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6146 auto *T = new (Mem)
6147 PackIndexingType(*this, Canonical, Pattern, IndexExpr, Expansions);
6148 Types.push_back(T);
6149 return QualType(T, 0);
6150}
6151
6152/// getUnaryTransformationType - We don't unique these, since the memory
6153/// savings are minimal and these are rare.
6155 QualType UnderlyingType,
6157 const {
6158 UnaryTransformType *ut = nullptr;
6159
6160 if (BaseType->isDependentType()) {
6161 // Look in the folding set for an existing type.
6162 llvm::FoldingSetNodeID ID;
6164
6165 void *InsertPos = nullptr;
6167 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6168
6169 if (!Canon) {
6170 // Build a new, canonical __underlying_type(type) type.
6171 Canon = new (*this, alignof(DependentUnaryTransformType))
6172 DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind);
6173 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
6174 }
6175 ut = new (*this, alignof(UnaryTransformType))
6176 UnaryTransformType(BaseType, QualType(), Kind, QualType(Canon, 0));
6177 } else {
6178 QualType CanonType = getCanonicalType(UnderlyingType);
6179 ut = new (*this, alignof(UnaryTransformType))
6180 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6181 }
6182 Types.push_back(ut);
6183 return QualType(ut, 0);
6184}
6185
6186QualType ASTContext::getAutoTypeInternal(
6187 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6188 bool IsPack, ConceptDecl *TypeConstraintConcept,
6189 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6190 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6191 !TypeConstraintConcept && !IsDependent)
6192 return getAutoDeductType();
6193
6194 // Look in the folding set for an existing type.
6195 void *InsertPos = nullptr;
6196 llvm::FoldingSetNodeID ID;
6197 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
6198 TypeConstraintConcept, TypeConstraintArgs);
6199 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
6200 return QualType(AT, 0);
6201
6202 QualType Canon;
6203 if (!IsCanon) {
6204 if (!DeducedType.isNull()) {
6205 Canon = DeducedType.getCanonicalType();
6206 } else if (TypeConstraintConcept) {
6207 bool AnyNonCanonArgs = false;
6208 ConceptDecl *CanonicalConcept = TypeConstraintConcept->getCanonicalDecl();
6209 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6210 *this, TypeConstraintArgs, AnyNonCanonArgs);
6211 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6212 Canon =
6213 getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6214 CanonicalConcept, CanonicalConceptArgs, true);
6215 // Find the insert position again.
6216 [[maybe_unused]] auto *Nothing =
6217 AutoTypes.FindNodeOrInsertPos(ID, InsertPos);
6218 assert(!Nothing && "canonical type broken");
6219 }
6220 }
6221 }
6222
6223 void *Mem = Allocate(sizeof(AutoType) +
6224 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6225 alignof(AutoType));
6226 auto *AT = new (Mem) AutoType(
6227 DeducedType, Keyword,
6228 (IsDependent ? TypeDependence::DependentInstantiation
6229 : TypeDependence::None) |
6230 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6231 Canon, TypeConstraintConcept, TypeConstraintArgs);
6232 Types.push_back(AT);
6233 AutoTypes.InsertNode(AT, InsertPos);
6234 return QualType(AT, 0);
6235}
6236
6237/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6238/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6239/// canonical deduced-but-dependent 'auto' type.
6242 bool IsDependent, bool IsPack,
6243 ConceptDecl *TypeConstraintConcept,
6244 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6245 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6246 assert((!IsDependent || DeducedType.isNull()) &&
6247 "A dependent auto should be undeduced");
6248 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6249 TypeConstraintConcept, TypeConstraintArgs);
6250}
6251
6253 QualType CanonT = T.getCanonicalType();
6254
6255 // Remove a type-constraint from a top-level auto or decltype(auto).
6256 if (auto *AT = CanonT->getAs<AutoType>()) {
6257 if (!AT->isConstrained())
6258 return T;
6259 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6260 AT->isDependentType(),
6261 AT->containsUnexpandedParameterPack()),
6262 T.getQualifiers());
6263 }
6264
6265 // FIXME: We only support constrained auto at the top level in the type of a
6266 // non-type template parameter at the moment. Once we lift that restriction,
6267 // we'll need to recursively build types containing auto here.
6268 assert(!CanonT->getContainedAutoType() ||
6269 !CanonT->getContainedAutoType()->isConstrained());
6270 return T;
6271}
6272
6273QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6274 TemplateName Template, QualType DeducedType, bool IsDependent,
6275 QualType Canon) const {
6276 // Look in the folding set for an existing type.
6277 void *InsertPos = nullptr;
6278 llvm::FoldingSetNodeID ID;
6280 IsDependent);
6282 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6283 return QualType(DTST, 0);
6284
6285 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6286 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent,
6287 Canon);
6288 llvm::FoldingSetNodeID TempID;
6289 DTST->Profile(TempID);
6290 assert(ID == TempID && "ID does not match");
6291 Types.push_back(DTST);
6292 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6293 return QualType(DTST, 0);
6294}
6295
6296/// Return the uniqued reference to the deduced template specialization type
6297/// which has been deduced to the given type, or to the canonical undeduced
6298/// such type, or the canonical deduced-but-dependent such type.
6300 TemplateName Template, QualType DeducedType, bool IsDependent) const {
6301 QualType Canon = DeducedType.isNull()
6302 ? getDeducedTemplateSpecializationTypeInternal(
6304 IsDependent, QualType())
6305 : DeducedType.getCanonicalType();
6306 return getDeducedTemplateSpecializationTypeInternal(Template, DeducedType,
6307 IsDependent, Canon);
6308}
6309
6310/// getAtomicType - Return the uniqued reference to the atomic type for
6311/// the given value type.
6313 // Unique pointers, to guarantee there is only one pointer of a particular
6314 // structure.
6315 llvm::FoldingSetNodeID ID;
6317
6318 void *InsertPos = nullptr;
6319 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6320 return QualType(AT, 0);
6321
6322 // If the atomic value type isn't canonical, this won't be a canonical type
6323 // either, so fill in the canonical type field.
6324 QualType Canonical;
6325 if (!T.isCanonical()) {
6326 Canonical = getAtomicType(getCanonicalType(T));
6327
6328 // Get the new insert position for the node we care about.
6329 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6330 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6331 }
6332 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6333 Types.push_back(New);
6334 AtomicTypes.InsertNode(New, InsertPos);
6335 return QualType(New, 0);
6336}
6337
6338/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6340 if (AutoDeductTy.isNull())
6341 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6343 TypeDependence::None, QualType(),
6344 /*concept*/ nullptr, /*args*/ {}),
6345 0);
6346 return AutoDeductTy;
6347}
6348
6349/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6353 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6354 return AutoRRefDeductTy;
6355}
6356
6357/// getTagDeclType - Return the unique reference to the type for the
6358/// specified TagDecl (struct/union/class/enum) decl.
6360 assert(Decl);
6361 // FIXME: What is the design on getTagDeclType when it requires casting
6362 // away const? mutable?
6363 return getTypeDeclType(const_cast<TagDecl*>(Decl));
6364}
6365
6366/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6367/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6368/// needs to agree with the definition in <stddef.h>.
6370 return getFromTargetType(Target->getSizeType());
6371}
6372
6373/// Return the unique signed counterpart of the integer type
6374/// corresponding to size_t.
6376 return getFromTargetType(Target->getSignedSizeType());
6377}
6378
6379/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6381 return getFromTargetType(Target->getIntMaxType());
6382}
6383
6384/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6386 return getFromTargetType(Target->getUIntMaxType());
6387}
6388
6389/// getSignedWCharType - Return the type of "signed wchar_t".
6390/// Used when in C++, as a GCC extension.
6392 // FIXME: derive from "Target" ?
6393 return WCharTy;
6394}
6395
6396/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6397/// Used when in C++, as a GCC extension.
6399 // FIXME: derive from "Target" ?
6400 return UnsignedIntTy;
6401}
6402
6404 return getFromTargetType(Target->getIntPtrType());
6405}
6406
6409}
6410
6411/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6412/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6414 return getFromTargetType(Target->getPtrDiffType(LangAS::Default));
6415}
6416
6417/// Return the unique unsigned counterpart of "ptrdiff_t"
6418/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6419/// in the definition of %tu format specifier.
6421 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6422}
6423
6424/// Return the unique type for "pid_t" defined in
6425/// <sys/types.h>. We need this to compute the correct type for vfork().
6427 return getFromTargetType(Target->getProcessIDType());
6428}
6429
6430//===----------------------------------------------------------------------===//
6431// Type Operators
6432//===----------------------------------------------------------------------===//
6433
6435 // Push qualifiers into arrays, and then discard any remaining
6436 // qualifiers.
6437 T = getCanonicalType(T);
6439 const Type *Ty = T.getTypePtr();
6441 if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) {
6443 } else if (isa<ArrayType>(Ty)) {
6445 } else if (isa<FunctionType>(Ty)) {
6446 Result = getPointerType(QualType(Ty, 0));
6447 } else {
6448 Result = QualType(Ty, 0);
6449 }
6450
6452}
6453
6455 Qualifiers &quals) const {
6456 SplitQualType splitType = type.getSplitUnqualifiedType();
6457
6458 // FIXME: getSplitUnqualifiedType() actually walks all the way to
6459 // the unqualified desugared type and then drops it on the floor.
6460 // We then have to strip that sugar back off with
6461 // getUnqualifiedDesugaredType(), which is silly.
6462 const auto *AT =
6463 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
6464
6465 // If we don't have an array, just use the results in splitType.
6466 if (!AT) {
6467 quals = splitType.Quals;
6468 return QualType(splitType.Ty, 0);
6469 }
6470
6471 // Otherwise, recurse on the array's element type.
6472 QualType elementType = AT->getElementType();
6473 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6474
6475 // If that didn't change the element type, AT has no qualifiers, so we
6476 // can just use the results in splitType.
6477 if (elementType == unqualElementType) {
6478 assert(quals.empty()); // from the recursive call
6479 quals = splitType.Quals;
6480 return QualType(splitType.Ty, 0);
6481 }
6482
6483 // Otherwise, add in the qualifiers from the outermost type, then
6484 // build the type back up.
6485 quals.addConsistentQualifiers(splitType.Quals);
6486
6487 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
6488 return getConstantArrayType(unqualElementType, CAT->getSize(),
6489 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
6490 }
6491
6492 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
6493 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
6494 }
6495
6496 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
6497 return getVariableArrayType(unqualElementType,
6498 VAT->getSizeExpr(),
6499 VAT->getSizeModifier(),
6500 VAT->getIndexTypeCVRQualifiers(),
6501 VAT->getBracketsRange());
6502 }
6503
6504 const auto *DSAT = cast<DependentSizedArrayType>(AT);
6505 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
6506 DSAT->getSizeModifier(), 0,
6507 SourceRange());
6508}
6509
6510/// Attempt to unwrap two types that may both be array types with the same bound
6511/// (or both be array types of unknown bound) for the purpose of comparing the
6512/// cv-decomposition of two types per C++ [conv.qual].
6513///
6514/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6515/// C++20 [conv.qual], if permitted by the current language mode.
6517 bool AllowPiMismatch) {
6518 while (true) {
6519 auto *AT1 = getAsArrayType(T1);
6520 if (!AT1)
6521 return;
6522
6523 auto *AT2 = getAsArrayType(T2);
6524 if (!AT2)
6525 return;
6526
6527 // If we don't have two array types with the same constant bound nor two
6528 // incomplete array types, we've unwrapped everything we can.
6529 // C++20 also permits one type to be a constant array type and the other
6530 // to be an incomplete array type.
6531 // FIXME: Consider also unwrapping array of unknown bound and VLA.
6532 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
6533 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
6534 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
6535 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6536 isa<IncompleteArrayType>(AT2))))
6537 return;
6538 } else if (isa<IncompleteArrayType>(AT1)) {
6539 if (!(isa<IncompleteArrayType>(AT2) ||
6540 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6541 isa<ConstantArrayType>(AT2))))
6542 return;
6543 } else {
6544 return;
6545 }
6546
6547 T1 = AT1->getElementType();
6548 T2 = AT2->getElementType();
6549 }
6550}
6551
6552/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
6553///
6554/// If T1 and T2 are both pointer types of the same kind, or both array types
6555/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6556/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6557///
6558/// This function will typically be called in a loop that successively
6559/// "unwraps" pointer and pointer-to-member types to compare them at each
6560/// level.
6561///
6562/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6563/// C++20 [conv.qual], if permitted by the current language mode.
6564///
6565/// \return \c true if a pointer type was unwrapped, \c false if we reached a
6566/// pair of types that can't be unwrapped further.
6568 bool AllowPiMismatch) {
6569 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6570
6571 const auto *T1PtrType = T1->getAs<PointerType>();
6572 const auto *T2PtrType = T2->getAs<PointerType>();
6573 if (T1PtrType && T2PtrType) {
6574 T1 = T1PtrType->getPointeeType();
6575 T2 = T2PtrType->getPointeeType();
6576 return true;
6577 }
6578
6579 const auto *T1MPType = T1->getAs<MemberPointerType>();
6580 const auto *T2MPType = T2->getAs<MemberPointerType>();
6581 if (T1MPType && T2MPType &&
6582 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6583 QualType(T2MPType->getClass(), 0))) {
6584 T1 = T1MPType->getPointeeType();
6585 T2 = T2MPType->getPointeeType();
6586 return true;
6587 }
6588
6589 if (getLangOpts().ObjC) {
6590 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6591 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6592 if (T1OPType && T2OPType) {
6593 T1 = T1OPType->getPointeeType();
6594 T2 = T2OPType->getPointeeType();
6595 return true;
6596 }
6597 }
6598
6599 // FIXME: Block pointers, too?
6600
6601 return false;
6602}
6603
6605 while (true) {
6606 Qualifiers Quals;
6607 T1 = getUnqualifiedArrayType(T1, Quals);
6608 T2 = getUnqualifiedArrayType(T2, Quals);
6609 if (hasSameType(T1, T2))
6610 return true;
6611 if (!UnwrapSimilarTypes(T1, T2))
6612 return false;
6613 }
6614}
6615
6617 while (true) {
6618 Qualifiers Quals1, Quals2;
6619 T1 = getUnqualifiedArrayType(T1, Quals1);
6620 T2 = getUnqualifiedArrayType(T2, Quals2);
6621
6622 Quals1.removeCVRQualifiers();
6623 Quals2.removeCVRQualifiers();
6624 if (Quals1 != Quals2)
6625 return false;
6626
6627 if (hasSameType(T1, T2))
6628 return true;
6629
6630 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6631 return false;
6632 }
6633}
6634
6637 SourceLocation NameLoc) const {
6638 switch (Name.getKind()) {
6641 // DNInfo work in progress: CHECKME: what about DNLoc?
6642 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6643 NameLoc);
6644
6646 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6647 // DNInfo work in progress: CHECKME: what about DNLoc?
6648 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6649 }
6650
6652 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6653 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6654 }
6655
6657 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6658 DeclarationName DName;
6659 if (DTN->isIdentifier()) {
6661 return DeclarationNameInfo(DName, NameLoc);
6662 } else {
6664 // DNInfo work in progress: FIXME: source locations?
6665 DeclarationNameLoc DNLoc =
6667 return DeclarationNameInfo(DName, NameLoc, DNLoc);
6668 }
6669 }
6670
6673 = Name.getAsSubstTemplateTemplateParm();
6674 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6675 NameLoc);
6676 }
6677
6680 = Name.getAsSubstTemplateTemplateParmPack();
6682 NameLoc);
6683 }
6685 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
6686 NameLoc);
6687 }
6688
6689 llvm_unreachable("bad template name kind!");
6690}
6691
6694 switch (Name.getKind()) {
6698 TemplateDecl *Template = Name.getAsTemplateDecl();
6699 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
6700 Template = getCanonicalTemplateTemplateParmDecl(TTP);
6701
6702 // The canonical template name is the canonical template declaration.
6703 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6704 }
6705
6708 llvm_unreachable("cannot canonicalize unresolved template");
6709
6711 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6712 assert(DTN && "Non-dependent template names must refer to template decls.");
6713 return DTN->CanonicalTemplateName;
6714 }
6715
6718 = Name.getAsSubstTemplateTemplateParm();
6720 }
6721
6724 Name.getAsSubstTemplateTemplateParmPack();
6725 TemplateArgument canonArgPack =
6728 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
6729 subst->getFinal(), subst->getIndex());
6730 }
6731 }
6732
6733 llvm_unreachable("bad template name!");
6734}
6735
6737 const TemplateName &Y) const {
6740}
6741
6742bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
6743 if (!XCE != !YCE)
6744 return false;
6745
6746 if (!XCE)
6747 return true;
6748
6749 llvm::FoldingSetNodeID XCEID, YCEID;
6750 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6751 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6752 return XCEID == YCEID;
6753}
6754
6756 const TypeConstraint *YTC) const {
6757 if (!XTC != !YTC)
6758 return false;
6759
6760 if (!XTC)
6761 return true;
6762
6763 auto *NCX = XTC->getNamedConcept();
6764 auto *NCY = YTC->getNamedConcept();
6765 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
6766 return false;
6769 return false;
6771 if (XTC->getConceptReference()
6773 ->NumTemplateArgs !=
6775 return false;
6776
6777 // Compare slowly by profiling.
6778 //
6779 // We couldn't compare the profiling result for the template
6780 // args here. Consider the following example in different modules:
6781 //
6782 // template <__integer_like _Tp, C<_Tp> Sentinel>
6783 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
6784 // return __t;
6785 // }
6786 //
6787 // When we compare the profiling result for `C<_Tp>` in different
6788 // modules, it will compare the type of `_Tp` in different modules.
6789 // However, the type of `_Tp` in different modules refer to different
6790 // types here naturally. So we couldn't compare the profiling result
6791 // for the template args directly.
6794}
6795
6797 const NamedDecl *Y) const {
6798 if (X->getKind() != Y->getKind())
6799 return false;
6800
6801 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
6802 auto *TY = cast<TemplateTypeParmDecl>(Y);
6803 if (TX->isParameterPack() != TY->isParameterPack())
6804 return false;
6805 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
6806 return false;
6807 return isSameTypeConstraint(TX->getTypeConstraint(),
6808 TY->getTypeConstraint());
6809 }
6810
6811 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6812 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
6813 return TX->isParameterPack() == TY->isParameterPack() &&
6814 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
6815 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
6816 TY->getPlaceholderTypeConstraint());
6817 }
6818
6819 auto *TX = cast<TemplateTemplateParmDecl>(X);
6820 auto *TY = cast<TemplateTemplateParmDecl>(Y);
6821 return TX->isParameterPack() == TY->isParameterPack() &&
6822 isSameTemplateParameterList(TX->getTemplateParameters(),
6823 TY->getTemplateParameters());
6824}
6825
6827 const TemplateParameterList *X, const TemplateParameterList *Y) const {
6828 if (X->size() != Y->size())
6829 return false;
6830
6831 for (unsigned I = 0, N = X->size(); I != N; ++I)
6832 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
6833 return false;
6834
6835 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
6836}
6837
6839 const NamedDecl *Y) const {
6840 // If the type parameter isn't the same already, we don't need to check the
6841 // default argument further.
6842 if (!isSameTemplateParameter(X, Y))
6843 return false;
6844
6845 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
6846 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
6847 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6848 return false;
6849
6850 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
6851 TTPY->getDefaultArgument().getArgument().getAsType());
6852 }
6853
6854 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6855 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
6856 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
6857 return false;
6858
6859 Expr *DefaultArgumentX =
6860 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
6861 Expr *DefaultArgumentY =
6862 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
6863 llvm::FoldingSetNodeID XID, YID;
6864 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
6865 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
6866 return XID == YID;
6867 }
6868
6869 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
6870 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
6871
6872 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6873 return false;
6874
6875 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
6876 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
6877 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
6878}
6879
6881 if (auto *NS = X->getAsNamespace())
6882 return NS;
6883 if (auto *NAS = X->getAsNamespaceAlias())
6884 return NAS->getNamespace();
6885 return nullptr;
6886}
6887
6889 const NestedNameSpecifier *Y) {
6890 if (auto *NSX = getNamespace(X)) {
6891 auto *NSY = getNamespace(Y);
6892 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
6893 return false;
6894 } else if (X->getKind() != Y->getKind())
6895 return false;
6896
6897 // FIXME: For namespaces and types, we're permitted to check that the entity
6898 // is named via the same tokens. We should probably do so.
6899 switch (X->getKind()) {
6901 if (X->getAsIdentifier() != Y->getAsIdentifier())
6902 return false;
6903 break;
6906 // We've already checked that we named the same namespace.
6907 break;
6910 if (X->getAsType()->getCanonicalTypeInternal() !=
6912 return false;
6913 break;
6916 return true;
6917 }
6918
6919 // Recurse into earlier portion of NNS, if any.
6920 auto *PX = X->getPrefix();
6921 auto *PY = Y->getPrefix();
6922 if (PX && PY)
6923 return isSameQualifier(PX, PY);
6924 return !PX && !PY;
6925}
6926
6927/// Determine whether the attributes we can overload on are identical for A and
6928/// B. Will ignore any overloadable attrs represented in the type of A and B.
6930 const FunctionDecl *B) {
6931 // Note that pass_object_size attributes are represented in the function's
6932 // ExtParameterInfo, so we don't need to check them here.
6933
6934 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
6935 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
6936 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
6937
6938 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
6939 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
6940 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
6941
6942 // Return false if the number of enable_if attributes is different.
6943 if (!Cand1A || !Cand2A)
6944 return false;
6945
6946 Cand1ID.clear();
6947 Cand2ID.clear();
6948
6949 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
6950 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
6951
6952 // Return false if any of the enable_if expressions of A and B are
6953 // different.
6954 if (Cand1ID != Cand2ID)
6955 return false;
6956 }
6957 return true;
6958}
6959
6960bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
6961 // Caution: this function is called by the AST reader during deserialization,
6962 // so it cannot rely on AST invariants being met. Non-trivial accessors
6963 // should be avoided, along with any traversal of redeclaration chains.
6964
6965 if (X == Y)
6966 return true;
6967
6968 if (X->getDeclName() != Y->getDeclName())
6969 return false;
6970
6971 // Must be in the same context.
6972 //
6973 // Note that we can't use DeclContext::Equals here, because the DeclContexts
6974 // could be two different declarations of the same function. (We will fix the
6975 // semantic DC to refer to the primary definition after merging.)
6976 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
6977 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
6978 return false;
6979
6980 // Two typedefs refer to the same entity if they have the same underlying
6981 // type.
6982 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
6983 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
6984 return hasSameType(TypedefX->getUnderlyingType(),
6985 TypedefY->getUnderlyingType());
6986
6987 // Must have the same kind.
6988 if (X->getKind() != Y->getKind())
6989 return false;
6990
6991 // Objective-C classes and protocols with the same name always match.
6992 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
6993 return true;
6994
6995 if (isa<ClassTemplateSpecializationDecl>(X)) {
6996 // No need to handle these here: we merge them when adding them to the
6997 // template.
6998 return false;
6999 }
7000
7001 // Compatible tags match.
7002 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7003 const auto *TagY = cast<TagDecl>(Y);
7004 return (TagX->getTagKind() == TagY->getTagKind()) ||
7005 ((TagX->getTagKind() == TagTypeKind::Struct ||
7006 TagX->getTagKind() == TagTypeKind::Class ||
7007 TagX->getTagKind() == TagTypeKind::Interface) &&
7008 (TagY->getTagKind() == TagTypeKind::Struct ||
7009 TagY->getTagKind() == TagTypeKind::Class ||
7010 TagY->getTagKind() == TagTypeKind::Interface));
7011 }
7012
7013 // Functions with the same type and linkage match.
7014 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7015 // functions, etc.
7016 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7017 const auto *FuncY = cast<FunctionDecl>(Y);
7018 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7019 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7020 if (CtorX->getInheritedConstructor() &&
7021 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7022 CtorY->getInheritedConstructor().getConstructor()))
7023 return false;
7024 }
7025
7026 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7027 return false;
7028
7029 // Multiversioned functions with different feature strings are represented
7030 // as separate declarations.
7031 if (FuncX->isMultiVersion()) {
7032 const auto *TAX = FuncX->getAttr<TargetAttr>();
7033 const auto *TAY = FuncY->getAttr<TargetAttr>();
7034 assert(TAX && TAY && "Multiversion Function without target attribute");
7035
7036 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7037 return false;
7038 }
7039
7040 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7041 // not the same entity if they are constrained.
7042 if ((FuncX->isMemberLikeConstrainedFriend() ||
7043 FuncY->isMemberLikeConstrainedFriend()) &&
7044 !FuncX->getLexicalDeclContext()->Equals(
7045 FuncY->getLexicalDeclContext())) {
7046 return false;
7047 }
7048
7049 if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(),
7050 FuncY->getTrailingRequiresClause()))
7051 return false;
7052
7053 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7054 // Map to the first declaration that we've already merged into this one.
7055 // The TSI of redeclarations might not match (due to calling conventions
7056 // being inherited onto the type but not the TSI), but the TSI type of
7057 // the first declaration of the function should match across modules.
7058 FD = FD->getCanonicalDecl();
7059 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7060 : FD->getType();
7061 };
7062 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7063 if (!hasSameType(XT, YT)) {
7064 // We can get functions with different types on the redecl chain in C++17
7065 // if they have differing exception specifications and at least one of
7066 // the excpetion specs is unresolved.
7067 auto *XFPT = XT->getAs<FunctionProtoType>();
7068 auto *YFPT = YT->getAs<FunctionProtoType>();
7069 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7070 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7073 return true;
7074 return false;
7075 }
7076
7077 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7078 hasSameOverloadableAttrs(FuncX, FuncY);
7079 }
7080
7081 // Variables with the same type and linkage match.
7082 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7083 const auto *VarY = cast<VarDecl>(Y);
7084 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7085 // During deserialization, we might compare variables before we load
7086 // their types. Assume the types will end up being the same.
7087 if (VarX->getType().isNull() || VarY->getType().isNull())
7088 return true;
7089
7090 if (hasSameType(VarX->getType(), VarY->getType()))
7091 return true;
7092
7093 // We can get decls with different types on the redecl chain. Eg.
7094 // template <typename T> struct S { static T Var[]; }; // #1
7095 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7096 // Only? happens when completing an incomplete array type. In this case
7097 // when comparing #1 and #2 we should go through their element type.
7098 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7099 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7100 if (!VarXTy || !VarYTy)
7101 return false;
7102 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7103 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7104 }
7105 return false;
7106 }
7107
7108 // Namespaces with the same name and inlinedness match.
7109 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7110 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7111 return NamespaceX->isInline() == NamespaceY->isInline();
7112 }
7113
7114 // Identical template names and kinds match if their template parameter lists
7115 // and patterns match.
7116 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7117 const auto *TemplateY = cast<TemplateDecl>(Y);
7118
7119 // ConceptDecl wouldn't be the same if their constraint expression differs.
7120 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7121 const auto *ConceptY = cast<ConceptDecl>(Y);
7122 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7123 ConceptY->getConstraintExpr()))
7124 return false;
7125 }
7126
7127 return isSameEntity(TemplateX->getTemplatedDecl(),
7128 TemplateY->getTemplatedDecl()) &&
7129 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7130 TemplateY->getTemplateParameters());
7131 }
7132
7133 // Fields with the same name and the same type match.
7134 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7135 const auto *FDY = cast<FieldDecl>(Y);
7136 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7137 return hasSameType(FDX->getType(), FDY->getType());
7138 }
7139
7140 // Indirect fields with the same target field match.
7141 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7142 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7143 return IFDX->getAnonField()->getCanonicalDecl() ==
7144 IFDY->getAnonField()->getCanonicalDecl();
7145 }
7146
7147 // Enumerators with the same name match.
7148 if (isa<EnumConstantDecl>(X))
7149 // FIXME: Also check the value is odr-equivalent.
7150 return true;
7151
7152 // Using shadow declarations with the same target match.
7153 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7154 const auto *USY = cast<UsingShadowDecl>(Y);
7155 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7156 }
7157
7158 // Using declarations with the same qualifier match. (We already know that
7159 // the name matches.)
7160 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7161 const auto *UY = cast<UsingDecl>(Y);
7162 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7163 UX->hasTypename() == UY->hasTypename() &&
7164 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7165 }
7166 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7167 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7168 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7169 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7170 }
7171 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7172 return isSameQualifier(
7173 UX->getQualifier(),
7174 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7175 }
7176
7177 // Using-pack declarations are only created by instantiation, and match if
7178 // they're instantiated from matching UnresolvedUsing...Decls.
7179 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7180 return declaresSameEntity(
7181 UX->getInstantiatedFromUsingDecl(),
7182 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7183 }
7184
7185 // Namespace alias definitions with the same target match.
7186 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7187 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7188 return NAX->getNamespace()->Equals(NAY->getNamespace());
7189 }
7190
7191 return false;
7192}
7193
7196 switch (Arg.getKind()) {
7198 return Arg;
7199
7201 return Arg;
7202
7204 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7206 Arg.getIsDefaulted());
7207 }
7208
7211 /*isNullPtr*/ true, Arg.getIsDefaulted());
7212
7215 Arg.getIsDefaulted());
7216
7218 return TemplateArgument(
7221
7224
7226 return TemplateArgument(*this,
7228 Arg.getAsStructuralValue());
7229
7232 /*isNullPtr*/ false, Arg.getIsDefaulted());
7233
7235 bool AnyNonCanonArgs = false;
7236 auto CanonArgs = ::getCanonicalTemplateArguments(
7237 *this, Arg.pack_elements(), AnyNonCanonArgs);
7238 if (!AnyNonCanonArgs)
7239 return Arg;
7240 return TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this),
7241 CanonArgs);
7242 }
7243 }
7244
7245 // Silence GCC warning
7246 llvm_unreachable("Unhandled template argument kind");
7247}
7248
7251 if (!NNS)
7252 return nullptr;
7253
7254 switch (NNS->getKind()) {
7256 // Canonicalize the prefix but keep the identifier the same.
7257 return NestedNameSpecifier::Create(*this,
7259 NNS->getAsIdentifier());
7260
7262 // A namespace is canonical; build a nested-name-specifier with
7263 // this namespace and no prefix.
7264 return NestedNameSpecifier::Create(*this, nullptr,
7265 NNS->getAsNamespace()->getFirstDecl());
7266
7268 // A namespace is canonical; build a nested-name-specifier with
7269 // this namespace and no prefix.
7271 *this, nullptr,
7273
7274 // The difference between TypeSpec and TypeSpecWithTemplate is that the
7275 // latter will have the 'template' keyword when printed.
7278 const Type *T = getCanonicalType(NNS->getAsType());
7279
7280 // If we have some kind of dependent-named type (e.g., "typename T::type"),
7281 // break it apart into its prefix and identifier, then reconsititute those
7282 // as the canonical nested-name-specifier. This is required to canonicalize
7283 // a dependent nested-name-specifier involving typedefs of dependent-name
7284 // types, e.g.,
7285 // typedef typename T::type T1;
7286 // typedef typename T1::type T2;
7287 if (const auto *DNT = T->getAs<DependentNameType>())
7288 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
7289 DNT->getIdentifier());
7290 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
7291 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, T);
7292
7293 // TODO: Set 'Template' parameter to true for other template types.
7294 return NestedNameSpecifier::Create(*this, nullptr, false, T);
7295 }
7296
7299 // The global specifier and __super specifer are canonical and unique.
7300 return NNS;
7301 }
7302
7303 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
7304}
7305
7307 // Handle the non-qualified case efficiently.
7308 if (!T.hasLocalQualifiers()) {
7309 // Handle the common positive case fast.
7310 if (const auto *AT = dyn_cast<ArrayType>(T))
7311 return AT;
7312 }
7313
7314 // Handle the common negative case fast.
7315 if (!isa<ArrayType>(T.getCanonicalType()))
7316 return nullptr;
7317
7318 // Apply any qualifiers from the array type to the element type. This
7319 // implements C99 6.7.3p8: "If the specification of an array type includes
7320 // any type qualifiers, the element type is so qualified, not the array type."
7321
7322 // If we get here, we either have type qualifiers on the type, or we have
7323 // sugar such as a typedef in the way. If we have type qualifiers on the type
7324 // we must propagate them down into the element type.
7325
7326 SplitQualType split = T.getSplitDesugaredType();
7327 Qualifiers qs = split.Quals;
7328
7329 // If we have a simple case, just return now.
7330 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7331 if (!ATy || qs.empty())
7332 return ATy;
7333
7334 // Otherwise, we have an array and we have qualifiers on it. Push the
7335 // qualifiers into the array element type and return a new array type.
7336 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7337
7338 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7339 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7340 CAT->getSizeExpr(),
7341 CAT->getSizeModifier(),
7342 CAT->getIndexTypeCVRQualifiers()));
7343 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
7344 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
7345 IAT->getSizeModifier(),
7346 IAT->getIndexTypeCVRQualifiers()));
7347
7348 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
7349 return cast<ArrayType>(
7351 DSAT->getSizeExpr(),
7352 DSAT->getSizeModifier(),
7353 DSAT->getIndexTypeCVRQualifiers(),
7354 DSAT->getBracketsRange()));
7355
7356 const auto *VAT = cast<VariableArrayType>(ATy);
7357 return cast<ArrayType>(getVariableArrayType(NewEltTy,
7358 VAT->getSizeExpr(),
7359 VAT->getSizeModifier(),
7360 VAT->getIndexTypeCVRQualifiers(),
7361 VAT->getBracketsRange()));
7362}
7363
7366 return getArrayParameterType(T);
7367 if (T->isArrayType() || T->isFunctionType())
7368 return getDecayedType(T);
7369 return T;
7370}
7371
7375 return T.getUnqualifiedType();
7376}
7377
7379 // C++ [except.throw]p3:
7380 // A throw-expression initializes a temporary object, called the exception
7381 // object, the type of which is determined by removing any top-level
7382 // cv-qualifiers from the static type of the operand of throw and adjusting
7383 // the type from "array of T" or "function returning T" to "pointer to T"
7384 // or "pointer to function returning T", [...]
7386 if (T->isArrayType() || T->isFunctionType())
7387 T = getDecayedType(T);
7388 return T.getUnqualifiedType();
7389}
7390
7391/// getArrayDecayedType - Return the properly qualified result of decaying the
7392/// specified array type to a pointer. This operation is non-trivial when
7393/// handling typedefs etc. The canonical type of "T" must be an array type,
7394/// this returns a pointer to a properly qualified element of the array.
7395///
7396/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
7398 // Get the element type with 'getAsArrayType' so that we don't lose any
7399 // typedefs in the element type of the array. This also handles propagation
7400 // of type qualifiers from the array type into the element type if present
7401 // (C99 6.7.3p8).
7402 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
7403 assert(PrettyArrayType && "Not an array type!");
7404
7405 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
7406
7407 // int x[restrict 4] -> int *restrict
7409 PrettyArrayType->getIndexTypeQualifiers());
7410
7411 // int x[_Nullable] -> int * _Nullable
7412 if (auto Nullability = Ty->getNullability()) {
7413 Result = const_cast<ASTContext *>(this)->getAttributedType(
7415 }
7416 return Result;
7417}
7418
7420 return getBaseElementType(array->getElementType());
7421}
7422
7424 Qualifiers qs;
7425 while (true) {
7426 SplitQualType split = type.getSplitDesugaredType();
7427 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
7428 if (!array) break;
7429
7430 type = array->getElementType();
7432 }
7433
7434 return getQualifiedType(type, qs);
7435}
7436
7437/// getConstantArrayElementCount - Returns number of constant array elements.
7438uint64_t
7440 uint64_t ElementCount = 1;
7441 do {
7442 ElementCount *= CA->getZExtSize();
7443 CA = dyn_cast_or_null<ConstantArrayType>(
7445 } while (CA);
7446 return ElementCount;
7447}
7448
7450 const ArrayInitLoopExpr *AILE) const {
7451 if (!AILE)
7452 return 0;
7453
7454 uint64_t ElementCount = 1;
7455
7456 do {
7457 ElementCount *= AILE->getArraySize().getZExtValue();
7458 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
7459 } while (AILE);
7460
7461 return ElementCount;
7462}
7463
7464/// getFloatingRank - Return a relative rank for floating point types.
7465/// This routine will assert if passed a built-in type that isn't a float.
7467 if (const auto *CT = T->getAs<ComplexType>())
7468 return getFloatingRank(CT->getElementType());
7469
7470 switch (T->castAs<BuiltinType>()->getKind()) {
7471 default: llvm_unreachable("getFloatingRank(): not a floating type");
7472 case BuiltinType::Float16: return Float16Rank;
7473 case BuiltinType::Half: return HalfRank;
7474 case BuiltinType::Float: return FloatRank;
7475 case BuiltinType::Double: return DoubleRank;
7476 case BuiltinType::LongDouble: return LongDoubleRank;
7477 case BuiltinType::Float128: return Float128Rank;
7478 case BuiltinType::BFloat16: return BFloat16Rank;
7479 case BuiltinType::Ibm128: return Ibm128Rank;
7480 }
7481}
7482
7483/// getFloatingTypeOrder - Compare the rank of the two specified floating
7484/// point types, ignoring the domain of the type (i.e. 'double' ==
7485/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
7486/// LHS < RHS, return -1.
7488 FloatingRank LHSR = getFloatingRank(LHS);
7489 FloatingRank RHSR = getFloatingRank(RHS);
7490
7491 if (LHSR == RHSR)
7492 return 0;
7493 if (LHSR > RHSR)
7494 return 1;
7495 return -1;
7496}
7497
7500 return 0;
7501 return getFloatingTypeOrder(LHS, RHS);
7502}
7503
7504/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
7505/// routine will assert if passed a built-in type that isn't an integer or enum,
7506/// or if it is not canonicalized.
7507unsigned ASTContext::getIntegerRank(const Type *T) const {
7508 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
7509
7510 // Results in this 'losing' to any type of the same size, but winning if
7511 // larger.
7512 if (const auto *EIT = dyn_cast<BitIntType>(T))
7513 return 0 + (EIT->getNumBits() << 3);
7514
7515 switch (cast<BuiltinType>(T)->getKind()) {
7516 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
7517 case BuiltinType::Bool:
7518 return 1 + (getIntWidth(BoolTy) << 3);
7519 case BuiltinType::Char_S:
7520 case BuiltinType::Char_U:
7521 case BuiltinType::SChar:
7522 case BuiltinType::UChar:
7523 return 2 + (getIntWidth(CharTy) << 3);
7524 case BuiltinType::Short:
7525 case BuiltinType::UShort:
7526 return 3 + (getIntWidth(ShortTy) << 3);
7527 case BuiltinType::Int:
7528 case BuiltinType::UInt:
7529 return 4 + (getIntWidth(IntTy) << 3);
7530 case BuiltinType::Long:
7531 case BuiltinType::ULong:
7532 return 5 + (getIntWidth(LongTy) << 3);
7533 case BuiltinType::LongLong:
7534 case BuiltinType::ULongLong:
7535 return 6 + (getIntWidth(LongLongTy) << 3);
7536 case BuiltinType::Int128:
7537 case BuiltinType::UInt128:
7538 return 7 + (getIntWidth(Int128Ty) << 3);
7539
7540 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
7541 // their underlying types" [c++20 conv.rank]
7542 case BuiltinType::Char8:
7543 return getIntegerRank(UnsignedCharTy.getTypePtr());
7544 case BuiltinType::Char16:
7545 return getIntegerRank(
7546 getFromTargetType(Target->getChar16Type()).getTypePtr());
7547 case BuiltinType::Char32:
7548 return getIntegerRank(
7549 getFromTargetType(Target->getChar32Type()).getTypePtr());
7550 case BuiltinType::WChar_S:
7551 case BuiltinType::WChar_U:
7552 return getIntegerRank(
7553 getFromTargetType(Target->getWCharType()).getTypePtr());
7554 }
7555}
7556
7557/// Whether this is a promotable bitfield reference according
7558/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
7559///
7560/// \returns the type this bit-field will promote to, or NULL if no
7561/// promotion occurs.
7563 if (E->isTypeDependent() || E->isValueDependent())
7564 return {};
7565
7566 // C++ [conv.prom]p5:
7567 // If the bit-field has an enumerated type, it is treated as any other
7568 // value of that type for promotion purposes.
7570 return {};
7571
7572 // FIXME: We should not do this unless E->refersToBitField() is true. This
7573 // matters in C where getSourceBitField() will find bit-fields for various
7574 // cases where the source expression is not a bit-field designator.
7575
7576 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
7577 if (!Field)
7578 return {};
7579
7580 QualType FT = Field->getType();
7581
7582 uint64_t BitWidth = Field->getBitWidthValue(*this);
7583 uint64_t IntSize = getTypeSize(IntTy);
7584 // C++ [conv.prom]p5:
7585 // A prvalue for an integral bit-field can be converted to a prvalue of type
7586 // int if int can represent all the values of the bit-field; otherwise, it
7587 // can be converted to unsigned int if unsigned int can represent all the
7588 // values of the bit-field. If the bit-field is larger yet, no integral
7589 // promotion applies to it.
7590 // C11 6.3.1.1/2:
7591 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
7592 // If an int can represent all values of the original type (as restricted by
7593 // the width, for a bit-field), the value is converted to an int; otherwise,
7594 // it is converted to an unsigned int.
7595 //
7596 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
7597 // We perform that promotion here to match GCC and C++.
7598 // FIXME: C does not permit promotion of an enum bit-field whose rank is
7599 // greater than that of 'int'. We perform that promotion to match GCC.
7600 //
7601 // C23 6.3.1.1p2:
7602 // The value from a bit-field of a bit-precise integer type is converted to
7603 // the corresponding bit-precise integer type. (The rest is the same as in
7604 // C11.)
7605 if (QualType QT = Field->getType(); QT->isBitIntType())
7606 return QT;
7607
7608 if (BitWidth < IntSize)
7609 return IntTy;
7610
7611 if (BitWidth == IntSize)
7612 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
7613
7614 // Bit-fields wider than int are not subject to promotions, and therefore act
7615 // like the base type. GCC has some weird bugs in this area that we
7616 // deliberately do not follow (GCC follows a pre-standard resolution to
7617 // C's DR315 which treats bit-width as being part of the type, and this leaks
7618 // into their semantics in some cases).
7619 return {};
7620}
7621
7622/// getPromotedIntegerType - Returns the type that Promotable will
7623/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
7624/// integer type.
7626 assert(!Promotable.isNull());
7627 assert(isPromotableIntegerType(Promotable));
7628 if (const auto *ET = Promotable->getAs<EnumType>())
7629 return ET->getDecl()->getPromotionType();
7630
7631 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
7632 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
7633 // (3.9.1) can be converted to a prvalue of the first of the following
7634 // types that can represent all the values of its underlying type:
7635 // int, unsigned int, long int, unsigned long int, long long int, or
7636 // unsigned long long int [...]
7637 // FIXME: Is there some better way to compute this?
7638 if (BT->getKind() == BuiltinType::WChar_S ||
7639 BT->getKind() == BuiltinType::WChar_U ||
7640 BT->getKind() == BuiltinType::Char8 ||
7641 BT->getKind() == BuiltinType::Char16 ||
7642 BT->getKind() == BuiltinType::Char32) {
7643 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
7644 uint64_t FromSize = getTypeSize(BT);
7645 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
7647 for (const auto &PT : PromoteTypes) {
7648 uint64_t ToSize = getTypeSize(PT);
7649 if (FromSize < ToSize ||
7650 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
7651 return PT;
7652 }
7653 llvm_unreachable("char type should fit into long long");
7654 }
7655 }
7656
7657 // At this point, we should have a signed or unsigned integer type.
7658 if (Promotable->isSignedIntegerType())
7659 return IntTy;
7660 uint64_t PromotableSize = getIntWidth(Promotable);
7661 uint64_t IntSize = getIntWidth(IntTy);
7662 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
7663 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
7664}
7665
7666/// Recurses in pointer/array types until it finds an objc retainable
7667/// type and returns its ownership.
7669 while (!T.isNull()) {
7670 if (T.getObjCLifetime() != Qualifiers::OCL_None)
7671 return T.getObjCLifetime();
7672 if (T->isArrayType())
7674 else if (const auto *PT = T->getAs<PointerType>())
7675 T = PT->getPointeeType();
7676 else if (const auto *RT = T->getAs<ReferenceType>())
7677 T = RT->getPointeeType();
7678 else
7679 break;
7680 }
7681
7682 return Qualifiers::OCL_None;
7683}
7684
7685static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7686 // Incomplete enum types are not treated as integer types.
7687 // FIXME: In C++, enum types are never integer types.
7688 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7689 return ET->getDecl()->getIntegerType().getTypePtr();
7690 return nullptr;
7691}
7692
7693/// getIntegerTypeOrder - Returns the highest ranked integer type:
7694/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
7695/// LHS < RHS, return -1.
7697 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7698 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7699
7700 // Unwrap enums to their underlying type.
7701 if (const auto *ET = dyn_cast<EnumType>(LHSC))
7702 LHSC = getIntegerTypeForEnum(ET);
7703 if (const auto *ET = dyn_cast<EnumType>(RHSC))
7704 RHSC = getIntegerTypeForEnum(ET);
7705
7706 if (LHSC == RHSC) return 0;
7707
7708 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
7709 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
7710
7711 unsigned LHSRank = getIntegerRank(LHSC);
7712 unsigned RHSRank = getIntegerRank(RHSC);
7713
7714 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
7715 if (LHSRank == RHSRank) return 0;
7716 return LHSRank > RHSRank ? 1 : -1;
7717 }
7718
7719 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
7720 if (LHSUnsigned) {
7721 // If the unsigned [LHS] type is larger, return it.
7722 if (LHSRank >= RHSRank)
7723 return 1;
7724
7725 // If the signed type can represent all values of the unsigned type, it
7726 // wins. Because we are dealing with 2's complement and types that are
7727 // powers of two larger than each other, this is always safe.
7728 return -1;
7729 }
7730
7731 // If the unsigned [RHS] type is larger, return it.
7732 if (RHSRank >= LHSRank)
7733 return -1;
7734
7735 // If the signed type can represent all values of the unsigned type, it
7736 // wins. Because we are dealing with 2's complement and types that are
7737 // powers of two larger than each other, this is always safe.
7738 return 1;
7739}
7740
7742 if (CFConstantStringTypeDecl)
7743 return CFConstantStringTypeDecl;
7744
7745 assert(!CFConstantStringTagDecl &&
7746 "tag and typedef should be initialized together");
7747 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
7748 CFConstantStringTagDecl->startDefinition();
7749
7750 struct {
7751 QualType Type;
7752 const char *Name;
7753 } Fields[5];
7754 unsigned Count = 0;
7755
7756 /// Objective-C ABI
7757 ///
7758 /// typedef struct __NSConstantString_tag {
7759 /// const int *isa;
7760 /// int flags;
7761 /// const char *str;
7762 /// long length;
7763 /// } __NSConstantString;
7764 ///
7765 /// Swift ABI (4.1, 4.2)
7766 ///
7767 /// typedef struct __NSConstantString_tag {
7768 /// uintptr_t _cfisa;
7769 /// uintptr_t _swift_rc;
7770 /// _Atomic(uint64_t) _cfinfoa;
7771 /// const char *_ptr;
7772 /// uint32_t _length;
7773 /// } __NSConstantString;
7774 ///
7775 /// Swift ABI (5.0)
7776 ///
7777 /// typedef struct __NSConstantString_tag {
7778 /// uintptr_t _cfisa;
7779 /// uintptr_t _swift_rc;
7780 /// _Atomic(uint64_t) _cfinfoa;
7781 /// const char *_ptr;
7782 /// uintptr_t _length;
7783 /// } __NSConstantString;
7784
7785 const auto CFRuntime = getLangOpts().CFRuntime;
7786 if (static_cast<unsigned>(CFRuntime) <
7787 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
7788 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
7789 Fields[Count++] = { IntTy, "flags" };
7790 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
7791 Fields[Count++] = { LongTy, "length" };
7792 } else {
7793 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
7794 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
7795 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
7796 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
7799 Fields[Count++] = { IntTy, "_ptr" };
7800 else
7801 Fields[Count++] = { getUIntPtrType(), "_ptr" };
7802 }
7803
7804 // Create fields
7805 for (unsigned i = 0; i < Count; ++i) {
7806 FieldDecl *Field =
7807 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
7808 SourceLocation(), &Idents.get(Fields[i].Name),
7809 Fields[i].Type, /*TInfo=*/nullptr,
7810 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7811 Field->setAccess(AS_public);
7812 CFConstantStringTagDecl->addDecl(Field);
7813 }
7814
7815 CFConstantStringTagDecl->completeDefinition();
7816 // This type is designed to be compatible with NSConstantString, but cannot
7817 // use the same name, since NSConstantString is an interface.
7818 auto tagType = getTagDeclType(CFConstantStringTagDecl);
7819 CFConstantStringTypeDecl =
7820 buildImplicitTypedef(tagType, "__NSConstantString");
7821
7822 return CFConstantStringTypeDecl;
7823}
7824
7826 if (!CFConstantStringTagDecl)
7827 getCFConstantStringDecl(); // Build the tag and the typedef.
7828 return CFConstantStringTagDecl;
7829}
7830
7831// getCFConstantStringType - Return the type used for constant CFStrings.
7834}
7835
7837 if (ObjCSuperType.isNull()) {
7838 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
7839 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
7840 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
7841 }
7842 return ObjCSuperType;
7843}
7844
7846 const auto *TD = T->castAs<TypedefType>();
7847 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
7848 const auto *TagType =
7849 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
7850 CFConstantStringTagDecl = TagType->getDecl();
7851}
7852
7854 if (BlockDescriptorType)
7855 return getTagDeclType(BlockDescriptorType);
7856
7857 RecordDecl *RD;
7858 // FIXME: Needs the FlagAppleBlock bit.
7859 RD = buildImplicitRecord("__block_descriptor");
7860 RD->startDefinition();
7861
7862 QualType FieldTypes[] = {
7865 };
7866
7867 static const char *const FieldNames[] = {
7868 "reserved",
7869 "Size"
7870 };
7871
7872 for (size_t i = 0; i < 2; ++i) {
7874 *this, RD, SourceLocation(), SourceLocation(),
7875 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7876 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7877 Field->setAccess(AS_public);
7878 RD->addDecl(Field);
7879 }
7880
7881 RD->completeDefinition();
7882
7883 BlockDescriptorType = RD;
7884
7885 return getTagDeclType(BlockDescriptorType);
7886}
7887
7889 if (BlockDescriptorExtendedType)
7890 return getTagDeclType(BlockDescriptorExtendedType);
7891
7892 RecordDecl *RD;
7893 // FIXME: Needs the FlagAppleBlock bit.
7894 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
7895 RD->startDefinition();
7896
7897 QualType FieldTypes[] = {
7902 };
7903
7904 static const char *const FieldNames[] = {
7905 "reserved",
7906 "Size",
7907 "CopyFuncPtr",
7908 "DestroyFuncPtr"
7909 };
7910
7911 for (size_t i = 0; i < 4; ++i) {
7913 *this, RD, SourceLocation(), SourceLocation(),
7914 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7915 /*BitWidth=*/nullptr,
7916 /*Mutable=*/false, ICIS_NoInit);
7917 Field->setAccess(AS_public);
7918 RD->addDecl(Field);
7919 }
7920
7921 RD->completeDefinition();
7922
7923 BlockDescriptorExtendedType = RD;
7924 return getTagDeclType(BlockDescriptorExtendedType);
7925}
7926
7928 const auto *BT = dyn_cast<BuiltinType>(T);
7929
7930 if (!BT) {
7931 if (isa<PipeType>(T))
7932 return OCLTK_Pipe;
7933
7934 return OCLTK_Default;
7935 }
7936
7937 switch (BT->getKind()) {
7938#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7939 case BuiltinType::Id: \
7940 return OCLTK_Image;
7941#include "clang/Basic/OpenCLImageTypes.def"
7942
7943 case BuiltinType::OCLClkEvent:
7944 return OCLTK_ClkEvent;
7945
7946 case BuiltinType::OCLEvent:
7947 return OCLTK_Event;
7948
7949 case BuiltinType::OCLQueue:
7950 return OCLTK_Queue;
7951
7952 case BuiltinType::OCLReserveID:
7953 return OCLTK_ReserveID;
7954
7955 case BuiltinType::OCLSampler:
7956 return OCLTK_Sampler;
7957
7958 default:
7959 return OCLTK_Default;
7960 }
7961}
7962
7964 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
7965}
7966
7967/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
7968/// requires copy/dispose. Note that this must match the logic
7969/// in buildByrefHelpers.
7971 const VarDecl *D) {
7972 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
7973 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
7974 if (!copyExpr && record->hasTrivialDestructor()) return false;
7975
7976 return true;
7977 }
7978
7979 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
7980 // move or destroy.
7982 return true;
7983
7984 if (!Ty->isObjCRetainableType()) return false;
7985
7986 Qualifiers qs = Ty.getQualifiers();
7987
7988 // If we have lifetime, that dominates.
7989 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
7990 switch (lifetime) {
7991 case Qualifiers::OCL_None: llvm_unreachable("impossible");
7992
7993 // These are just bits as far as the runtime is concerned.
7996 return false;
7997
7998 // These cases should have been taken care of when checking the type's
7999 // non-triviality.
8002 llvm_unreachable("impossible");
8003 }
8004 llvm_unreachable("fell out of lifetime switch!");
8005 }
8006 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8008}
8009
8011 Qualifiers::ObjCLifetime &LifeTime,
8012 bool &HasByrefExtendedLayout) const {
8013 if (!getLangOpts().ObjC ||
8014 getLangOpts().getGC() != LangOptions::NonGC)
8015 return false;
8016
8017 HasByrefExtendedLayout = false;
8018 if (Ty->isRecordType()) {
8019 HasByrefExtendedLayout = true;
8020 LifeTime = Qualifiers::OCL_None;
8021 } else if ((LifeTime = Ty.getObjCLifetime())) {
8022 // Honor the ARC qualifiers.
8023 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8024 // The MRR rule.
8026 } else {
8027 LifeTime = Qualifiers::OCL_None;
8028 }
8029 return true;
8030}
8031
8033 assert(Target && "Expected target to be initialized");
8034 const llvm::Triple &T = Target->getTriple();
8035 // Windows is LLP64 rather than LP64
8036 if (T.isOSWindows() && T.isArch64Bit())
8037 return UnsignedLongLongTy;
8038 return UnsignedLongTy;
8039}
8040
8042 assert(Target && "Expected target to be initialized");
8043 const llvm::Triple &T = Target->getTriple();
8044 // Windows is LLP64 rather than LP64
8045 if (T.isOSWindows() && T.isArch64Bit())
8046 return LongLongTy;
8047 return LongTy;
8048}
8049
8051 if (!ObjCInstanceTypeDecl)
8052 ObjCInstanceTypeDecl =
8053 buildImplicitTypedef(getObjCIdType(), "instancetype");
8054 return ObjCInstanceTypeDecl;
8055}
8056
8057// This returns true if a type has been typedefed to BOOL:
8058// typedef <type> BOOL;
8060 if (const auto *TT = dyn_cast<TypedefType>(T))
8061 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8062 return II->isStr("BOOL");
8063
8064 return false;
8065}
8066
8067/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8068/// purpose.
8070 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8071 return CharUnits::Zero();
8072
8074
8075 // Make all integer and enum types at least as large as an int
8076 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8077 sz = std::max(sz, getTypeSizeInChars(IntTy));
8078 // Treat arrays as pointers, since that's how they're passed in.
8079 else if (type->isArrayType())
8081 return sz;
8082}
8083
8085 return getTargetInfo().getCXXABI().isMicrosoft() &&
8086 VD->isStaticDataMember() &&
8088 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8089}
8090
8093 if (!VD->isInline())
8095
8096 // In almost all cases, it's a weak definition.
8097 auto *First = VD->getFirstDecl();
8098 if (First->isInlineSpecified() || !First->isStaticDataMember())
8100
8101 // If there's a file-context declaration in this translation unit, it's a
8102 // non-discardable definition.
8103 for (auto *D : VD->redecls())
8105 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8107
8108 // If we've not seen one yet, we don't know.
8110}
8111
8112static std::string charUnitsToString(const CharUnits &CU) {
8113 return llvm::itostr(CU.getQuantity());
8114}
8115
8116/// getObjCEncodingForBlock - Return the encoded type for this block
8117/// declaration.
8119 std::string S;
8120
8121 const BlockDecl *Decl = Expr->getBlockDecl();
8122 QualType BlockTy =
8124 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8125 // Encode result type.
8126 if (getLangOpts().EncodeExtendedBlockSig)
8128 true /*Extended*/);
8129 else
8130 getObjCEncodingForType(BlockReturnTy, S);
8131 // Compute size of all parameters.
8132 // Start with computing size of a pointer in number of bytes.
8133 // FIXME: There might(should) be a better way of doing this computation!
8135 CharUnits ParmOffset = PtrSize;
8136 for (auto *PI : Decl->parameters()) {
8137 QualType PType = PI->getType();
8139 if (sz.isZero())
8140 continue;
8141 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8142 ParmOffset += sz;
8143 }
8144 // Size of the argument frame
8145 S += charUnitsToString(ParmOffset);
8146 // Block pointer and offset.
8147 S += "@?0";
8148
8149 // Argument types.
8150 ParmOffset = PtrSize;
8151 for (auto *PVDecl : Decl->parameters()) {
8152 QualType PType = PVDecl->getOriginalType();
8153 if (const auto *AT =
8154 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8155 // Use array's original type only if it has known number of
8156 // elements.
8157 if (!isa<ConstantArrayType>(AT))
8158 PType = PVDecl->getType();
8159 } else if (PType->isFunctionType())
8160 PType = PVDecl->getType();
8161 if (getLangOpts().EncodeExtendedBlockSig)
8163 S, true /*Extended*/);
8164 else
8165 getObjCEncodingForType(PType, S);
8166 S += charUnitsToString(ParmOffset);
8167 ParmOffset += getObjCEncodingTypeSize(PType);
8168 }
8169
8170 return S;
8171}
8172
8173std::string
8175 std::string S;
8176 // Encode result type.
8177 getObjCEncodingForType(Decl->getReturnType(), S);
8178 CharUnits ParmOffset;
8179 // Compute size of all parameters.
8180 for (auto *PI : Decl->parameters()) {
8181 QualType PType = PI->getType();
8183 if (sz.isZero())
8184 continue;
8185
8186 assert(sz.isPositive() &&
8187 "getObjCEncodingForFunctionDecl - Incomplete param type");
8188 ParmOffset += sz;
8189 }
8190 S += charUnitsToString(ParmOffset);
8191 ParmOffset = CharUnits::Zero();
8192
8193 // Argument types.
8194 for (auto *PVDecl : Decl->parameters()) {
8195 QualType PType = PVDecl->getOriginalType();
8196 if (const auto *AT =
8197 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8198 // Use array's original type only if it has known number of
8199 // elements.
8200 if (!isa<ConstantArrayType>(AT))
8201 PType = PVDecl->getType();
8202 } else if (PType->isFunctionType())
8203 PType = PVDecl->getType();
8204 getObjCEncodingForType(PType, S);
8205 S += charUnitsToString(ParmOffset);
8206 ParmOffset += getObjCEncodingTypeSize(PType);
8207 }
8208
8209 return S;
8210}
8211
8212/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8213/// method parameter or return type. If Extended, include class names and
8214/// block object types.
8216 QualType T, std::string& S,
8217 bool Extended) const {
8218 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8220 // Encode parameter type.
8221 ObjCEncOptions Options = ObjCEncOptions()
8222 .setExpandPointedToStructures()
8223 .setExpandStructures()
8224 .setIsOutermostType();
8225 if (Extended)
8226 Options.setEncodeBlockParameters().setEncodeClassNames();
8227 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8228}
8229
8230/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8231/// declaration.
8233 bool Extended) const {
8234 // FIXME: This is not very efficient.
8235 // Encode return type.
8236 std::string S;
8237 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8238 Decl->getReturnType(), S, Extended);
8239 // Compute size of all parameters.
8240 // Start with computing size of a pointer in number of bytes.
8241 // FIXME: There might(should) be a better way of doing this computation!
8243 // The first two arguments (self and _cmd) are pointers; account for
8244 // their size.
8245 CharUnits ParmOffset = 2 * PtrSize;
8246 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8247 E = Decl->sel_param_end(); PI != E; ++PI) {
8248 QualType PType = (*PI)->getType();
8250 if (sz.isZero())
8251 continue;
8252
8253 assert(sz.isPositive() &&
8254 "getObjCEncodingForMethodDecl - Incomplete param type");
8255 ParmOffset += sz;
8256 }
8257 S += charUnitsToString(ParmOffset);
8258 S += "@0:";
8259 S += charUnitsToString(PtrSize);
8260
8261 // Argument types.
8262 ParmOffset = 2 * PtrSize;
8263 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8264 E = Decl->sel_param_end(); PI != E; ++PI) {
8265 const ParmVarDecl *PVDecl = *PI;
8266 QualType PType = PVDecl->getOriginalType();
8267 if (const auto *AT =
8268 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8269 // Use array's original type only if it has known number of
8270 // elements.
8271 if (!isa<ConstantArrayType>(AT))
8272 PType = PVDecl->getType();
8273 } else if (PType->isFunctionType())
8274 PType = PVDecl->getType();
8276 PType, S, Extended);
8277 S += charUnitsToString(ParmOffset);
8278 ParmOffset += getObjCEncodingTypeSize(PType);
8279 }
8280
8281 return S;
8282}
8283
8286 const ObjCPropertyDecl *PD,
8287 const Decl *Container) const {
8288 if (!Container)
8289 return nullptr;
8290 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8291 for (auto *PID : CID->property_impls())
8292 if (PID->getPropertyDecl() == PD)
8293 return PID;
8294 } else {
8295 const auto *OID = cast<ObjCImplementationDecl>(Container);
8296 for (auto *PID : OID->property_impls())
8297 if (PID->getPropertyDecl() == PD)
8298 return PID;
8299 }
8300 return nullptr;
8301}
8302
8303/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8304/// property declaration. If non-NULL, Container must be either an
8305/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8306/// NULL when getting encodings for protocol properties.
8307/// Property attributes are stored as a comma-delimited C string. The simple
8308/// attributes readonly and bycopy are encoded as single characters. The
8309/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8310/// encoded as single characters, followed by an identifier. Property types
8311/// are also encoded as a parametrized attribute. The characters used to encode
8312/// these attributes are defined by the following enumeration:
8313/// @code
8314/// enum PropertyAttributes {
8315/// kPropertyReadOnly = 'R', // property is read-only.
8316/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8317/// kPropertyByref = '&', // property is a reference to the value last assigned
8318/// kPropertyDynamic = 'D', // property is dynamic
8319/// kPropertyGetter = 'G', // followed by getter selector name
8320/// kPropertySetter = 'S', // followed by setter selector name
8321/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8322/// kPropertyType = 'T' // followed by old-style type encoding.
8323/// kPropertyWeak = 'W' // 'weak' property
8324/// kPropertyStrong = 'P' // property GC'able
8325/// kPropertyNonAtomic = 'N' // property non-atomic
8326/// kPropertyOptional = '?' // property optional
8327/// };
8328/// @endcode
8329std::string
8331 const Decl *Container) const {
8332 // Collect information from the property implementation decl(s).
8333 bool Dynamic = false;
8334 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8335
8336 if (ObjCPropertyImplDecl *PropertyImpDecl =
8338 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8339 Dynamic = true;
8340 else
8341 SynthesizePID = PropertyImpDecl;
8342 }
8343
8344 // FIXME: This is not very efficient.
8345 std::string S = "T";
8346
8347 // Encode result type.
8348 // GCC has some special rules regarding encoding of properties which
8349 // closely resembles encoding of ivars.
8351
8352 if (PD->isOptional())
8353 S += ",?";
8354
8355 if (PD->isReadOnly()) {
8356 S += ",R";
8358 S += ",C";
8360 S += ",&";
8362 S += ",W";
8363 } else {
8364 switch (PD->getSetterKind()) {
8365 case ObjCPropertyDecl::Assign: break;
8366 case ObjCPropertyDecl::Copy: S += ",C"; break;
8367 case ObjCPropertyDecl::Retain: S += ",&"; break;
8368 case ObjCPropertyDecl::Weak: S += ",W"; break;
8369 }
8370 }
8371
8372 // It really isn't clear at all what this means, since properties
8373 // are "dynamic by default".
8374 if (Dynamic)
8375 S += ",D";
8376
8378 S += ",N";
8379
8381 S += ",G";
8382 S += PD->getGetterName().getAsString();
8383 }
8384
8386 S += ",S";
8387 S += PD->getSetterName().getAsString();
8388 }
8389
8390 if (SynthesizePID) {
8391 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
8392 S += ",V";
8393 S += OID->getNameAsString();
8394 }
8395
8396 // FIXME: OBJCGC: weak & strong
8397 return S;
8398}
8399
8400/// getLegacyIntegralTypeEncoding -
8401/// Another legacy compatibility encoding: 32-bit longs are encoded as
8402/// 'l' or 'L' , but not always. For typedefs, we need to use
8403/// 'i' or 'I' instead if encoding a struct field, or a pointer!
8405 if (PointeeTy->getAs<TypedefType>()) {
8406 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
8407 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
8408 PointeeTy = UnsignedIntTy;
8409 else
8410 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
8411 PointeeTy = IntTy;
8412 }
8413 }
8414}
8415
8417 const FieldDecl *Field,
8418 QualType *NotEncodedT) const {
8419 // We follow the behavior of gcc, expanding structures which are
8420 // directly pointed to, and expanding embedded structures. Note that
8421 // these rules are sufficient to prevent recursive encoding of the
8422 // same type.
8423 getObjCEncodingForTypeImpl(T, S,
8424 ObjCEncOptions()
8425 .setExpandPointedToStructures()
8426 .setExpandStructures()
8427 .setIsOutermostType(),
8428 Field, NotEncodedT);
8429}
8430
8432 std::string& S) const {
8433 // Encode result type.
8434 // GCC has some special rules regarding encoding of properties which
8435 // closely resembles encoding of ivars.
8436 getObjCEncodingForTypeImpl(T, S,
8437 ObjCEncOptions()
8438 .setExpandPointedToStructures()
8439 .setExpandStructures()
8440 .setIsOutermostType()
8441 .setEncodingProperty(),
8442 /*Field=*/nullptr);
8443}
8444
8446 const BuiltinType *BT) {
8447 BuiltinType::Kind kind = BT->getKind();
8448 switch (kind) {
8449 case BuiltinType::Void: return 'v';
8450 case BuiltinType::Bool: return 'B';
8451 case BuiltinType::Char8:
8452 case BuiltinType::Char_U:
8453 case BuiltinType::UChar: return 'C';
8454 case BuiltinType::Char16:
8455 case BuiltinType::UShort: return 'S';
8456 case BuiltinType::Char32:
8457 case BuiltinType::UInt: return 'I';
8458 case BuiltinType::ULong:
8459 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
8460 case BuiltinType::UInt128: return 'T';
8461 case BuiltinType::ULongLong: return 'Q';
8462 case BuiltinType::Char_S:
8463 case BuiltinType::SChar: return 'c';
8464 case BuiltinType::Short: return 's';
8465 case BuiltinType::WChar_S:
8466 case BuiltinType::WChar_U:
8467 case BuiltinType::Int: return 'i';
8468 case BuiltinType::Long:
8469 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
8470 case BuiltinType::LongLong: return 'q';
8471 case BuiltinType::Int128: return 't';
8472 case BuiltinType::Float: return 'f';
8473 case BuiltinType::Double: return 'd';
8474 case BuiltinType::LongDouble: return 'D';
8475 case BuiltinType::NullPtr: return '*'; // like char*
8476
8477 case BuiltinType::BFloat16:
8478 case BuiltinType::Float16:
8479 case BuiltinType::Float128:
8480 case BuiltinType::Ibm128:
8481 case BuiltinType::Half:
8482 case BuiltinType::ShortAccum:
8483 case BuiltinType::Accum:
8484 case BuiltinType::LongAccum:
8485 case BuiltinType::UShortAccum:
8486 case BuiltinType::UAccum:
8487 case BuiltinType::ULongAccum:
8488 case BuiltinType::ShortFract:
8489 case BuiltinType::Fract:
8490 case BuiltinType::LongFract:
8491 case BuiltinType::UShortFract:
8492 case BuiltinType::UFract:
8493 case BuiltinType::ULongFract:
8494 case BuiltinType::SatShortAccum:
8495 case BuiltinType::SatAccum:
8496 case BuiltinType::SatLongAccum:
8497 case BuiltinType::SatUShortAccum:
8498 case BuiltinType::SatUAccum:
8499 case BuiltinType::SatULongAccum:
8500 case BuiltinType::SatShortFract:
8501 case BuiltinType::SatFract:
8502 case BuiltinType::SatLongFract:
8503 case BuiltinType::SatUShortFract:
8504 case BuiltinType::SatUFract:
8505 case BuiltinType::SatULongFract:
8506 // FIXME: potentially need @encodes for these!
8507 return ' ';
8508
8509#define SVE_TYPE(Name, Id, SingletonId) \
8510 case BuiltinType::Id:
8511#include "clang/Basic/AArch64SVEACLETypes.def"
8512#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8513#include "clang/Basic/RISCVVTypes.def"
8514#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8515#include "clang/Basic/WebAssemblyReferenceTypes.def"
8516#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8517#include "clang/Basic/AMDGPUTypes.def"
8518 {
8519 DiagnosticsEngine &Diags = C->getDiagnostics();
8520 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
8521 "cannot yet @encode type %0");
8522 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
8523 return ' ';
8524 }
8525
8526 case BuiltinType::ObjCId:
8527 case BuiltinType::ObjCClass:
8528 case BuiltinType::ObjCSel:
8529 llvm_unreachable("@encoding ObjC primitive type");
8530
8531 // OpenCL and placeholder types don't need @encodings.
8532#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8533 case BuiltinType::Id:
8534#include "clang/Basic/OpenCLImageTypes.def"
8535#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8536 case BuiltinType::Id:
8537#include "clang/Basic/OpenCLExtensionTypes.def"
8538 case BuiltinType::OCLEvent:
8539 case BuiltinType::OCLClkEvent:
8540 case BuiltinType::OCLQueue:
8541 case BuiltinType::OCLReserveID:
8542 case BuiltinType::OCLSampler:
8543 case BuiltinType::Dependent:
8544#define PPC_VECTOR_TYPE(Name, Id, Size) \
8545 case BuiltinType::Id:
8546#include "clang/Basic/PPCTypes.def"
8547#define BUILTIN_TYPE(KIND, ID)
8548#define PLACEHOLDER_TYPE(KIND, ID) \
8549 case BuiltinType::KIND:
8550#include "clang/AST/BuiltinTypes.def"
8551 llvm_unreachable("invalid builtin type for @encode");
8552 }
8553 llvm_unreachable("invalid BuiltinType::Kind value");
8554}
8555
8556static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
8557 EnumDecl *Enum = ET->getDecl();
8558
8559 // The encoding of an non-fixed enum type is always 'i', regardless of size.
8560 if (!Enum->isFixed())
8561 return 'i';
8562
8563 // The encoding of a fixed enum type matches its fixed underlying type.
8564 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
8566}
8567
8568static void EncodeBitField(const ASTContext *Ctx, std::string& S,
8569 QualType T, const FieldDecl *FD) {
8570 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
8571 S += 'b';
8572 // The NeXT runtime encodes bit fields as b followed by the number of bits.
8573 // The GNU runtime requires more information; bitfields are encoded as b,
8574 // then the offset (in bits) of the first element, then the type of the
8575 // bitfield, then the size in bits. For example, in this structure:
8576 //
8577 // struct
8578 // {
8579 // int integer;
8580 // int flags:2;
8581 // };
8582 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
8583 // runtime, but b32i2 for the GNU runtime. The reason for this extra
8584 // information is not especially sensible, but we're stuck with it for
8585 // compatibility with GCC, although providing it breaks anything that
8586 // actually uses runtime introspection and wants to work on both runtimes...
8587 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
8588 uint64_t Offset;
8589
8590 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
8591 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
8592 IVD);
8593 } else {
8594 const RecordDecl *RD = FD->getParent();
8595 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
8596 Offset = RL.getFieldOffset(FD->getFieldIndex());
8597 }
8598
8599 S += llvm::utostr(Offset);
8600
8601 if (const auto *ET = T->getAs<EnumType>())
8602 S += ObjCEncodingForEnumType(Ctx, ET);
8603 else {
8604 const auto *BT = T->castAs<BuiltinType>();
8605 S += getObjCEncodingForPrimitiveType(Ctx, BT);
8606 }
8607 }
8608 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
8609}
8610
8611// Helper function for determining whether the encoded type string would include
8612// a template specialization type.
8614 bool VisitBasesAndFields) {
8616
8617 if (auto *PT = T->getAs<PointerType>())
8619 PT->getPointeeType().getTypePtr(), false);
8620
8621 auto *CXXRD = T->getAsCXXRecordDecl();
8622
8623 if (!CXXRD)
8624 return false;
8625
8626 if (isa<ClassTemplateSpecializationDecl>(CXXRD))
8627 return true;
8628
8629 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
8630 return false;
8631
8632 for (const auto &B : CXXRD->bases())
8633 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
8634 true))
8635 return true;
8636
8637 for (auto *FD : CXXRD->fields())
8638 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
8639 true))
8640 return true;
8641
8642 return false;
8643}
8644
8645// FIXME: Use SmallString for accumulating string.
8646void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
8647 const ObjCEncOptions Options,
8648 const FieldDecl *FD,
8649 QualType *NotEncodedT) const {
8651 switch (CT->getTypeClass()) {
8652 case Type::Builtin:
8653 case Type::Enum:
8654 if (FD && FD->isBitField())
8655 return EncodeBitField(this, S, T, FD);
8656 if (const auto *BT = dyn_cast<BuiltinType>(CT))
8657 S += getObjCEncodingForPrimitiveType(this, BT);
8658 else
8659 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
8660 return;
8661
8662 case Type::Complex:
8663 S += 'j';
8664 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
8665 ObjCEncOptions(),
8666 /*Field=*/nullptr);
8667 return;
8668
8669 case Type::Atomic:
8670 S += 'A';
8671 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
8672 ObjCEncOptions(),
8673 /*Field=*/nullptr);
8674 return;
8675
8676 // encoding for pointer or reference types.
8677 case Type::Pointer:
8678 case Type::LValueReference:
8679 case Type::RValueReference: {
8680 QualType PointeeTy;
8681 if (isa<PointerType>(CT)) {
8682 const auto *PT = T->castAs<PointerType>();
8683 if (PT->isObjCSelType()) {
8684 S += ':';
8685 return;
8686 }
8687 PointeeTy = PT->getPointeeType();
8688 } else {
8689 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8690 }
8691
8692 bool isReadOnly = false;
8693 // For historical/compatibility reasons, the read-only qualifier of the
8694 // pointee gets emitted _before_ the '^'. The read-only qualifier of
8695 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8696 // Also, do not emit the 'r' for anything but the outermost type!
8697 if (T->getAs<TypedefType>()) {
8698 if (Options.IsOutermostType() && T.isConstQualified()) {
8699 isReadOnly = true;
8700 S += 'r';
8701 }
8702 } else if (Options.IsOutermostType()) {
8703 QualType P = PointeeTy;
8704 while (auto PT = P->getAs<PointerType>())
8705 P = PT->getPointeeType();
8706 if (P.isConstQualified()) {
8707 isReadOnly = true;
8708 S += 'r';
8709 }
8710 }
8711 if (isReadOnly) {
8712 // Another legacy compatibility encoding. Some ObjC qualifier and type
8713 // combinations need to be rearranged.
8714 // Rewrite "in const" from "nr" to "rn"
8715 if (StringRef(S).ends_with("nr"))
8716 S.replace(S.end()-2, S.end(), "rn");
8717 }
8718
8719 if (PointeeTy->isCharType()) {
8720 // char pointer types should be encoded as '*' unless it is a
8721 // type that has been typedef'd to 'BOOL'.
8722 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
8723 S += '*';
8724 return;
8725 }
8726 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
8727 // GCC binary compat: Need to convert "struct objc_class *" to "#".
8728 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
8729 S += '#';
8730 return;
8731 }
8732 // GCC binary compat: Need to convert "struct objc_object *" to "@".
8733 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
8734 S += '@';
8735 return;
8736 }
8737 // If the encoded string for the class includes template names, just emit
8738 // "^v" for pointers to the class.
8739 if (getLangOpts().CPlusPlus &&
8740 (!getLangOpts().EncodeCXXClassTemplateSpec &&
8742 RTy, Options.ExpandPointedToStructures()))) {
8743 S += "^v";
8744 return;
8745 }
8746 // fall through...
8747 }
8748 S += '^';
8750
8751 ObjCEncOptions NewOptions;
8752 if (Options.ExpandPointedToStructures())
8753 NewOptions.setExpandStructures();
8754 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
8755 /*Field=*/nullptr, NotEncodedT);
8756 return;
8757 }
8758
8759 case Type::ConstantArray:
8760 case Type::IncompleteArray:
8761 case Type::VariableArray: {
8762 const auto *AT = cast<ArrayType>(CT);
8763
8764 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
8765 // Incomplete arrays are encoded as a pointer to the array element.
8766 S += '^';
8767
8768 getObjCEncodingForTypeImpl(
8769 AT->getElementType(), S,
8770 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
8771 } else {
8772 S += '[';
8773
8774 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
8775 S += llvm::utostr(CAT->getZExtSize());
8776 else {
8777 //Variable length arrays are encoded as a regular array with 0 elements.
8778 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
8779 "Unknown array type!");
8780 S += '0';
8781 }
8782
8783 getObjCEncodingForTypeImpl(
8784 AT->getElementType(), S,
8785 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
8786 NotEncodedT);
8787 S += ']';
8788 }
8789 return;
8790 }
8791
8792 case Type::FunctionNoProto:
8793 case Type::FunctionProto:
8794 S += '?';
8795 return;
8796
8797 case Type::Record: {
8798 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
8799 S += RDecl->isUnion() ? '(' : '{';
8800 // Anonymous structures print as '?'
8801 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
8802 S += II->getName();
8803 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
8804 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
8805 llvm::raw_string_ostream OS(S);
8806 printTemplateArgumentList(OS, TemplateArgs.asArray(),
8808 }
8809 } else {
8810 S += '?';
8811 }
8812 if (Options.ExpandStructures()) {
8813 S += '=';
8814 if (!RDecl->isUnion()) {
8815 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
8816 } else {
8817 for (const auto *Field : RDecl->fields()) {
8818 if (FD) {
8819 S += '"';
8820 S += Field->getNameAsString();
8821 S += '"';
8822 }
8823
8824 // Special case bit-fields.
8825 if (Field->isBitField()) {
8826 getObjCEncodingForTypeImpl(Field->getType(), S,
8827 ObjCEncOptions().setExpandStructures(),
8828 Field);
8829 } else {
8830 QualType qt = Field->getType();
8832 getObjCEncodingForTypeImpl(
8833 qt, S,
8834 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
8835 NotEncodedT);
8836 }
8837 }
8838 }
8839 }
8840 S += RDecl->isUnion() ? ')' : '}';
8841 return;
8842 }
8843
8844 case Type::BlockPointer: {
8845 const auto *BT = T->castAs<BlockPointerType>();
8846 S += "@?"; // Unlike a pointer-to-function, which is "^?".
8847 if (Options.EncodeBlockParameters()) {
8848 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
8849
8850 S += '<';
8851 // Block return type
8852 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
8853 Options.forComponentType(), FD, NotEncodedT);
8854 // Block self
8855 S += "@?";
8856 // Block parameters
8857 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
8858 for (const auto &I : FPT->param_types())
8859 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
8860 NotEncodedT);
8861 }
8862 S += '>';
8863 }
8864 return;
8865 }
8866
8867 case Type::ObjCObject: {
8868 // hack to match legacy encoding of *id and *Class
8870 if (Ty->isObjCIdType()) {
8871 S += "{objc_object=}";
8872 return;
8873 }
8874 else if (Ty->isObjCClassType()) {
8875 S += "{objc_class=}";
8876 return;
8877 }
8878 // TODO: Double check to make sure this intentionally falls through.
8879 [[fallthrough]];
8880 }
8881
8882 case Type::ObjCInterface: {
8883 // Ignore protocol qualifiers when mangling at this level.
8884 // @encode(class_name)
8885 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
8886 S += '{';
8887 S += OI->getObjCRuntimeNameAsString();
8888 if (Options.ExpandStructures()) {
8889 S += '=';
8891 DeepCollectObjCIvars(OI, true, Ivars);
8892 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
8893 const FieldDecl *Field = Ivars[i];
8894 if (Field->isBitField())
8895 getObjCEncodingForTypeImpl(Field->getType(), S,
8896 ObjCEncOptions().setExpandStructures(),
8897 Field);
8898 else
8899 getObjCEncodingForTypeImpl(Field->getType(), S,
8900 ObjCEncOptions().setExpandStructures(), FD,
8901 NotEncodedT);
8902 }
8903 }
8904 S += '}';
8905 return;
8906 }
8907
8908 case Type::ObjCObjectPointer: {
8909 const auto *OPT = T->castAs<ObjCObjectPointerType>();
8910 if (OPT->isObjCIdType()) {
8911 S += '@';
8912 return;
8913 }
8914
8915 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
8916 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
8917 // Since this is a binary compatibility issue, need to consult with
8918 // runtime folks. Fortunately, this is a *very* obscure construct.
8919 S += '#';
8920 return;
8921 }
8922
8923 if (OPT->isObjCQualifiedIdType()) {
8924 getObjCEncodingForTypeImpl(
8925 getObjCIdType(), S,
8926 Options.keepingOnly(ObjCEncOptions()
8927 .setExpandPointedToStructures()
8928 .setExpandStructures()),
8929 FD);
8930 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
8931 // Note that we do extended encoding of protocol qualifier list
8932 // Only when doing ivar or property encoding.
8933 S += '"';
8934 for (const auto *I : OPT->quals()) {
8935 S += '<';
8936 S += I->getObjCRuntimeNameAsString();
8937 S += '>';
8938 }
8939 S += '"';
8940 }
8941 return;
8942 }
8943
8944 S += '@';
8945 if (OPT->getInterfaceDecl() &&
8946 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
8947 S += '"';
8948 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
8949 for (const auto *I : OPT->quals()) {
8950 S += '<';
8951 S += I->getObjCRuntimeNameAsString();
8952 S += '>';
8953 }
8954 S += '"';
8955 }
8956 return;
8957 }
8958
8959 // gcc just blithely ignores member pointers.
8960 // FIXME: we should do better than that. 'M' is available.
8961 case Type::MemberPointer:
8962 // This matches gcc's encoding, even though technically it is insufficient.
8963 //FIXME. We should do a better job than gcc.
8964 case Type::Vector:
8965 case Type::ExtVector:
8966 // Until we have a coherent encoding of these three types, issue warning.
8967 if (NotEncodedT)
8968 *NotEncodedT = T;
8969 return;
8970
8971 case Type::ConstantMatrix:
8972 if (NotEncodedT)
8973 *NotEncodedT = T;
8974 return;
8975
8976 case Type::BitInt:
8977 if (NotEncodedT)
8978 *NotEncodedT = T;
8979 return;
8980
8981 // We could see an undeduced auto type here during error recovery.
8982 // Just ignore it.
8983 case Type::Auto:
8984 case Type::DeducedTemplateSpecialization:
8985 return;
8986
8987 case Type::ArrayParameter:
8988 case Type::Pipe:
8989#define ABSTRACT_TYPE(KIND, BASE)
8990#define TYPE(KIND, BASE)
8991#define DEPENDENT_TYPE(KIND, BASE) \
8992 case Type::KIND:
8993#define NON_CANONICAL_TYPE(KIND, BASE) \
8994 case Type::KIND:
8995#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
8996 case Type::KIND:
8997#include "clang/AST/TypeNodes.inc"
8998 llvm_unreachable("@encode for dependent type!");
8999 }
9000 llvm_unreachable("bad type kind!");
9001}
9002
9003void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9004 std::string &S,
9005 const FieldDecl *FD,
9006 bool includeVBases,
9007 QualType *NotEncodedT) const {
9008 assert(RDecl && "Expected non-null RecordDecl");
9009 assert(!RDecl->isUnion() && "Should not be called for unions");
9010 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9011 return;
9012
9013 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9014 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9015 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9016
9017 if (CXXRec) {
9018 for (const auto &BI : CXXRec->bases()) {
9019 if (!BI.isVirtual()) {
9020 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9021 if (base->isEmpty())
9022 continue;
9023 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9024 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9025 std::make_pair(offs, base));
9026 }
9027 }
9028 }
9029
9030 for (FieldDecl *Field : RDecl->fields()) {
9031 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
9032 continue;
9033 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9034 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9035 std::make_pair(offs, Field));
9036 }
9037
9038 if (CXXRec && includeVBases) {
9039 for (const auto &BI : CXXRec->vbases()) {
9040 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9041 if (base->isEmpty())
9042 continue;
9043 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9044 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9045 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9046 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9047 std::make_pair(offs, base));
9048 }
9049 }
9050
9051 CharUnits size;
9052 if (CXXRec) {
9053 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9054 } else {
9055 size = layout.getSize();
9056 }
9057
9058#ifndef NDEBUG
9059 uint64_t CurOffs = 0;
9060#endif
9061 std::multimap<uint64_t, NamedDecl *>::iterator
9062 CurLayObj = FieldOrBaseOffsets.begin();
9063
9064 if (CXXRec && CXXRec->isDynamicClass() &&
9065 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9066 if (FD) {
9067 S += "\"_vptr$";
9068 std::string recname = CXXRec->getNameAsString();
9069 if (recname.empty()) recname = "?";
9070 S += recname;
9071 S += '"';
9072 }
9073 S += "^^?";
9074#ifndef NDEBUG
9075 CurOffs += getTypeSize(VoidPtrTy);
9076#endif
9077 }
9078
9079 if (!RDecl->hasFlexibleArrayMember()) {
9080 // Mark the end of the structure.
9081 uint64_t offs = toBits(size);
9082 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9083 std::make_pair(offs, nullptr));
9084 }
9085
9086 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9087#ifndef NDEBUG
9088 assert(CurOffs <= CurLayObj->first);
9089 if (CurOffs < CurLayObj->first) {
9090 uint64_t padding = CurLayObj->first - CurOffs;
9091 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9092 // packing/alignment of members is different that normal, in which case
9093 // the encoding will be out-of-sync with the real layout.
9094 // If the runtime switches to just consider the size of types without
9095 // taking into account alignment, we could make padding explicit in the
9096 // encoding (e.g. using arrays of chars). The encoding strings would be
9097 // longer then though.
9098 CurOffs += padding;
9099 }
9100#endif
9101
9102 NamedDecl *dcl = CurLayObj->second;
9103 if (!dcl)
9104 break; // reached end of structure.
9105
9106 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9107 // We expand the bases without their virtual bases since those are going
9108 // in the initial structure. Note that this differs from gcc which
9109 // expands virtual bases each time one is encountered in the hierarchy,
9110 // making the encoding type bigger than it really is.
9111 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9112 NotEncodedT);
9113 assert(!base->isEmpty());
9114#ifndef NDEBUG
9115 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9116#endif
9117 } else {
9118 const auto *field = cast<FieldDecl>(dcl);
9119 if (FD) {
9120 S += '"';
9121 S += field->getNameAsString();
9122 S += '"';
9123 }
9124
9125 if (field->isBitField()) {
9126 EncodeBitField(this, S, field->getType(), field);
9127#ifndef NDEBUG
9128 CurOffs += field->getBitWidthValue(*this);
9129#endif
9130 } else {
9131 QualType qt = field->getType();
9133 getObjCEncodingForTypeImpl(
9134 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9135 FD, NotEncodedT);
9136#ifndef NDEBUG
9137 CurOffs += getTypeSize(field->getType());
9138#endif
9139 }
9140 }
9141 }
9142}
9143
9145 std::string& S) const {
9146 if (QT & Decl::OBJC_TQ_In)
9147 S += 'n';
9148 if (QT & Decl::OBJC_TQ_Inout)
9149 S += 'N';
9150 if (QT & Decl::OBJC_TQ_Out)
9151 S += 'o';
9152 if (QT & Decl::OBJC_TQ_Bycopy)
9153 S += 'O';
9154 if (QT & Decl::OBJC_TQ_Byref)
9155 S += 'R';
9156 if (QT & Decl::OBJC_TQ_Oneway)
9157 S += 'V';
9158}
9159
9161 if (!ObjCIdDecl) {
9164 ObjCIdDecl = buildImplicitTypedef(T, "id");
9165 }
9166 return ObjCIdDecl;
9167}
9168
9170 if (!ObjCSelDecl) {
9172 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9173 }
9174 return ObjCSelDecl;
9175}
9176
9178 if (!ObjCClassDecl) {
9181 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9182 }
9183 return ObjCClassDecl;
9184}
9185
9187 if (!ObjCProtocolClassDecl) {
9188 ObjCProtocolClassDecl
9191 &Idents.get("Protocol"),
9192 /*typeParamList=*/nullptr,
9193 /*PrevDecl=*/nullptr,
9194 SourceLocation(), true);
9195 }
9196
9197 return ObjCProtocolClassDecl;
9198}
9199
9200//===----------------------------------------------------------------------===//
9201// __builtin_va_list Construction Functions
9202//===----------------------------------------------------------------------===//
9203
9205 StringRef Name) {
9206 // typedef char* __builtin[_ms]_va_list;
9207 QualType T = Context->getPointerType(Context->CharTy);
9208 return Context->buildImplicitTypedef(T, Name);
9209}
9210
9212 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9213}
9214
9216 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9217}
9218
9220 // typedef void* __builtin_va_list;
9221 QualType T = Context->getPointerType(Context->VoidTy);
9222 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9223}
9224
9225static TypedefDecl *
9227 // struct __va_list
9228 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9229 if (Context->getLangOpts().CPlusPlus) {
9230 // namespace std { struct __va_list {
9231 auto *NS = NamespaceDecl::Create(
9232 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9233 /*Inline=*/false, SourceLocation(), SourceLocation(),
9234 &Context->Idents.get("std"),
9235 /*PrevDecl=*/nullptr, /*Nested=*/false);
9236 NS->setImplicit();
9237 VaListTagDecl->setDeclContext(NS);
9238 }
9239
9240 VaListTagDecl->startDefinition();
9241
9242 const size_t NumFields = 5;
9243 QualType FieldTypes[NumFields];
9244 const char *FieldNames[NumFields];
9245
9246 // void *__stack;
9247 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9248 FieldNames[0] = "__stack";
9249
9250 // void *__gr_top;
9251 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9252 FieldNames[1] = "__gr_top";
9253
9254 // void *__vr_top;
9255 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9256 FieldNames[2] = "__vr_top";
9257
9258 // int __gr_offs;
9259 FieldTypes[3] = Context->IntTy;
9260 FieldNames[3] = "__gr_offs";
9261
9262 // int __vr_offs;
9263 FieldTypes[4] = Context->IntTy;
9264 FieldNames[4] = "__vr_offs";
9265
9266 // Create fields
9267 for (unsigned i = 0; i < NumFields; ++i) {
9268 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9269 VaListTagDecl,
9272 &Context->Idents.get(FieldNames[i]),
9273 FieldTypes[i], /*TInfo=*/nullptr,
9274 /*BitWidth=*/nullptr,
9275 /*Mutable=*/false,
9276 ICIS_NoInit);
9277 Field->setAccess(AS_public);
9278 VaListTagDecl->addDecl(Field);
9279 }
9280 VaListTagDecl->completeDefinition();
9281 Context->VaListTagDecl = VaListTagDecl;
9282 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9283
9284 // } __builtin_va_list;
9285 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9286}
9287
9289 // typedef struct __va_list_tag {
9290 RecordDecl *VaListTagDecl;
9291
9292 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9293 VaListTagDecl->startDefinition();
9294
9295 const size_t NumFields = 5;
9296 QualType FieldTypes[NumFields];
9297 const char *FieldNames[NumFields];
9298
9299 // unsigned char gpr;
9300 FieldTypes[0] = Context->UnsignedCharTy;
9301 FieldNames[0] = "gpr";
9302
9303 // unsigned char fpr;
9304 FieldTypes[1] = Context->UnsignedCharTy;
9305 FieldNames[1] = "fpr";
9306
9307 // unsigned short reserved;
9308 FieldTypes[2] = Context->UnsignedShortTy;
9309 FieldNames[2] = "reserved";
9310
9311 // void* overflow_arg_area;
9312 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9313 FieldNames[3] = "overflow_arg_area";
9314
9315 // void* reg_save_area;
9316 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9317 FieldNames[4] = "reg_save_area";
9318
9319 // Create fields
9320 for (unsigned i = 0; i < NumFields; ++i) {
9321 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9324 &Context->Idents.get(FieldNames[i]),
9325 FieldTypes[i], /*TInfo=*/nullptr,
9326 /*BitWidth=*/nullptr,
9327 /*Mutable=*/false,
9328 ICIS_NoInit);
9329 Field->setAccess(AS_public);
9330 VaListTagDecl->addDecl(Field);
9331 }
9332 VaListTagDecl->completeDefinition();
9333 Context->VaListTagDecl = VaListTagDecl;
9334 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9335
9336 // } __va_list_tag;
9337 TypedefDecl *VaListTagTypedefDecl =
9338 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9339
9340 QualType VaListTagTypedefType =
9341 Context->getTypedefType(VaListTagTypedefDecl);
9342
9343 // typedef __va_list_tag __builtin_va_list[1];
9344 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9345 QualType VaListTagArrayType = Context->getConstantArrayType(
9346 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9347 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9348}
9349
9350static TypedefDecl *
9352 // struct __va_list_tag {
9353 RecordDecl *VaListTagDecl;
9354 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9355 VaListTagDecl->startDefinition();
9356
9357 const size_t NumFields = 4;
9358 QualType FieldTypes[NumFields];
9359 const char *FieldNames[NumFields];
9360
9361 // unsigned gp_offset;
9362 FieldTypes[0] = Context->UnsignedIntTy;
9363 FieldNames[0] = "gp_offset";
9364
9365 // unsigned fp_offset;
9366 FieldTypes[1] = Context->UnsignedIntTy;
9367 FieldNames[1] = "fp_offset";
9368
9369 // void* overflow_arg_area;
9370 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9371 FieldNames[2] = "overflow_arg_area";
9372
9373 // void* reg_save_area;
9374 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9375 FieldNames[3] = "reg_save_area";
9376
9377 // Create fields
9378 for (unsigned i = 0; i < NumFields; ++i) {
9379 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9380 VaListTagDecl,
9383 &Context->Idents.get(FieldNames[i]),
9384 FieldTypes[i], /*TInfo=*/nullptr,
9385 /*BitWidth=*/nullptr,
9386 /*Mutable=*/false,
9387 ICIS_NoInit);
9388 Field->setAccess(AS_public);
9389 VaListTagDecl->addDecl(Field);
9390 }
9391 VaListTagDecl->completeDefinition();
9392 Context->VaListTagDecl = VaListTagDecl;
9393 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9394
9395 // };
9396
9397 // typedef struct __va_list_tag __builtin_va_list[1];
9398 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9399 QualType VaListTagArrayType = Context->getConstantArrayType(
9400 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9401 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9402}
9403
9405 // typedef int __builtin_va_list[4];
9406 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
9407 QualType IntArrayType = Context->getConstantArrayType(
9408 Context->IntTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9409 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
9410}
9411
9412static TypedefDecl *
9414 // struct __va_list
9415 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
9416 if (Context->getLangOpts().CPlusPlus) {
9417 // namespace std { struct __va_list {
9418 NamespaceDecl *NS;
9419 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
9420 Context->getTranslationUnitDecl(),
9421 /*Inline=*/false, SourceLocation(),
9422 SourceLocation(), &Context->Idents.get("std"),
9423 /*PrevDecl=*/nullptr, /*Nested=*/false);
9424 NS->setImplicit();
9425 VaListDecl->setDeclContext(NS);
9426 }
9427
9428 VaListDecl->startDefinition();
9429
9430 // void * __ap;
9431 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9432 VaListDecl,
9435 &Context->Idents.get("__ap"),
9436 Context->getPointerType(Context->VoidTy),
9437 /*TInfo=*/nullptr,
9438 /*BitWidth=*/nullptr,
9439 /*Mutable=*/false,
9440 ICIS_NoInit);
9441 Field->setAccess(AS_public);
9442 VaListDecl->addDecl(Field);
9443
9444 // };
9445 VaListDecl->completeDefinition();
9446 Context->VaListTagDecl = VaListDecl;
9447
9448 // typedef struct __va_list __builtin_va_list;
9449 QualType T = Context->getRecordType(VaListDecl);
9450 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9451}
9452
9453static TypedefDecl *
9455 // struct __va_list_tag {
9456 RecordDecl *VaListTagDecl;
9457 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9458 VaListTagDecl->startDefinition();
9459
9460 const size_t NumFields = 4;
9461 QualType FieldTypes[NumFields];
9462 const char *FieldNames[NumFields];
9463
9464 // long __gpr;
9465 FieldTypes[0] = Context->LongTy;
9466 FieldNames[0] = "__gpr";
9467
9468 // long __fpr;
9469 FieldTypes[1] = Context->LongTy;
9470 FieldNames[1] = "__fpr";
9471
9472 // void *__overflow_arg_area;
9473 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9474 FieldNames[2] = "__overflow_arg_area";
9475
9476 // void *__reg_save_area;
9477 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9478 FieldNames[3] = "__reg_save_area";
9479
9480 // Create fields
9481 for (unsigned i = 0; i < NumFields; ++i) {
9482 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9483 VaListTagDecl,
9486 &Context->Idents.get(FieldNames[i]),
9487 FieldTypes[i], /*TInfo=*/nullptr,
9488 /*BitWidth=*/nullptr,
9489 /*Mutable=*/false,
9490 ICIS_NoInit);
9491 Field->setAccess(AS_public);
9492 VaListTagDecl->addDecl(Field);
9493 }
9494 VaListTagDecl->completeDefinition();
9495 Context->VaListTagDecl = VaListTagDecl;
9496 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9497
9498 // };
9499
9500 // typedef __va_list_tag __builtin_va_list[1];
9501 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9502 QualType VaListTagArrayType = Context->getConstantArrayType(
9503 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9504
9505 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9506}
9507
9509 // typedef struct __va_list_tag {
9510 RecordDecl *VaListTagDecl;
9511 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9512 VaListTagDecl->startDefinition();
9513
9514 const size_t NumFields = 3;
9515 QualType FieldTypes[NumFields];
9516 const char *FieldNames[NumFields];
9517
9518 // void *CurrentSavedRegisterArea;
9519 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9520 FieldNames[0] = "__current_saved_reg_area_pointer";
9521
9522 // void *SavedRegAreaEnd;
9523 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9524 FieldNames[1] = "__saved_reg_area_end_pointer";
9525
9526 // void *OverflowArea;
9527 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9528 FieldNames[2] = "__overflow_area_pointer";
9529
9530 // Create fields
9531 for (unsigned i = 0; i < NumFields; ++i) {
9533 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
9534 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
9535 /*TInfo=*/nullptr,
9536 /*BitWidth=*/nullptr,
9537 /*Mutable=*/false, ICIS_NoInit);
9538 Field->setAccess(AS_public);
9539 VaListTagDecl->addDecl(Field);
9540 }
9541 VaListTagDecl->completeDefinition();
9542 Context->VaListTagDecl = VaListTagDecl;
9543 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9544
9545 // } __va_list_tag;
9546 TypedefDecl *VaListTagTypedefDecl =
9547 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9548
9549 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
9550
9551 // typedef __va_list_tag __builtin_va_list[1];
9552 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9553 QualType VaListTagArrayType = Context->getConstantArrayType(
9554 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9555
9556 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9557}
9558
9561 switch (Kind) {
9563 return CreateCharPtrBuiltinVaListDecl(Context);
9565 return CreateVoidPtrBuiltinVaListDecl(Context);
9567 return CreateAArch64ABIBuiltinVaListDecl(Context);
9569 return CreatePowerABIBuiltinVaListDecl(Context);
9571 return CreateX86_64ABIBuiltinVaListDecl(Context);
9573 return CreatePNaClABIBuiltinVaListDecl(Context);
9575 return CreateAAPCSABIBuiltinVaListDecl(Context);
9577 return CreateSystemZBuiltinVaListDecl(Context);
9579 return CreateHexagonBuiltinVaListDecl(Context);
9580 }
9581
9582 llvm_unreachable("Unhandled __builtin_va_list type kind");
9583}
9584
9586 if (!BuiltinVaListDecl) {
9587 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
9588 assert(BuiltinVaListDecl->isImplicit());
9589 }
9590
9591 return BuiltinVaListDecl;
9592}
9593
9595 // Force the creation of VaListTagDecl by building the __builtin_va_list
9596 // declaration.
9597 if (!VaListTagDecl)
9598 (void)getBuiltinVaListDecl();
9599
9600 return VaListTagDecl;
9601}
9602
9604 if (!BuiltinMSVaListDecl)
9605 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
9606
9607 return BuiltinMSVaListDecl;
9608}
9609
9611 // Allow redecl custom type checking builtin for HLSL.
9612 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
9614 return true;
9616}
9617
9619 assert(ObjCConstantStringType.isNull() &&
9620 "'NSConstantString' type already set!");
9621
9622 ObjCConstantStringType = getObjCInterfaceType(Decl);
9623}
9624
9625/// Retrieve the template name that corresponds to a non-empty
9626/// lookup.
9629 UnresolvedSetIterator End) const {
9630 unsigned size = End - Begin;
9631 assert(size > 1 && "set is not overloaded!");
9632
9633 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
9634 size * sizeof(FunctionTemplateDecl*));
9635 auto *OT = new (memory) OverloadedTemplateStorage(size);
9636
9637 NamedDecl **Storage = OT->getStorage();
9638 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
9639 NamedDecl *D = *I;
9640 assert(isa<FunctionTemplateDecl>(D) ||
9641 isa<UnresolvedUsingValueDecl>(D) ||
9642 (isa<UsingShadowDecl>(D) &&
9643 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
9644 *Storage++ = D;
9645 }
9646
9647 return TemplateName(OT);
9648}
9649
9650/// Retrieve a template name representing an unqualified-id that has been
9651/// assumed to name a template for ADL purposes.
9653 auto *OT = new (*this) AssumedTemplateStorage(Name);
9654 return TemplateName(OT);
9655}
9656
9657/// Retrieve the template name that represents a qualified
9658/// template name such as \c std::vector.
9660 bool TemplateKeyword,
9661 TemplateName Template) const {
9662 assert(Template.getKind() == TemplateName::Template ||
9663 Template.getKind() == TemplateName::UsingTemplate);
9664
9665 // FIXME: Canonicalization?
9666 llvm::FoldingSetNodeID ID;
9667 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
9668
9669 void *InsertPos = nullptr;
9671 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9672 if (!QTN) {
9673 QTN = new (*this, alignof(QualifiedTemplateName))
9674 QualifiedTemplateName(NNS, TemplateKeyword, Template);
9675 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
9676 }
9677
9678 return TemplateName(QTN);
9679}
9680
9681/// Retrieve the template name that represents a dependent
9682/// template name such as \c MetaFun::template apply.
9685 const IdentifierInfo *Name) const {
9686 assert((!NNS || NNS->isDependent()) &&
9687 "Nested name specifier must be dependent");
9688
9689 llvm::FoldingSetNodeID ID;
9690 DependentTemplateName::Profile(ID, NNS, Name);
9691
9692 void *InsertPos = nullptr;
9694 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9695
9696 if (QTN)
9697 return TemplateName(QTN);
9698
9700 if (CanonNNS == NNS) {
9701 QTN = new (*this, alignof(DependentTemplateName))
9702 DependentTemplateName(NNS, Name);
9703 } else {
9704 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
9705 QTN = new (*this, alignof(DependentTemplateName))
9706 DependentTemplateName(NNS, Name, Canon);
9707 DependentTemplateName *CheckQTN =
9708 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9709 assert(!CheckQTN && "Dependent type name canonicalization broken");
9710 (void)CheckQTN;
9711 }
9712
9713 DependentTemplateNames.InsertNode(QTN, InsertPos);
9714 return TemplateName(QTN);
9715}
9716
9717/// Retrieve the template name that represents a dependent
9718/// template name such as \c MetaFun::template operator+.
9721 OverloadedOperatorKind Operator) const {
9722 assert((!NNS || NNS->isDependent()) &&
9723 "Nested name specifier must be dependent");
9724
9725 llvm::FoldingSetNodeID ID;
9726 DependentTemplateName::Profile(ID, NNS, Operator);
9727
9728 void *InsertPos = nullptr;
9730 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9731
9732 if (QTN)
9733 return TemplateName(QTN);
9734
9736 if (CanonNNS == NNS) {
9737 QTN = new (*this, alignof(DependentTemplateName))
9738 DependentTemplateName(NNS, Operator);
9739 } else {
9740 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
9741 QTN = new (*this, alignof(DependentTemplateName))
9742 DependentTemplateName(NNS, Operator, Canon);
9743
9744 DependentTemplateName *CheckQTN
9745 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9746 assert(!CheckQTN && "Dependent template name canonicalization broken");
9747 (void)CheckQTN;
9748 }
9749
9750 DependentTemplateNames.InsertNode(QTN, InsertPos);
9751 return TemplateName(QTN);
9752}
9753
9755 TemplateName Replacement, Decl *AssociatedDecl, unsigned Index,
9756 std::optional<unsigned> PackIndex) const {
9757 llvm::FoldingSetNodeID ID;
9758 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
9759 Index, PackIndex);
9760
9761 void *insertPos = nullptr;
9763 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
9764
9765 if (!subst) {
9766 subst = new (*this) SubstTemplateTemplateParmStorage(
9767 Replacement, AssociatedDecl, Index, PackIndex);
9768 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
9769 }
9770
9771 return TemplateName(subst);
9772}
9773
9776 Decl *AssociatedDecl,
9777 unsigned Index, bool Final) const {
9778 auto &Self = const_cast<ASTContext &>(*this);
9779 llvm::FoldingSetNodeID ID;
9781 AssociatedDecl, Index, Final);
9782
9783 void *InsertPos = nullptr;
9785 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
9786
9787 if (!Subst) {
9788 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
9789 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
9790 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
9791 }
9792
9793 return TemplateName(Subst);
9794}
9795
9796/// getFromTargetType - Given one of the integer types provided by
9797/// TargetInfo, produce the corresponding type. The unsigned @p Type
9798/// is actually a value of type @c TargetInfo::IntType.
9799CanQualType ASTContext::getFromTargetType(unsigned Type) const {
9800 switch (Type) {
9801 case TargetInfo::NoInt: return {};
9804 case TargetInfo::SignedShort: return ShortTy;
9806 case TargetInfo::SignedInt: return IntTy;
9808 case TargetInfo::SignedLong: return LongTy;
9812 }
9813
9814 llvm_unreachable("Unhandled TargetInfo::IntType value");
9815}
9816
9817//===----------------------------------------------------------------------===//
9818// Type Predicates.
9819//===----------------------------------------------------------------------===//
9820
9821/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
9822/// garbage collection attribute.
9823///
9825 if (getLangOpts().getGC() == LangOptions::NonGC)
9826 return Qualifiers::GCNone;
9827
9828 assert(getLangOpts().ObjC);
9829 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
9830
9831 // Default behaviour under objective-C's gc is for ObjC pointers
9832 // (or pointers to them) be treated as though they were declared
9833 // as __strong.
9834 if (GCAttrs == Qualifiers::GCNone) {
9836 return Qualifiers::Strong;
9837 else if (Ty->isPointerType())
9839 } else {
9840 // It's not valid to set GC attributes on anything that isn't a
9841 // pointer.
9842#ifndef NDEBUG
9844 while (const auto *AT = dyn_cast<ArrayType>(CT))
9845 CT = AT->getElementType();
9846 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
9847#endif
9848 }
9849 return GCAttrs;
9850}
9851
9852//===----------------------------------------------------------------------===//
9853// Type Compatibility Testing
9854//===----------------------------------------------------------------------===//
9855
9856/// areCompatVectorTypes - Return true if the two specified vector types are
9857/// compatible.
9858static bool areCompatVectorTypes(const VectorType *LHS,
9859 const VectorType *RHS) {
9860 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9861 return LHS->getElementType() == RHS->getElementType() &&
9862 LHS->getNumElements() == RHS->getNumElements();
9863}
9864
9865/// areCompatMatrixTypes - Return true if the two specified matrix types are
9866/// compatible.
9868 const ConstantMatrixType *RHS) {
9869 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9870 return LHS->getElementType() == RHS->getElementType() &&
9871 LHS->getNumRows() == RHS->getNumRows() &&
9872 LHS->getNumColumns() == RHS->getNumColumns();
9873}
9874
9876 QualType SecondVec) {
9877 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
9878 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
9879
9880 if (hasSameUnqualifiedType(FirstVec, SecondVec))
9881 return true;
9882
9883 // Treat Neon vector types and most AltiVec vector types as if they are the
9884 // equivalent GCC vector types.
9885 const auto *First = FirstVec->castAs<VectorType>();
9886 const auto *Second = SecondVec->castAs<VectorType>();
9887 if (First->getNumElements() == Second->getNumElements() &&
9888 hasSameType(First->getElementType(), Second->getElementType()) &&
9889 First->getVectorKind() != VectorKind::AltiVecPixel &&
9890 First->getVectorKind() != VectorKind::AltiVecBool &&
9893 First->getVectorKind() != VectorKind::SveFixedLengthData &&
9894 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
9897 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
9899 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
9901 return true;
9902
9903 return false;
9904}
9905
9906/// getSVETypeSize - Return SVE vector or predicate register size.
9907static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
9908 assert(Ty->isSveVLSBuiltinType() && "Invalid SVE Type");
9909 if (Ty->getKind() == BuiltinType::SveBool ||
9910 Ty->getKind() == BuiltinType::SveCount)
9911 return (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth();
9912 return Context.getLangOpts().VScaleMin * 128;
9913}
9914
9916 QualType SecondType) {
9917 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9918 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9919 if (const auto *VT = SecondType->getAs<VectorType>()) {
9920 // Predicates have the same representation as uint8 so we also have to
9921 // check the kind to make these types incompatible.
9922 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
9923 return BT->getKind() == BuiltinType::SveBool;
9924 else if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
9925 return VT->getElementType().getCanonicalType() ==
9926 FirstType->getSveEltType(*this);
9927 else if (VT->getVectorKind() == VectorKind::Generic)
9928 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
9929 hasSameType(VT->getElementType(),
9930 getBuiltinVectorTypeInfo(BT).ElementType);
9931 }
9932 }
9933 return false;
9934 };
9935
9936 return IsValidCast(FirstType, SecondType) ||
9937 IsValidCast(SecondType, FirstType);
9938}
9939
9941 QualType SecondType) {
9942 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9943 const auto *BT = FirstType->getAs<BuiltinType>();
9944 if (!BT)
9945 return false;
9946
9947 const auto *VecTy = SecondType->getAs<VectorType>();
9948 if (VecTy && (VecTy->getVectorKind() == VectorKind::SveFixedLengthData ||
9949 VecTy->getVectorKind() == VectorKind::Generic)) {
9951 getLangOpts().getLaxVectorConversions();
9952
9953 // Can not convert between sve predicates and sve vectors because of
9954 // different size.
9955 if (BT->getKind() == BuiltinType::SveBool &&
9956 VecTy->getVectorKind() == VectorKind::SveFixedLengthData)
9957 return false;
9958
9959 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
9960 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
9961 // converts to VLAT and VLAT implicitly converts to GNUT."
9962 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
9963 // predicates.
9964 if (VecTy->getVectorKind() == VectorKind::Generic &&
9965 getTypeSize(SecondType) != getSVETypeSize(*this, BT))
9966 return false;
9967
9968 // If -flax-vector-conversions=all is specified, the types are
9969 // certainly compatible.
9971 return true;
9972
9973 // If -flax-vector-conversions=integer is specified, the types are
9974 // compatible if the elements are integer types.
9976 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
9977 FirstType->getSveEltType(*this)->isIntegerType();
9978 }
9979
9980 return false;
9981 };
9982
9983 return IsLaxCompatible(FirstType, SecondType) ||
9984 IsLaxCompatible(SecondType, FirstType);
9985}
9986
9987/// getRVVTypeSize - Return RVV vector register size.
9988static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
9989 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
9990 auto VScale = Context.getTargetInfo().getVScaleRange(Context.getLangOpts());
9991 if (!VScale)
9992 return 0;
9993
9995
9996 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
9997 if (Info.ElementType == Context.BoolTy)
9998 EltSize = 1;
9999
10000 uint64_t MinElts = Info.EC.getKnownMinValue();
10001 return VScale->first * MinElts * EltSize;
10002}
10003
10005 QualType SecondType) {
10006 assert(
10007 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10008 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10009 "Expected RVV builtin type and vector type!");
10010
10011 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10012 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10013 if (const auto *VT = SecondType->getAs<VectorType>()) {
10014 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10016 return FirstType->isRVVVLSBuiltinType() &&
10017 Info.ElementType == BoolTy &&
10018 getTypeSize(SecondType) == getRVVTypeSize(*this, BT);
10019 }
10020 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10021 VT->getVectorKind() == VectorKind::Generic)
10022 return FirstType->isRVVVLSBuiltinType() &&
10023 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10024 hasSameType(VT->getElementType(),
10025 getBuiltinVectorTypeInfo(BT).ElementType);
10026 }
10027 }
10028 return false;
10029 };
10030
10031 return IsValidCast(FirstType, SecondType) ||
10032 IsValidCast(SecondType, FirstType);
10033}
10034
10036 QualType SecondType) {
10037 assert(
10038 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10039 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10040 "Expected RVV builtin type and vector type!");
10041
10042 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10043 const auto *BT = FirstType->getAs<BuiltinType>();
10044 if (!BT)
10045 return false;
10046
10047 if (!BT->isRVVVLSBuiltinType())
10048 return false;
10049
10050 const auto *VecTy = SecondType->getAs<VectorType>();
10051 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10053 getLangOpts().getLaxVectorConversions();
10054
10055 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10056 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10057 return false;
10058
10059 // If -flax-vector-conversions=all is specified, the types are
10060 // certainly compatible.
10062 return true;
10063
10064 // If -flax-vector-conversions=integer is specified, the types are
10065 // compatible if the elements are integer types.
10067 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10068 FirstType->getRVVEltType(*this)->isIntegerType();
10069 }
10070
10071 return false;
10072 };
10073
10074 return IsLaxCompatible(FirstType, SecondType) ||
10075 IsLaxCompatible(SecondType, FirstType);
10076}
10077
10079 while (true) {
10080 // __strong id
10081 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10082 if (Attr->getAttrKind() == attr::ObjCOwnership)
10083 return true;
10084
10085 Ty = Attr->getModifiedType();
10086
10087 // X *__strong (...)
10088 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10089 Ty = Paren->getInnerType();
10090
10091 // We do not want to look through typedefs, typeof(expr),
10092 // typeof(type), or any other way that the type is somehow
10093 // abstracted.
10094 } else {
10095 return false;
10096 }
10097 }
10098}
10099
10100//===----------------------------------------------------------------------===//
10101// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10102//===----------------------------------------------------------------------===//
10103
10104/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10105/// inheritance hierarchy of 'rProto'.
10106bool
10108 ObjCProtocolDecl *rProto) const {
10109 if (declaresSameEntity(lProto, rProto))
10110 return true;
10111 for (auto *PI : rProto->protocols())
10112 if (ProtocolCompatibleWithProtocol(lProto, PI))
10113 return true;
10114 return false;
10115}
10116
10117/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10118/// Class<pr1, ...>.
10120 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10121 for (auto *lhsProto : lhs->quals()) {
10122 bool match = false;
10123 for (auto *rhsProto : rhs->quals()) {
10124 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10125 match = true;
10126 break;
10127 }
10128 }
10129 if (!match)
10130 return false;
10131 }
10132 return true;
10133}
10134
10135/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10136/// ObjCQualifiedIDType.
10138 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10139 bool compare) {
10140 // Allow id<P..> and an 'id' in all cases.
10141 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10142 return true;
10143
10144 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10145 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10147 return false;
10148
10149 if (lhs->isObjCQualifiedIdType()) {
10150 if (rhs->qual_empty()) {
10151 // If the RHS is a unqualified interface pointer "NSString*",
10152 // make sure we check the class hierarchy.
10153 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10154 for (auto *I : lhs->quals()) {
10155 // when comparing an id<P> on lhs with a static type on rhs,
10156 // see if static class implements all of id's protocols, directly or
10157 // through its super class and categories.
10158 if (!rhsID->ClassImplementsProtocol(I, true))
10159 return false;
10160 }
10161 }
10162 // If there are no qualifiers and no interface, we have an 'id'.
10163 return true;
10164 }
10165 // Both the right and left sides have qualifiers.
10166 for (auto *lhsProto : lhs->quals()) {
10167 bool match = false;
10168
10169 // when comparing an id<P> on lhs with a static type on rhs,
10170 // see if static class implements all of id's protocols, directly or
10171 // through its super class and categories.
10172 for (auto *rhsProto : rhs->quals()) {
10173 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10174 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10175 match = true;
10176 break;
10177 }
10178 }
10179 // If the RHS is a qualified interface pointer "NSString<P>*",
10180 // make sure we check the class hierarchy.
10181 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10182 for (auto *I : lhs->quals()) {
10183 // when comparing an id<P> on lhs with a static type on rhs,
10184 // see if static class implements all of id's protocols, directly or
10185 // through its super class and categories.
10186 if (rhsID->ClassImplementsProtocol(I, true)) {
10187 match = true;
10188 break;
10189 }
10190 }
10191 }
10192 if (!match)
10193 return false;
10194 }
10195
10196 return true;
10197 }
10198
10199 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10200
10201 if (lhs->getInterfaceType()) {
10202 // If both the right and left sides have qualifiers.
10203 for (auto *lhsProto : lhs->quals()) {
10204 bool match = false;
10205
10206 // when comparing an id<P> on rhs with a static type on lhs,
10207 // see if static class implements all of id's protocols, directly or
10208 // through its super class and categories.
10209 // First, lhs protocols in the qualifier list must be found, direct
10210 // or indirect in rhs's qualifier list or it is a mismatch.
10211 for (auto *rhsProto : rhs->quals()) {
10212 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10213 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10214 match = true;
10215 break;
10216 }
10217 }
10218 if (!match)
10219 return false;
10220 }
10221
10222 // Static class's protocols, or its super class or category protocols
10223 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10224 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10225 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10226 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10227 // This is rather dubious but matches gcc's behavior. If lhs has
10228 // no type qualifier and its class has no static protocol(s)
10229 // assume that it is mismatch.
10230 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10231 return false;
10232 for (auto *lhsProto : LHSInheritedProtocols) {
10233 bool match = false;
10234 for (auto *rhsProto : rhs->quals()) {
10235 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10236 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10237 match = true;
10238 break;
10239 }
10240 }
10241 if (!match)
10242 return false;
10243 }
10244 }
10245 return true;
10246 }
10247 return false;
10248}
10249
10250/// canAssignObjCInterfaces - Return true if the two interface types are
10251/// compatible for assignment from RHS to LHS. This handles validation of any
10252/// protocol qualifiers on the LHS or RHS.
10254 const ObjCObjectPointerType *RHSOPT) {
10255 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10256 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10257
10258 // If either type represents the built-in 'id' type, return true.
10259 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10260 return true;
10261
10262 // Function object that propagates a successful result or handles
10263 // __kindof types.
10264 auto finish = [&](bool succeeded) -> bool {
10265 if (succeeded)
10266 return true;
10267
10268 if (!RHS->isKindOfType())
10269 return false;
10270
10271 // Strip off __kindof and protocol qualifiers, then check whether
10272 // we can assign the other way.
10274 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10275 };
10276
10277 // Casts from or to id<P> are allowed when the other side has compatible
10278 // protocols.
10279 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10280 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10281 }
10282
10283 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10284 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10285 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10286 }
10287
10288 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10289 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10290 return true;
10291 }
10292
10293 // If we have 2 user-defined types, fall into that path.
10294 if (LHS->getInterface() && RHS->getInterface()) {
10295 return finish(canAssignObjCInterfaces(LHS, RHS));
10296 }
10297
10298 return false;
10299}
10300
10301/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10302/// for providing type-safety for objective-c pointers used to pass/return
10303/// arguments in block literals. When passed as arguments, passing 'A*' where
10304/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10305/// not OK. For the return type, the opposite is not OK.
10307 const ObjCObjectPointerType *LHSOPT,
10308 const ObjCObjectPointerType *RHSOPT,
10309 bool BlockReturnType) {
10310
10311 // Function object that propagates a successful result or handles
10312 // __kindof types.
10313 auto finish = [&](bool succeeded) -> bool {
10314 if (succeeded)
10315 return true;
10316
10317 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10318 if (!Expected->isKindOfType())
10319 return false;
10320
10321 // Strip off __kindof and protocol qualifiers, then check whether
10322 // we can assign the other way.
10324 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10325 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10326 BlockReturnType);
10327 };
10328
10329 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10330 return true;
10331
10332 if (LHSOPT->isObjCBuiltinType()) {
10333 return finish(RHSOPT->isObjCBuiltinType() ||
10334 RHSOPT->isObjCQualifiedIdType());
10335 }
10336
10337 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10338 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10339 // Use for block parameters previous type checking for compatibility.
10340 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10341 // Or corrected type checking as in non-compat mode.
10342 (!BlockReturnType &&
10343 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10344 else
10346 (BlockReturnType ? LHSOPT : RHSOPT),
10347 (BlockReturnType ? RHSOPT : LHSOPT), false));
10348 }
10349
10350 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10351 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10352 if (LHS && RHS) { // We have 2 user-defined types.
10353 if (LHS != RHS) {
10354 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10355 return finish(BlockReturnType);
10356 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10357 return finish(!BlockReturnType);
10358 }
10359 else
10360 return true;
10361 }
10362 return false;
10363}
10364
10365/// Comparison routine for Objective-C protocols to be used with
10366/// llvm::array_pod_sort.
10368 ObjCProtocolDecl * const *rhs) {
10369 return (*lhs)->getName().compare((*rhs)->getName());
10370}
10371
10372/// getIntersectionOfProtocols - This routine finds the intersection of set
10373/// of protocols inherited from two distinct objective-c pointer objects with
10374/// the given common base.
10375/// It is used to build composite qualifier list of the composite type of
10376/// the conditional expression involving two objective-c pointer objects.
10377static
10379 const ObjCInterfaceDecl *CommonBase,
10380 const ObjCObjectPointerType *LHSOPT,
10381 const ObjCObjectPointerType *RHSOPT,
10382 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
10383
10384 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10385 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10386 assert(LHS->getInterface() && "LHS must have an interface base");
10387 assert(RHS->getInterface() && "RHS must have an interface base");
10388
10389 // Add all of the protocols for the LHS.
10391
10392 // Start with the protocol qualifiers.
10393 for (auto *proto : LHS->quals()) {
10394 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
10395 }
10396
10397 // Also add the protocols associated with the LHS interface.
10398 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
10399
10400 // Add all of the protocols for the RHS.
10402
10403 // Start with the protocol qualifiers.
10404 for (auto *proto : RHS->quals()) {
10405 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
10406 }
10407
10408 // Also add the protocols associated with the RHS interface.
10409 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
10410
10411 // Compute the intersection of the collected protocol sets.
10412 for (auto *proto : LHSProtocolSet) {
10413 if (RHSProtocolSet.count(proto))
10414 IntersectionSet.push_back(proto);
10415 }
10416
10417 // Compute the set of protocols that is implied by either the common type or
10418 // the protocols within the intersection.
10420 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
10421
10422 // Remove any implied protocols from the list of inherited protocols.
10423 if (!ImpliedProtocols.empty()) {
10424 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
10425 return ImpliedProtocols.contains(proto);
10426 });
10427 }
10428
10429 // Sort the remaining protocols by name.
10430 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
10432}
10433
10434/// Determine whether the first type is a subtype of the second.
10436 QualType rhs) {
10437 // Common case: two object pointers.
10438 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
10439 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
10440 if (lhsOPT && rhsOPT)
10441 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
10442
10443 // Two block pointers.
10444 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
10445 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
10446 if (lhsBlock && rhsBlock)
10447 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
10448
10449 // If either is an unqualified 'id' and the other is a block, it's
10450 // acceptable.
10451 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
10452 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
10453 return true;
10454
10455 return false;
10456}
10457
10458// Check that the given Objective-C type argument lists are equivalent.
10460 const ObjCInterfaceDecl *iface,
10461 ArrayRef<QualType> lhsArgs,
10462 ArrayRef<QualType> rhsArgs,
10463 bool stripKindOf) {
10464 if (lhsArgs.size() != rhsArgs.size())
10465 return false;
10466
10467 ObjCTypeParamList *typeParams = iface->getTypeParamList();
10468 if (!typeParams)
10469 return false;
10470
10471 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
10472 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
10473 continue;
10474
10475 switch (typeParams->begin()[i]->getVariance()) {
10477 if (!stripKindOf ||
10478 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
10479 rhsArgs[i].stripObjCKindOfType(ctx))) {
10480 return false;
10481 }
10482 break;
10483
10485 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
10486 return false;
10487 break;
10488
10490 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
10491 return false;
10492 break;
10493 }
10494 }
10495
10496 return true;
10497}
10498
10500 const ObjCObjectPointerType *Lptr,
10501 const ObjCObjectPointerType *Rptr) {
10502 const ObjCObjectType *LHS = Lptr->getObjectType();
10503 const ObjCObjectType *RHS = Rptr->getObjectType();
10504 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
10505 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
10506
10507 if (!LDecl || !RDecl)
10508 return {};
10509
10510 // When either LHS or RHS is a kindof type, we should return a kindof type.
10511 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
10512 // kindof(A).
10513 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
10514
10515 // Follow the left-hand side up the class hierarchy until we either hit a
10516 // root or find the RHS. Record the ancestors in case we don't find it.
10517 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
10518 LHSAncestors;
10519 while (true) {
10520 // Record this ancestor. We'll need this if the common type isn't in the
10521 // path from the LHS to the root.
10522 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
10523
10524 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
10525 // Get the type arguments.
10526 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
10527 bool anyChanges = false;
10528 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10529 // Both have type arguments, compare them.
10530 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10531 LHS->getTypeArgs(), RHS->getTypeArgs(),
10532 /*stripKindOf=*/true))
10533 return {};
10534 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10535 // If only one has type arguments, the result will not have type
10536 // arguments.
10537 LHSTypeArgs = {};
10538 anyChanges = true;
10539 }
10540
10541 // Compute the intersection of protocols.
10543 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
10544 Protocols);
10545 if (!Protocols.empty())
10546 anyChanges = true;
10547
10548 // If anything in the LHS will have changed, build a new result type.
10549 // If we need to return a kindof type but LHS is not a kindof type, we
10550 // build a new result type.
10551 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
10553 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
10554 anyKindOf || LHS->isKindOfType());
10556 }
10557
10558 return getObjCObjectPointerType(QualType(LHS, 0));
10559 }
10560
10561 // Find the superclass.
10562 QualType LHSSuperType = LHS->getSuperClassType();
10563 if (LHSSuperType.isNull())
10564 break;
10565
10566 LHS = LHSSuperType->castAs<ObjCObjectType>();
10567 }
10568
10569 // We didn't find anything by following the LHS to its root; now check
10570 // the RHS against the cached set of ancestors.
10571 while (true) {
10572 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
10573 if (KnownLHS != LHSAncestors.end()) {
10574 LHS = KnownLHS->second;
10575
10576 // Get the type arguments.
10577 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
10578 bool anyChanges = false;
10579 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10580 // Both have type arguments, compare them.
10581 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10582 LHS->getTypeArgs(), RHS->getTypeArgs(),
10583 /*stripKindOf=*/true))
10584 return {};
10585 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10586 // If only one has type arguments, the result will not have type
10587 // arguments.
10588 RHSTypeArgs = {};
10589 anyChanges = true;
10590 }
10591
10592 // Compute the intersection of protocols.
10594 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
10595 Protocols);
10596 if (!Protocols.empty())
10597 anyChanges = true;
10598
10599 // If we need to return a kindof type but RHS is not a kindof type, we
10600 // build a new result type.
10601 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
10603 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
10604 anyKindOf || RHS->isKindOfType());
10606 }
10607
10608 return getObjCObjectPointerType(QualType(RHS, 0));
10609 }
10610
10611 // Find the superclass of the RHS.
10612 QualType RHSSuperType = RHS->getSuperClassType();
10613 if (RHSSuperType.isNull())
10614 break;
10615
10616 RHS = RHSSuperType->castAs<ObjCObjectType>();
10617 }
10618
10619 return {};
10620}
10621
10623 const ObjCObjectType *RHS) {
10624 assert(LHS->getInterface() && "LHS is not an interface type");
10625 assert(RHS->getInterface() && "RHS is not an interface type");
10626
10627 // Verify that the base decls are compatible: the RHS must be a subclass of
10628 // the LHS.
10629 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
10630 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
10631 if (!IsSuperClass)
10632 return false;
10633
10634 // If the LHS has protocol qualifiers, determine whether all of them are
10635 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
10636 // LHS).
10637 if (LHS->getNumProtocols() > 0) {
10638 // OK if conversion of LHS to SuperClass results in narrowing of types
10639 // ; i.e., SuperClass may implement at least one of the protocols
10640 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
10641 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
10642 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
10643 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
10644 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
10645 // qualifiers.
10646 for (auto *RHSPI : RHS->quals())
10647 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
10648 // If there is no protocols associated with RHS, it is not a match.
10649 if (SuperClassInheritedProtocols.empty())
10650 return false;
10651
10652 for (const auto *LHSProto : LHS->quals()) {
10653 bool SuperImplementsProtocol = false;
10654 for (auto *SuperClassProto : SuperClassInheritedProtocols)
10655 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
10656 SuperImplementsProtocol = true;
10657 break;
10658 }
10659 if (!SuperImplementsProtocol)
10660 return false;
10661 }
10662 }
10663
10664 // If the LHS is specialized, we may need to check type arguments.
10665 if (LHS->isSpecialized()) {
10666 // Follow the superclass chain until we've matched the LHS class in the
10667 // hierarchy. This substitutes type arguments through.
10668 const ObjCObjectType *RHSSuper = RHS;
10669 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
10670 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
10671
10672 // If the RHS is specializd, compare type arguments.
10673 if (RHSSuper->isSpecialized() &&
10674 !sameObjCTypeArgs(*this, LHS->getInterface(),
10675 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
10676 /*stripKindOf=*/true)) {
10677 return false;
10678 }
10679 }
10680
10681 return true;
10682}
10683
10685 // get the "pointed to" types
10686 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
10687 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
10688
10689 if (!LHSOPT || !RHSOPT)
10690 return false;
10691
10692 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
10693 canAssignObjCInterfaces(RHSOPT, LHSOPT);
10694}
10695
10698 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
10699 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
10700}
10701
10702/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
10703/// both shall have the identically qualified version of a compatible type.
10704/// C99 6.2.7p1: Two types have compatible types if their types are the
10705/// same. See 6.7.[2,3,5] for additional rules.
10707 bool CompareUnqualified) {
10708 if (getLangOpts().CPlusPlus)
10709 return hasSameType(LHS, RHS);
10710
10711 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
10712}
10713
10715 return typesAreCompatible(LHS, RHS);
10716}
10717
10719 return !mergeTypes(LHS, RHS, true).isNull();
10720}
10721
10722/// mergeTransparentUnionType - if T is a transparent union type and a member
10723/// of T is compatible with SubType, return the merged type, else return
10724/// QualType()
10726 bool OfBlockPointer,
10727 bool Unqualified) {
10728 if (const RecordType *UT = T->getAsUnionType()) {
10729 RecordDecl *UD = UT->getDecl();
10730 if (UD->hasAttr<TransparentUnionAttr>()) {
10731 for (const auto *I : UD->fields()) {
10732 QualType ET = I->getType().getUnqualifiedType();
10733 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
10734 if (!MT.isNull())
10735 return MT;
10736 }
10737 }
10738 }
10739
10740 return {};
10741}
10742
10743/// mergeFunctionParameterTypes - merge two types which appear as function
10744/// parameter types
10746 bool OfBlockPointer,
10747 bool Unqualified) {
10748 // GNU extension: two types are compatible if they appear as a function
10749 // argument, one of the types is a transparent union type and the other
10750 // type is compatible with a union member
10751 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
10752 Unqualified);
10753 if (!lmerge.isNull())
10754 return lmerge;
10755
10756 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
10757 Unqualified);
10758 if (!rmerge.isNull())
10759 return rmerge;
10760
10761 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
10762}
10763
10765 bool OfBlockPointer, bool Unqualified,
10766 bool AllowCXX,
10767 bool IsConditionalOperator) {
10768 const auto *lbase = lhs->castAs<FunctionType>();
10769 const auto *rbase = rhs->castAs<FunctionType>();
10770 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
10771 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
10772 bool allLTypes = true;
10773 bool allRTypes = true;
10774
10775 // Check return type
10776 QualType retType;
10777 if (OfBlockPointer) {
10778 QualType RHS = rbase->getReturnType();
10779 QualType LHS = lbase->getReturnType();
10780 bool UnqualifiedResult = Unqualified;
10781 if (!UnqualifiedResult)
10782 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
10783 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
10784 }
10785 else
10786 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
10787 Unqualified);
10788 if (retType.isNull())
10789 return {};
10790
10791 if (Unqualified)
10792 retType = retType.getUnqualifiedType();
10793
10794 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
10795 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
10796 if (Unqualified) {
10797 LRetType = LRetType.getUnqualifiedType();
10798 RRetType = RRetType.getUnqualifiedType();
10799 }
10800
10801 if (getCanonicalType(retType) != LRetType)
10802 allLTypes = false;
10803 if (getCanonicalType(retType) != RRetType)
10804 allRTypes = false;
10805
10806 // FIXME: double check this
10807 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
10808 // rbase->getRegParmAttr() != 0 &&
10809 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
10810 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
10811 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
10812
10813 // Compatible functions must have compatible calling conventions
10814 if (lbaseInfo.getCC() != rbaseInfo.getCC())
10815 return {};
10816
10817 // Regparm is part of the calling convention.
10818 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
10819 return {};
10820 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
10821 return {};
10822
10823 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
10824 return {};
10825 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
10826 return {};
10827 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
10828 return {};
10829
10830 // When merging declarations, it's common for supplemental information like
10831 // attributes to only be present in one of the declarations, and we generally
10832 // want type merging to preserve the union of information. So a merged
10833 // function type should be noreturn if it was noreturn in *either* operand
10834 // type.
10835 //
10836 // But for the conditional operator, this is backwards. The result of the
10837 // operator could be either operand, and its type should conservatively
10838 // reflect that. So a function type in a composite type is noreturn only
10839 // if it's noreturn in *both* operand types.
10840 //
10841 // Arguably, noreturn is a kind of subtype, and the conditional operator
10842 // ought to produce the most specific common supertype of its operand types.
10843 // That would differ from this rule in contravariant positions. However,
10844 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
10845 // as a practical matter, it would only affect C code that does abstraction of
10846 // higher-order functions (taking noreturn callbacks!), which is uncommon to
10847 // say the least. So we use the simpler rule.
10848 bool NoReturn = IsConditionalOperator
10849 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
10850 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
10851 if (lbaseInfo.getNoReturn() != NoReturn)
10852 allLTypes = false;
10853 if (rbaseInfo.getNoReturn() != NoReturn)
10854 allRTypes = false;
10855
10856 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
10857
10858 std::optional<FunctionEffectSet> MergedFX;
10859
10860 if (lproto && rproto) { // two C99 style function prototypes
10861 assert((AllowCXX ||
10862 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
10863 "C++ shouldn't be here");
10864 // Compatible functions must have the same number of parameters
10865 if (lproto->getNumParams() != rproto->getNumParams())
10866 return {};
10867
10868 // Variadic and non-variadic functions aren't compatible
10869 if (lproto->isVariadic() != rproto->isVariadic())
10870 return {};
10871
10872 if (lproto->getMethodQuals() != rproto->getMethodQuals())
10873 return {};
10874
10875 // Function effects are handled similarly to noreturn, see above.
10876 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
10877 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
10878 if (LHSFX != RHSFX) {
10879 if (IsConditionalOperator)
10880 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
10881 else {
10883 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
10884 // Here we're discarding a possible error due to conflicts in the effect
10885 // sets. But we're not in a context where we can report it. The
10886 // operation does however guarantee maintenance of invariants.
10887 }
10888 if (*MergedFX != LHSFX)
10889 allLTypes = false;
10890 if (*MergedFX != RHSFX)
10891 allRTypes = false;
10892 }
10893
10895 bool canUseLeft, canUseRight;
10896 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
10897 newParamInfos))
10898 return {};
10899
10900 if (!canUseLeft)
10901 allLTypes = false;
10902 if (!canUseRight)
10903 allRTypes = false;
10904
10905 // Check parameter type compatibility
10907 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
10908 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
10909 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
10911 lParamType, rParamType, OfBlockPointer, Unqualified);
10912 if (paramType.isNull())
10913 return {};
10914
10915 if (Unqualified)
10916 paramType = paramType.getUnqualifiedType();
10917
10918 types.push_back(paramType);
10919 if (Unqualified) {
10920 lParamType = lParamType.getUnqualifiedType();
10921 rParamType = rParamType.getUnqualifiedType();
10922 }
10923
10924 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
10925 allLTypes = false;
10926 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
10927 allRTypes = false;
10928 }
10929
10930 if (allLTypes) return lhs;
10931 if (allRTypes) return rhs;
10932
10933 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
10934 EPI.ExtInfo = einfo;
10935 EPI.ExtParameterInfos =
10936 newParamInfos.empty() ? nullptr : newParamInfos.data();
10937 if (MergedFX)
10938 EPI.FunctionEffects = *MergedFX;
10939 return getFunctionType(retType, types, EPI);
10940 }
10941
10942 if (lproto) allRTypes = false;
10943 if (rproto) allLTypes = false;
10944
10945 const FunctionProtoType *proto = lproto ? lproto : rproto;
10946 if (proto) {
10947 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
10948 if (proto->isVariadic())
10949 return {};
10950 // Check that the types are compatible with the types that
10951 // would result from default argument promotions (C99 6.7.5.3p15).
10952 // The only types actually affected are promotable integer
10953 // types and floats, which would be passed as a different
10954 // type depending on whether the prototype is visible.
10955 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
10956 QualType paramTy = proto->getParamType(i);
10957
10958 // Look at the converted type of enum types, since that is the type used
10959 // to pass enum values.
10960 if (const auto *Enum = paramTy->getAs<EnumType>()) {
10961 paramTy = Enum->getDecl()->getIntegerType();
10962 if (paramTy.isNull())
10963 return {};
10964 }
10965
10966 if (isPromotableIntegerType(paramTy) ||
10967 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
10968 return {};
10969 }
10970
10971 if (allLTypes) return lhs;
10972 if (allRTypes) return rhs;
10973
10975 EPI.ExtInfo = einfo;
10976 if (MergedFX)
10977 EPI.FunctionEffects = *MergedFX;
10978 return getFunctionType(retType, proto->getParamTypes(), EPI);
10979 }
10980
10981 if (allLTypes) return lhs;
10982 if (allRTypes) return rhs;
10983 return getFunctionNoProtoType(retType, einfo);
10984}
10985
10986/// Given that we have an enum type and a non-enum type, try to merge them.
10988 QualType other, bool isBlockReturnType) {
10989 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
10990 // a signed integer type, or an unsigned integer type.
10991 // Compatibility is based on the underlying type, not the promotion
10992 // type.
10993 QualType underlyingType = ET->getDecl()->getIntegerType();
10994 if (underlyingType.isNull())
10995 return {};
10996 if (Context.hasSameType(underlyingType, other))
10997 return other;
10998
10999 // In block return types, we're more permissive and accept any
11000 // integral type of the same size.
11001 if (isBlockReturnType && other->isIntegerType() &&
11002 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11003 return other;
11004
11005 return {};
11006}
11007
11008QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11009 bool Unqualified, bool BlockReturnType,
11010 bool IsConditionalOperator) {
11011 // For C++ we will not reach this code with reference types (see below),
11012 // for OpenMP variant call overloading we might.
11013 //
11014 // C++ [expr]: If an expression initially has the type "reference to T", the
11015 // type is adjusted to "T" prior to any further analysis, the expression
11016 // designates the object or function denoted by the reference, and the
11017 // expression is an lvalue unless the reference is an rvalue reference and
11018 // the expression is a function call (possibly inside parentheses).
11019 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11020 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11021 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11022 LHS->getTypeClass() == RHS->getTypeClass())
11023 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11024 OfBlockPointer, Unqualified, BlockReturnType);
11025 if (LHSRefTy || RHSRefTy)
11026 return {};
11027
11028 if (Unqualified) {
11029 LHS = LHS.getUnqualifiedType();
11030 RHS = RHS.getUnqualifiedType();
11031 }
11032
11033 QualType LHSCan = getCanonicalType(LHS),
11034 RHSCan = getCanonicalType(RHS);
11035
11036 // If two types are identical, they are compatible.
11037 if (LHSCan == RHSCan)
11038 return LHS;
11039
11040 // If the qualifiers are different, the types aren't compatible... mostly.
11041 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11042 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11043 if (LQuals != RQuals) {
11044 // If any of these qualifiers are different, we have a type
11045 // mismatch.
11046 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11047 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11048 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11049 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11050 return {};
11051
11052 // Exactly one GC qualifier difference is allowed: __strong is
11053 // okay if the other type has no GC qualifier but is an Objective
11054 // C object pointer (i.e. implicitly strong by default). We fix
11055 // this by pretending that the unqualified type was actually
11056 // qualified __strong.
11057 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11058 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11059 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11060
11061 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11062 return {};
11063
11064 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11066 }
11067 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11069 }
11070 return {};
11071 }
11072
11073 // Okay, qualifiers are equal.
11074
11075 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11076 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11077
11078 // We want to consider the two function types to be the same for these
11079 // comparisons, just force one to the other.
11080 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11081 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11082
11083 // Same as above for arrays
11084 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11085 LHSClass = Type::ConstantArray;
11086 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11087 RHSClass = Type::ConstantArray;
11088
11089 // ObjCInterfaces are just specialized ObjCObjects.
11090 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11091 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11092
11093 // Canonicalize ExtVector -> Vector.
11094 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11095 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11096
11097 // If the canonical type classes don't match.
11098 if (LHSClass != RHSClass) {
11099 // Note that we only have special rules for turning block enum
11100 // returns into block int returns, not vice-versa.
11101 if (const auto *ETy = LHS->getAs<EnumType>()) {
11102 return mergeEnumWithInteger(*this, ETy, RHS, false);
11103 }
11104 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
11105 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11106 }
11107 // allow block pointer type to match an 'id' type.
11108 if (OfBlockPointer && !BlockReturnType) {
11109 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11110 return LHS;
11111 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11112 return RHS;
11113 }
11114 // Allow __auto_type to match anything; it merges to the type with more
11115 // information.
11116 if (const auto *AT = LHS->getAs<AutoType>()) {
11117 if (!AT->isDeduced() && AT->isGNUAutoType())
11118 return RHS;
11119 }
11120 if (const auto *AT = RHS->getAs<AutoType>()) {
11121 if (!AT->isDeduced() && AT->isGNUAutoType())
11122 return LHS;
11123 }
11124 return {};
11125 }
11126
11127 // The canonical type classes match.
11128 switch (LHSClass) {
11129#define TYPE(Class, Base)
11130#define ABSTRACT_TYPE(Class, Base)
11131#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11132#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11133#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11134#include "clang/AST/TypeNodes.inc"
11135 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11136
11137 case Type::Auto:
11138 case Type::DeducedTemplateSpecialization:
11139 case Type::LValueReference:
11140 case Type::RValueReference:
11141 case Type::MemberPointer:
11142 llvm_unreachable("C++ should never be in mergeTypes");
11143
11144 case Type::ObjCInterface:
11145 case Type::IncompleteArray:
11146 case Type::VariableArray:
11147 case Type::FunctionProto:
11148 case Type::ExtVector:
11149 llvm_unreachable("Types are eliminated above");
11150
11151 case Type::Pointer:
11152 {
11153 // Merge two pointer types, while trying to preserve typedef info
11154 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11155 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11156 if (Unqualified) {
11157 LHSPointee = LHSPointee.getUnqualifiedType();
11158 RHSPointee = RHSPointee.getUnqualifiedType();
11159 }
11160 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11161 Unqualified);
11162 if (ResultType.isNull())
11163 return {};
11164 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11165 return LHS;
11166 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11167 return RHS;
11168 return getPointerType(ResultType);
11169 }
11170 case Type::BlockPointer:
11171 {
11172 // Merge two block pointer types, while trying to preserve typedef info
11173 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11174 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11175 if (Unqualified) {
11176 LHSPointee = LHSPointee.getUnqualifiedType();
11177 RHSPointee = RHSPointee.getUnqualifiedType();
11178 }
11179 if (getLangOpts().OpenCL) {
11180 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11181 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11182 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11183 // 6.12.5) thus the following check is asymmetric.
11184 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
11185 return {};
11186 LHSPteeQual.removeAddressSpace();
11187 RHSPteeQual.removeAddressSpace();
11188 LHSPointee =
11189 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11190 RHSPointee =
11191 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11192 }
11193 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11194 Unqualified);
11195 if (ResultType.isNull())
11196 return {};
11197 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11198 return LHS;
11199 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11200 return RHS;
11201 return getBlockPointerType(ResultType);
11202 }
11203 case Type::Atomic:
11204 {
11205 // Merge two pointer types, while trying to preserve typedef info
11206 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11207 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11208 if (Unqualified) {
11209 LHSValue = LHSValue.getUnqualifiedType();
11210 RHSValue = RHSValue.getUnqualifiedType();
11211 }
11212 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11213 Unqualified);
11214 if (ResultType.isNull())
11215 return {};
11216 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11217 return LHS;
11218 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11219 return RHS;
11220 return getAtomicType(ResultType);
11221 }
11222 case Type::ConstantArray:
11223 {
11224 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11225 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11226 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11227 return {};
11228
11229 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11230 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11231 if (Unqualified) {
11232 LHSElem = LHSElem.getUnqualifiedType();
11233 RHSElem = RHSElem.getUnqualifiedType();
11234 }
11235
11236 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11237 if (ResultType.isNull())
11238 return {};
11239
11240 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11241 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11242
11243 // If either side is a variable array, and both are complete, check whether
11244 // the current dimension is definite.
11245 if (LVAT || RVAT) {
11246 auto SizeFetch = [this](const VariableArrayType* VAT,
11247 const ConstantArrayType* CAT)
11248 -> std::pair<bool,llvm::APInt> {
11249 if (VAT) {
11250 std::optional<llvm::APSInt> TheInt;
11251 Expr *E = VAT->getSizeExpr();
11252 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11253 return std::make_pair(true, *TheInt);
11254 return std::make_pair(false, llvm::APSInt());
11255 }
11256 if (CAT)
11257 return std::make_pair(true, CAT->getSize());
11258 return std::make_pair(false, llvm::APInt());
11259 };
11260
11261 bool HaveLSize, HaveRSize;
11262 llvm::APInt LSize, RSize;
11263 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11264 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11265 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11266 return {}; // Definite, but unequal, array dimension
11267 }
11268
11269 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11270 return LHS;
11271 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11272 return RHS;
11273 if (LCAT)
11274 return getConstantArrayType(ResultType, LCAT->getSize(),
11275 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11276 if (RCAT)
11277 return getConstantArrayType(ResultType, RCAT->getSize(),
11278 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11279 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11280 return LHS;
11281 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11282 return RHS;
11283 if (LVAT) {
11284 // FIXME: This isn't correct! But tricky to implement because
11285 // the array's size has to be the size of LHS, but the type
11286 // has to be different.
11287 return LHS;
11288 }
11289 if (RVAT) {
11290 // FIXME: This isn't correct! But tricky to implement because
11291 // the array's size has to be the size of RHS, but the type
11292 // has to be different.
11293 return RHS;
11294 }
11295 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11296 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11297 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11298 }
11299 case Type::FunctionNoProto:
11300 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11301 /*AllowCXX=*/false, IsConditionalOperator);
11302 case Type::Record:
11303 case Type::Enum:
11304 return {};
11305 case Type::Builtin:
11306 // Only exactly equal builtin types are compatible, which is tested above.
11307 return {};
11308 case Type::Complex:
11309 // Distinct complex types are incompatible.
11310 return {};
11311 case Type::Vector:
11312 // FIXME: The merged type should be an ExtVector!
11313 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11314 RHSCan->castAs<VectorType>()))
11315 return LHS;
11316 return {};
11317 case Type::ConstantMatrix:
11319 RHSCan->castAs<ConstantMatrixType>()))
11320 return LHS;
11321 return {};
11322 case Type::ObjCObject: {
11323 // Check if the types are assignment compatible.
11324 // FIXME: This should be type compatibility, e.g. whether
11325 // "LHS x; RHS x;" at global scope is legal.
11327 RHS->castAs<ObjCObjectType>()))
11328 return LHS;
11329 return {};
11330 }
11331 case Type::ObjCObjectPointer:
11332 if (OfBlockPointer) {
11335 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11336 return LHS;
11337 return {};
11338 }
11341 return LHS;
11342 return {};
11343 case Type::Pipe:
11344 assert(LHS != RHS &&
11345 "Equivalent pipe types should have already been handled!");
11346 return {};
11347 case Type::ArrayParameter:
11348 assert(LHS != RHS &&
11349 "Equivalent ArrayParameter types should have already been handled!");
11350 return {};
11351 case Type::BitInt: {
11352 // Merge two bit-precise int types, while trying to preserve typedef info.
11353 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
11354 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
11355 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
11356 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
11357
11358 // Like unsigned/int, shouldn't have a type if they don't match.
11359 if (LHSUnsigned != RHSUnsigned)
11360 return {};
11361
11362 if (LHSBits != RHSBits)
11363 return {};
11364 return LHS;
11365 }
11366 }
11367
11368 llvm_unreachable("Invalid Type::Class!");
11369}
11370
11372 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
11373 bool &CanUseFirst, bool &CanUseSecond,
11375 assert(NewParamInfos.empty() && "param info list not empty");
11376 CanUseFirst = CanUseSecond = true;
11377 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
11378 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
11379
11380 // Fast path: if the first type doesn't have ext parameter infos,
11381 // we match if and only if the second type also doesn't have them.
11382 if (!FirstHasInfo && !SecondHasInfo)
11383 return true;
11384
11385 bool NeedParamInfo = false;
11386 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
11387 : SecondFnType->getExtParameterInfos().size();
11388
11389 for (size_t I = 0; I < E; ++I) {
11390 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
11391 if (FirstHasInfo)
11392 FirstParam = FirstFnType->getExtParameterInfo(I);
11393 if (SecondHasInfo)
11394 SecondParam = SecondFnType->getExtParameterInfo(I);
11395
11396 // Cannot merge unless everything except the noescape flag matches.
11397 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
11398 return false;
11399
11400 bool FirstNoEscape = FirstParam.isNoEscape();
11401 bool SecondNoEscape = SecondParam.isNoEscape();
11402 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
11403 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
11404 if (NewParamInfos.back().getOpaqueValue())
11405 NeedParamInfo = true;
11406 if (FirstNoEscape != IsNoEscape)
11407 CanUseFirst = false;
11408 if (SecondNoEscape != IsNoEscape)
11409 CanUseSecond = false;
11410 }
11411
11412 if (!NeedParamInfo)
11413 NewParamInfos.clear();
11414
11415 return true;
11416}
11417
11419 ObjCLayouts[CD] = nullptr;
11420}
11421
11422/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
11423/// 'RHS' attributes and returns the merged version; including for function
11424/// return types.
11426 QualType LHSCan = getCanonicalType(LHS),
11427 RHSCan = getCanonicalType(RHS);
11428 // If two types are identical, they are compatible.
11429 if (LHSCan == RHSCan)
11430 return LHS;
11431 if (RHSCan->isFunctionType()) {
11432 if (!LHSCan->isFunctionType())
11433 return {};
11434 QualType OldReturnType =
11435 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
11436 QualType NewReturnType =
11437 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
11438 QualType ResReturnType =
11439 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
11440 if (ResReturnType.isNull())
11441 return {};
11442 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
11443 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
11444 // In either case, use OldReturnType to build the new function type.
11445 const auto *F = LHS->castAs<FunctionType>();
11446 if (const auto *FPT = cast<FunctionProtoType>(F)) {
11447 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11448 EPI.ExtInfo = getFunctionExtInfo(LHS);
11449 QualType ResultType =
11450 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
11451 return ResultType;
11452 }
11453 }
11454 return {};
11455 }
11456
11457 // If the qualifiers are different, the types can still be merged.
11458 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11459 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11460 if (LQuals != RQuals) {
11461 // If any of these qualifiers are different, we have a type mismatch.
11462 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11463 LQuals.getAddressSpace() != RQuals.getAddressSpace())
11464 return {};
11465
11466 // Exactly one GC qualifier difference is allowed: __strong is
11467 // okay if the other type has no GC qualifier but is an Objective
11468 // C object pointer (i.e. implicitly strong by default). We fix
11469 // this by pretending that the unqualified type was actually
11470 // qualified __strong.
11471 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11472 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11473 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11474
11475 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11476 return {};
11477
11478 if (GC_L == Qualifiers::Strong)
11479 return LHS;
11480 if (GC_R == Qualifiers::Strong)
11481 return RHS;
11482 return {};
11483 }
11484
11485 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
11486 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11487 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11488 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
11489 if (ResQT == LHSBaseQT)
11490 return LHS;
11491 if (ResQT == RHSBaseQT)
11492 return RHS;
11493 }
11494 return {};
11495}
11496
11497//===----------------------------------------------------------------------===//
11498// Integer Predicates
11499//===----------------------------------------------------------------------===//
11500
11502 if (const auto *ET = T->getAs<EnumType>())
11503 T = ET->getDecl()->getIntegerType();
11504 if (T->isBooleanType())
11505 return 1;
11506 if (const auto *EIT = T->getAs<BitIntType>())
11507 return EIT->getNumBits();
11508 // For builtin types, just use the standard type sizing method
11509 return (unsigned)getTypeSize(T);
11510}
11511
11513 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11514 T->isFixedPointType()) &&
11515 "Unexpected type");
11516
11517 // Turn <4 x signed int> -> <4 x unsigned int>
11518 if (const auto *VTy = T->getAs<VectorType>())
11519 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
11520 VTy->getNumElements(), VTy->getVectorKind());
11521
11522 // For _BitInt, return an unsigned _BitInt with same width.
11523 if (const auto *EITy = T->getAs<BitIntType>())
11524 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
11525
11526 // For enums, get the underlying integer type of the enum, and let the general
11527 // integer type signchanging code handle it.
11528 if (const auto *ETy = T->getAs<EnumType>())
11529 T = ETy->getDecl()->getIntegerType();
11530
11531 switch (T->castAs<BuiltinType>()->getKind()) {
11532 case BuiltinType::Char_U:
11533 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
11534 case BuiltinType::Char_S:
11535 case BuiltinType::SChar:
11536 case BuiltinType::Char8:
11537 return UnsignedCharTy;
11538 case BuiltinType::Short:
11539 return UnsignedShortTy;
11540 case BuiltinType::Int:
11541 return UnsignedIntTy;
11542 case BuiltinType::Long:
11543 return UnsignedLongTy;
11544 case BuiltinType::LongLong:
11545 return UnsignedLongLongTy;
11546 case BuiltinType::Int128:
11547 return UnsignedInt128Ty;
11548 // wchar_t is special. It is either signed or not, but when it's signed,
11549 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
11550 // version of its underlying type instead.
11551 case BuiltinType::WChar_S:
11552 return getUnsignedWCharType();
11553
11554 case BuiltinType::ShortAccum:
11555 return UnsignedShortAccumTy;
11556 case BuiltinType::Accum:
11557 return UnsignedAccumTy;
11558 case BuiltinType::LongAccum:
11559 return UnsignedLongAccumTy;
11560 case BuiltinType::SatShortAccum:
11562 case BuiltinType::SatAccum:
11563 return SatUnsignedAccumTy;
11564 case BuiltinType::SatLongAccum:
11566 case BuiltinType::ShortFract:
11567 return UnsignedShortFractTy;
11568 case BuiltinType::Fract:
11569 return UnsignedFractTy;
11570 case BuiltinType::LongFract:
11571 return UnsignedLongFractTy;
11572 case BuiltinType::SatShortFract:
11574 case BuiltinType::SatFract:
11575 return SatUnsignedFractTy;
11576 case BuiltinType::SatLongFract:
11578 default:
11581 "Unexpected signed integer or fixed point type");
11582 return T;
11583 }
11584}
11585
11587 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11588 T->isFixedPointType()) &&
11589 "Unexpected type");
11590
11591 // Turn <4 x unsigned int> -> <4 x signed int>
11592 if (const auto *VTy = T->getAs<VectorType>())
11593 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
11594 VTy->getNumElements(), VTy->getVectorKind());
11595
11596 // For _BitInt, return a signed _BitInt with same width.
11597 if (const auto *EITy = T->getAs<BitIntType>())
11598 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
11599
11600 // For enums, get the underlying integer type of the enum, and let the general
11601 // integer type signchanging code handle it.
11602 if (const auto *ETy = T->getAs<EnumType>())
11603 T = ETy->getDecl()->getIntegerType();
11604
11605 switch (T->castAs<BuiltinType>()->getKind()) {
11606 case BuiltinType::Char_S:
11607 // Plain `char` is mapped to `signed char` even if it's already signed
11608 case BuiltinType::Char_U:
11609 case BuiltinType::UChar:
11610 case BuiltinType::Char8:
11611 return SignedCharTy;
11612 case BuiltinType::UShort:
11613 return ShortTy;
11614 case BuiltinType::UInt:
11615 return IntTy;
11616 case BuiltinType::ULong:
11617 return LongTy;
11618 case BuiltinType::ULongLong:
11619 return LongLongTy;
11620 case BuiltinType::UInt128:
11621 return Int128Ty;
11622 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
11623 // there's no matching "signed wchar_t". Therefore we return the signed
11624 // version of its underlying type instead.
11625 case BuiltinType::WChar_U:
11626 return getSignedWCharType();
11627
11628 case BuiltinType::UShortAccum:
11629 return ShortAccumTy;
11630 case BuiltinType::UAccum:
11631 return AccumTy;
11632 case BuiltinType::ULongAccum:
11633 return LongAccumTy;
11634 case BuiltinType::SatUShortAccum:
11635 return SatShortAccumTy;
11636 case BuiltinType::SatUAccum:
11637 return SatAccumTy;
11638 case BuiltinType::SatULongAccum:
11639 return SatLongAccumTy;
11640 case BuiltinType::UShortFract:
11641 return ShortFractTy;
11642 case BuiltinType::UFract:
11643 return FractTy;
11644 case BuiltinType::ULongFract:
11645 return LongFractTy;
11646 case BuiltinType::SatUShortFract:
11647 return SatShortFractTy;
11648 case BuiltinType::SatUFract:
11649 return SatFractTy;
11650 case BuiltinType::SatULongFract:
11651 return SatLongFractTy;
11652 default:
11653 assert(
11655 "Unexpected signed integer or fixed point type");
11656 return T;
11657 }
11658}
11659
11661
11663 QualType ReturnType) {}
11664
11665//===----------------------------------------------------------------------===//
11666// Builtin Type Computation
11667//===----------------------------------------------------------------------===//
11668
11669/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
11670/// pointer over the consumed characters. This returns the resultant type. If
11671/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
11672/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
11673/// a vector of "i*".
11674///
11675/// RequiresICE is filled in on return to indicate whether the value is required
11676/// to be an Integer Constant Expression.
11677static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
11679 bool &RequiresICE,
11680 bool AllowTypeModifiers) {
11681 // Modifiers.
11682 int HowLong = 0;
11683 bool Signed = false, Unsigned = false;
11684 RequiresICE = false;
11685
11686 // Read the prefixed modifiers first.
11687 bool Done = false;
11688 #ifndef NDEBUG
11689 bool IsSpecial = false;
11690 #endif
11691 while (!Done) {
11692 switch (*Str++) {
11693 default: Done = true; --Str; break;
11694 case 'I':
11695 RequiresICE = true;
11696 break;
11697 case 'S':
11698 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
11699 assert(!Signed && "Can't use 'S' modifier multiple times!");
11700 Signed = true;
11701 break;
11702 case 'U':
11703 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
11704 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
11705 Unsigned = true;
11706 break;
11707 case 'L':
11708 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
11709 assert(HowLong <= 2 && "Can't have LLLL modifier");
11710 ++HowLong;
11711 break;
11712 case 'N':
11713 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
11714 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11715 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
11716 #ifndef NDEBUG
11717 IsSpecial = true;
11718 #endif
11719 if (Context.getTargetInfo().getLongWidth() == 32)
11720 ++HowLong;
11721 break;
11722 case 'W':
11723 // This modifier represents int64 type.
11724 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11725 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
11726 #ifndef NDEBUG
11727 IsSpecial = true;
11728 #endif
11729 switch (Context.getTargetInfo().getInt64Type()) {
11730 default:
11731 llvm_unreachable("Unexpected integer type");
11733 HowLong = 1;
11734 break;
11736 HowLong = 2;
11737 break;
11738 }
11739 break;
11740 case 'Z':
11741 // This modifier represents int32 type.
11742 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11743 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
11744 #ifndef NDEBUG
11745 IsSpecial = true;
11746 #endif
11747 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
11748 default:
11749 llvm_unreachable("Unexpected integer type");
11751 HowLong = 0;
11752 break;
11754 HowLong = 1;
11755 break;
11757 HowLong = 2;
11758 break;
11759 }
11760 break;
11761 case 'O':
11762 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11763 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
11764 #ifndef NDEBUG
11765 IsSpecial = true;
11766 #endif
11767 if (Context.getLangOpts().OpenCL)
11768 HowLong = 1;
11769 else
11770 HowLong = 2;
11771 break;
11772 }
11773 }
11774
11775 QualType Type;
11776
11777 // Read the base type.
11778 switch (*Str++) {
11779 default: llvm_unreachable("Unknown builtin type letter!");
11780 case 'x':
11781 assert(HowLong == 0 && !Signed && !Unsigned &&
11782 "Bad modifiers used with 'x'!");
11783 Type = Context.Float16Ty;
11784 break;
11785 case 'y':
11786 assert(HowLong == 0 && !Signed && !Unsigned &&
11787 "Bad modifiers used with 'y'!");
11788 Type = Context.BFloat16Ty;
11789 break;
11790 case 'v':
11791 assert(HowLong == 0 && !Signed && !Unsigned &&
11792 "Bad modifiers used with 'v'!");
11793 Type = Context.VoidTy;
11794 break;
11795 case 'h':
11796 assert(HowLong == 0 && !Signed && !Unsigned &&
11797 "Bad modifiers used with 'h'!");
11798 Type = Context.HalfTy;
11799 break;
11800 case 'f':
11801 assert(HowLong == 0 && !Signed && !Unsigned &&
11802 "Bad modifiers used with 'f'!");
11803 Type = Context.FloatTy;
11804 break;
11805 case 'd':
11806 assert(HowLong < 3 && !Signed && !Unsigned &&
11807 "Bad modifiers used with 'd'!");
11808 if (HowLong == 1)
11809 Type = Context.LongDoubleTy;
11810 else if (HowLong == 2)
11811 Type = Context.Float128Ty;
11812 else
11813 Type = Context.DoubleTy;
11814 break;
11815 case 's':
11816 assert(HowLong == 0 && "Bad modifiers used with 's'!");
11817 if (Unsigned)
11818 Type = Context.UnsignedShortTy;
11819 else
11820 Type = Context.ShortTy;
11821 break;
11822 case 'i':
11823 if (HowLong == 3)
11824 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
11825 else if (HowLong == 2)
11826 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
11827 else if (HowLong == 1)
11828 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
11829 else
11830 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
11831 break;
11832 case 'c':
11833 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
11834 if (Signed)
11835 Type = Context.SignedCharTy;
11836 else if (Unsigned)
11837 Type = Context.UnsignedCharTy;
11838 else
11839 Type = Context.CharTy;
11840 break;
11841 case 'b': // boolean
11842 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
11843 Type = Context.BoolTy;
11844 break;
11845 case 'z': // size_t.
11846 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
11847 Type = Context.getSizeType();
11848 break;
11849 case 'w': // wchar_t.
11850 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
11851 Type = Context.getWideCharType();
11852 break;
11853 case 'F':
11854 Type = Context.getCFConstantStringType();
11855 break;
11856 case 'G':
11857 Type = Context.getObjCIdType();
11858 break;
11859 case 'H':
11860 Type = Context.getObjCSelType();
11861 break;
11862 case 'M':
11863 Type = Context.getObjCSuperType();
11864 break;
11865 case 'a':
11866 Type = Context.getBuiltinVaListType();
11867 assert(!Type.isNull() && "builtin va list type not initialized!");
11868 break;
11869 case 'A':
11870 // This is a "reference" to a va_list; however, what exactly
11871 // this means depends on how va_list is defined. There are two
11872 // different kinds of va_list: ones passed by value, and ones
11873 // passed by reference. An example of a by-value va_list is
11874 // x86, where va_list is a char*. An example of by-ref va_list
11875 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
11876 // we want this argument to be a char*&; for x86-64, we want
11877 // it to be a __va_list_tag*.
11878 Type = Context.getBuiltinVaListType();
11879 assert(!Type.isNull() && "builtin va list type not initialized!");
11880 if (Type->isArrayType())
11881 Type = Context.getArrayDecayedType(Type);
11882 else
11883 Type = Context.getLValueReferenceType(Type);
11884 break;
11885 case 'q': {
11886 char *End;
11887 unsigned NumElements = strtoul(Str, &End, 10);
11888 assert(End != Str && "Missing vector size");
11889 Str = End;
11890
11891 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11892 RequiresICE, false);
11893 assert(!RequiresICE && "Can't require vector ICE");
11894
11895 Type = Context.getScalableVectorType(ElementType, NumElements);
11896 break;
11897 }
11898 case 'Q': {
11899 switch (*Str++) {
11900 case 'a': {
11901 Type = Context.SveCountTy;
11902 break;
11903 }
11904 case 'b': {
11905 Type = Context.AMDGPUBufferRsrcTy;
11906 break;
11907 }
11908 default:
11909 llvm_unreachable("Unexpected target builtin type");
11910 }
11911 break;
11912 }
11913 case 'V': {
11914 char *End;
11915 unsigned NumElements = strtoul(Str, &End, 10);
11916 assert(End != Str && "Missing vector size");
11917 Str = End;
11918
11919 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11920 RequiresICE, false);
11921 assert(!RequiresICE && "Can't require vector ICE");
11922
11923 // TODO: No way to make AltiVec vectors in builtins yet.
11924 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
11925 break;
11926 }
11927 case 'E': {
11928 char *End;
11929
11930 unsigned NumElements = strtoul(Str, &End, 10);
11931 assert(End != Str && "Missing vector size");
11932
11933 Str = End;
11934
11935 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11936 false);
11937 Type = Context.getExtVectorType(ElementType, NumElements);
11938 break;
11939 }
11940 case 'X': {
11941 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11942 false);
11943 assert(!RequiresICE && "Can't require complex ICE");
11944 Type = Context.getComplexType(ElementType);
11945 break;
11946 }
11947 case 'Y':
11948 Type = Context.getPointerDiffType();
11949 break;
11950 case 'P':
11951 Type = Context.getFILEType();
11952 if (Type.isNull()) {
11954 return {};
11955 }
11956 break;
11957 case 'J':
11958 if (Signed)
11959 Type = Context.getsigjmp_bufType();
11960 else
11961 Type = Context.getjmp_bufType();
11962
11963 if (Type.isNull()) {
11965 return {};
11966 }
11967 break;
11968 case 'K':
11969 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
11970 Type = Context.getucontext_tType();
11971
11972 if (Type.isNull()) {
11974 return {};
11975 }
11976 break;
11977 case 'p':
11978 Type = Context.getProcessIDType();
11979 break;
11980 }
11981
11982 // If there are modifiers and if we're allowed to parse them, go for it.
11983 Done = !AllowTypeModifiers;
11984 while (!Done) {
11985 switch (char c = *Str++) {
11986 default: Done = true; --Str; break;
11987 case '*':
11988 case '&': {
11989 // Both pointers and references can have their pointee types
11990 // qualified with an address space.
11991 char *End;
11992 unsigned AddrSpace = strtoul(Str, &End, 10);
11993 if (End != Str) {
11994 // Note AddrSpace == 0 is not the same as an unspecified address space.
11995 Type = Context.getAddrSpaceQualType(
11996 Type,
11997 Context.getLangASForBuiltinAddressSpace(AddrSpace));
11998 Str = End;
11999 }
12000 if (c == '*')
12001 Type = Context.getPointerType(Type);
12002 else
12003 Type = Context.getLValueReferenceType(Type);
12004 break;
12005 }
12006 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12007 case 'C':
12008 Type = Type.withConst();
12009 break;
12010 case 'D':
12011 Type = Context.getVolatileType(Type);
12012 break;
12013 case 'R':
12014 Type = Type.withRestrict();
12015 break;
12016 }
12017 }
12018
12019 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12020 "Integer constant 'I' type must be an integer");
12021
12022 return Type;
12023}
12024
12025// On some targets such as PowerPC, some of the builtins are defined with custom
12026// type descriptors for target-dependent types. These descriptors are decoded in
12027// other functions, but it may be useful to be able to fall back to default
12028// descriptor decoding to define builtins mixing target-dependent and target-
12029// independent types. This function allows decoding one type descriptor with
12030// default decoding.
12031QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12032 GetBuiltinTypeError &Error, bool &RequireICE,
12033 bool AllowTypeModifiers) const {
12034 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12035}
12036
12037/// GetBuiltinType - Return the type for the specified builtin.
12039 GetBuiltinTypeError &Error,
12040 unsigned *IntegerConstantArgs) const {
12041 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12042 if (TypeStr[0] == '\0') {
12043 Error = GE_Missing_type;
12044 return {};
12045 }
12046
12047 SmallVector<QualType, 8> ArgTypes;
12048
12049 bool RequiresICE = false;
12050 Error = GE_None;
12051 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12052 RequiresICE, true);
12053 if (Error != GE_None)
12054 return {};
12055
12056 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12057
12058 while (TypeStr[0] && TypeStr[0] != '.') {
12059 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12060 if (Error != GE_None)
12061 return {};
12062
12063 // If this argument is required to be an IntegerConstantExpression and the
12064 // caller cares, fill in the bitmask we return.
12065 if (RequiresICE && IntegerConstantArgs)
12066 *IntegerConstantArgs |= 1 << ArgTypes.size();
12067
12068 // Do array -> pointer decay. The builtin should use the decayed type.
12069 if (Ty->isArrayType())
12070 Ty = getArrayDecayedType(Ty);
12071
12072 ArgTypes.push_back(Ty);
12073 }
12074
12075 if (Id == Builtin::BI__GetExceptionInfo)
12076 return {};
12077
12078 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12079 "'.' should only occur at end of builtin type list!");
12080
12081 bool Variadic = (TypeStr[0] == '.');
12082
12084 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
12085 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
12086
12087
12088 // We really shouldn't be making a no-proto type here.
12089 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12090 return getFunctionNoProtoType(ResType, EI);
12091
12093 EPI.ExtInfo = EI;
12094 EPI.Variadic = Variadic;
12096 EPI.ExceptionSpec.Type =
12098
12099 return getFunctionType(ResType, ArgTypes, EPI);
12100}
12101
12103 const FunctionDecl *FD) {
12104 if (!FD->isExternallyVisible())
12105 return GVA_Internal;
12106
12107 // Non-user-provided functions get emitted as weak definitions with every
12108 // use, no matter whether they've been explicitly instantiated etc.
12109 if (!FD->isUserProvided())
12110 return GVA_DiscardableODR;
12111
12113 switch (FD->getTemplateSpecializationKind()) {
12114 case TSK_Undeclared:
12117 break;
12118
12120 return GVA_StrongODR;
12121
12122 // C++11 [temp.explicit]p10:
12123 // [ Note: The intent is that an inline function that is the subject of
12124 // an explicit instantiation declaration will still be implicitly
12125 // instantiated when used so that the body can be considered for
12126 // inlining, but that no out-of-line copy of the inline function would be
12127 // generated in the translation unit. -- end note ]
12130
12133 break;
12134 }
12135
12136 if (!FD->isInlined())
12137 return External;
12138
12139 if ((!Context.getLangOpts().CPlusPlus &&
12140 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12141 !FD->hasAttr<DLLExportAttr>()) ||
12142 FD->hasAttr<GNUInlineAttr>()) {
12143 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12144
12145 // GNU or C99 inline semantics. Determine whether this symbol should be
12146 // externally visible.
12148 return External;
12149
12150 // C99 inline semantics, where the symbol is not externally visible.
12152 }
12153
12154 // Functions specified with extern and inline in -fms-compatibility mode
12155 // forcibly get emitted. While the body of the function cannot be later
12156 // replaced, the function definition cannot be discarded.
12157 if (FD->isMSExternInline())
12158 return GVA_StrongODR;
12159
12160 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12161 isa<CXXConstructorDecl>(FD) &&
12162 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12163 // Our approach to inheriting constructors is fundamentally different from
12164 // that used by the MS ABI, so keep our inheriting constructor thunks
12165 // internal rather than trying to pick an unambiguous mangling for them.
12166 return GVA_Internal;
12167
12168 return GVA_DiscardableODR;
12169}
12170
12172 const Decl *D, GVALinkage L) {
12173 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12174 // dllexport/dllimport on inline functions.
12175 if (D->hasAttr<DLLImportAttr>()) {
12176 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12178 } else if (D->hasAttr<DLLExportAttr>()) {
12179 if (L == GVA_DiscardableODR)
12180 return GVA_StrongODR;
12181 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12182 // Device-side functions with __global__ attribute must always be
12183 // visible externally so they can be launched from host.
12184 if (D->hasAttr<CUDAGlobalAttr>() &&
12185 (L == GVA_DiscardableODR || L == GVA_Internal))
12186 return GVA_StrongODR;
12187 // Single source offloading languages like CUDA/HIP need to be able to
12188 // access static device variables from host code of the same compilation
12189 // unit. This is done by externalizing the static variable with a shared
12190 // name between the host and device compilation which is the same for the
12191 // same compilation unit whereas different among different compilation
12192 // units.
12193 if (Context.shouldExternalize(D))
12194 return GVA_StrongExternal;
12195 }
12196 return L;
12197}
12198
12199/// Adjust the GVALinkage for a declaration based on what an external AST source
12200/// knows about whether there can be other definitions of this declaration.
12201static GVALinkage
12203 GVALinkage L) {
12204 ExternalASTSource *Source = Ctx.getExternalSource();
12205 if (!Source)
12206 return L;
12207
12208 switch (Source->hasExternalDefinitions(D)) {
12210 // Other translation units rely on us to provide the definition.
12211 if (L == GVA_DiscardableODR)
12212 return GVA_StrongODR;
12213 break;
12214
12217
12219 break;
12220 }
12221 return L;
12222}
12223
12227 basicGVALinkageForFunction(*this, FD)));
12228}
12229
12231 const VarDecl *VD) {
12232 // As an extension for interactive REPLs, make sure constant variables are
12233 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12234 // marking them as internal.
12235 if (Context.getLangOpts().CPlusPlus &&
12236 Context.getLangOpts().IncrementalExtensions &&
12237 VD->getType().isConstQualified() &&
12238 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12239 !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate())
12240 return GVA_DiscardableODR;
12241
12242 if (!VD->isExternallyVisible())
12243 return GVA_Internal;
12244
12245 if (VD->isStaticLocal()) {
12246 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12247 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12248 LexicalContext = LexicalContext->getLexicalParent();
12249
12250 // ObjC Blocks can create local variables that don't have a FunctionDecl
12251 // LexicalContext.
12252 if (!LexicalContext)
12253 return GVA_DiscardableODR;
12254
12255 // Otherwise, let the static local variable inherit its linkage from the
12256 // nearest enclosing function.
12257 auto StaticLocalLinkage =
12258 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12259
12260 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12261 // be emitted in any object with references to the symbol for the object it
12262 // contains, whether inline or out-of-line."
12263 // Similar behavior is observed with MSVC. An alternative ABI could use
12264 // StrongODR/AvailableExternally to match the function, but none are
12265 // known/supported currently.
12266 if (StaticLocalLinkage == GVA_StrongODR ||
12267 StaticLocalLinkage == GVA_AvailableExternally)
12268 return GVA_DiscardableODR;
12269 return StaticLocalLinkage;
12270 }
12271
12272 // MSVC treats in-class initialized static data members as definitions.
12273 // By giving them non-strong linkage, out-of-line definitions won't
12274 // cause link errors.
12276 return GVA_DiscardableODR;
12277
12278 // Most non-template variables have strong linkage; inline variables are
12279 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12280 GVALinkage StrongLinkage;
12281 switch (Context.getInlineVariableDefinitionKind(VD)) {
12283 StrongLinkage = GVA_StrongExternal;
12284 break;
12287 StrongLinkage = GVA_DiscardableODR;
12288 break;
12290 StrongLinkage = GVA_StrongODR;
12291 break;
12292 }
12293
12294 switch (VD->getTemplateSpecializationKind()) {
12295 case TSK_Undeclared:
12296 return StrongLinkage;
12297
12299 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12300 VD->isStaticDataMember()
12302 : StrongLinkage;
12303
12305 return GVA_StrongODR;
12306
12309
12311 return GVA_DiscardableODR;
12312 }
12313
12314 llvm_unreachable("Invalid Linkage!");
12315}
12316
12320 basicGVALinkageForVariable(*this, VD)));
12321}
12322
12324 if (const auto *VD = dyn_cast<VarDecl>(D)) {
12325 if (!VD->isFileVarDecl())
12326 return false;
12327 // Global named register variables (GNU extension) are never emitted.
12328 if (VD->getStorageClass() == SC_Register)
12329 return false;
12330 if (VD->getDescribedVarTemplate() ||
12331 isa<VarTemplatePartialSpecializationDecl>(VD))
12332 return false;
12333 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12334 // We never need to emit an uninstantiated function template.
12335 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12336 return false;
12337 } else if (isa<PragmaCommentDecl>(D))
12338 return true;
12339 else if (isa<PragmaDetectMismatchDecl>(D))
12340 return true;
12341 else if (isa<OMPRequiresDecl>(D))
12342 return true;
12343 else if (isa<OMPThreadPrivateDecl>(D))
12344 return !D->getDeclContext()->isDependentContext();
12345 else if (isa<OMPAllocateDecl>(D))
12346 return !D->getDeclContext()->isDependentContext();
12347 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
12348 return !D->getDeclContext()->isDependentContext();
12349 else if (isa<ImportDecl>(D))
12350 return true;
12351 else
12352 return false;
12353
12354 // If this is a member of a class template, we do not need to emit it.
12356 return false;
12357
12358 // Weak references don't produce any output by themselves.
12359 if (D->hasAttr<WeakRefAttr>())
12360 return false;
12361
12362 // Aliases and used decls are required.
12363 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
12364 return true;
12365
12366 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12367 // Forward declarations aren't required.
12368 if (!FD->doesThisDeclarationHaveABody())
12369 return FD->doesDeclarationForceExternallyVisibleDefinition();
12370
12371 // Constructors and destructors are required.
12372 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
12373 return true;
12374
12375 // The key function for a class is required. This rule only comes
12376 // into play when inline functions can be key functions, though.
12377 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12378 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12379 const CXXRecordDecl *RD = MD->getParent();
12380 if (MD->isOutOfLine() && RD->isDynamicClass()) {
12381 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
12382 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
12383 return true;
12384 }
12385 }
12386 }
12387
12389
12390 // static, static inline, always_inline, and extern inline functions can
12391 // always be deferred. Normal inline functions can be deferred in C99/C++.
12392 // Implicit template instantiations can also be deferred in C++.
12394 }
12395
12396 const auto *VD = cast<VarDecl>(D);
12397 assert(VD->isFileVarDecl() && "Expected file scoped var");
12398
12399 // If the decl is marked as `declare target to`, it should be emitted for the
12400 // host and for the device.
12401 if (LangOpts.OpenMP &&
12402 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
12403 return true;
12404
12405 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
12407 return false;
12408
12409 // Variables in other module units shouldn't be forced to be emitted.
12410 if (VD->isInAnotherModuleUnit())
12411 return false;
12412
12413 // Variables that can be needed in other TUs are required.
12416 return true;
12417
12418 // We never need to emit a variable that is available in another TU.
12420 return false;
12421
12422 // Variables that have destruction with side-effects are required.
12423 if (VD->needsDestruction(*this))
12424 return true;
12425
12426 // Variables that have initialization with side-effects are required.
12427 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
12428 // We can get a value-dependent initializer during error recovery.
12429 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
12430 return true;
12431
12432 // Likewise, variables with tuple-like bindings are required if their
12433 // bindings have side-effects.
12434 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
12435 for (const auto *BD : DD->bindings())
12436 if (const auto *BindingVD = BD->getHoldingVar())
12437 if (DeclMustBeEmitted(BindingVD))
12438 return true;
12439
12440 return false;
12441}
12442
12444 const FunctionDecl *FD,
12445 llvm::function_ref<void(FunctionDecl *)> Pred) const {
12446 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
12447 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
12448 FD = FD->getMostRecentDecl();
12449 // FIXME: The order of traversal here matters and depends on the order of
12450 // lookup results, which happens to be (mostly) oldest-to-newest, but we
12451 // shouldn't rely on that.
12452 for (auto *CurDecl :
12454 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
12455 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
12456 !SeenDecls.contains(CurFD)) {
12457 SeenDecls.insert(CurFD);
12458 Pred(CurFD);
12459 }
12460 }
12461}
12462
12464 bool IsCXXMethod,
12465 bool IsBuiltin) const {
12466 // Pass through to the C++ ABI object
12467 if (IsCXXMethod)
12468 return ABI->getDefaultMethodCallConv(IsVariadic);
12469
12470 // Builtins ignore user-specified default calling convention and remain the
12471 // Target's default calling convention.
12472 if (!IsBuiltin) {
12473 switch (LangOpts.getDefaultCallingConv()) {
12475 break;
12477 return CC_C;
12479 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
12480 return CC_X86FastCall;
12481 break;
12483 if (!IsVariadic)
12484 return CC_X86StdCall;
12485 break;
12487 // __vectorcall cannot be applied to variadic functions.
12488 if (!IsVariadic)
12489 return CC_X86VectorCall;
12490 break;
12492 // __regcall cannot be applied to variadic functions.
12493 if (!IsVariadic)
12494 return CC_X86RegCall;
12495 break;
12497 if (!IsVariadic)
12498 return CC_M68kRTD;
12499 break;
12500 }
12501 }
12502 return Target->getDefaultCallingConv();
12503}
12504
12506 // Pass through to the C++ ABI object
12507 return ABI->isNearlyEmpty(RD);
12508}
12509
12511 if (!VTContext.get()) {
12512 auto ABI = Target->getCXXABI();
12513 if (ABI.isMicrosoft())
12514 VTContext.reset(new MicrosoftVTableContext(*this));
12515 else {
12516 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
12519 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
12520 }
12521 }
12522 return VTContext.get();
12523}
12524
12526 if (!T)
12527 T = Target;
12528 switch (T->getCXXABI().getKind()) {
12529 case TargetCXXABI::AppleARM64:
12530 case TargetCXXABI::Fuchsia:
12531 case TargetCXXABI::GenericAArch64:
12532 case TargetCXXABI::GenericItanium:
12533 case TargetCXXABI::GenericARM:
12534 case TargetCXXABI::GenericMIPS:
12535 case TargetCXXABI::iOS:
12536 case TargetCXXABI::WebAssembly:
12537 case TargetCXXABI::WatchOS:
12538 case TargetCXXABI::XL:
12540 case TargetCXXABI::Microsoft:
12542 }
12543 llvm_unreachable("Unsupported ABI");
12544}
12545
12547 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
12548 "Device mangle context does not support Microsoft mangling.");
12549 switch (T.getCXXABI().getKind()) {
12550 case TargetCXXABI::AppleARM64:
12551 case TargetCXXABI::Fuchsia:
12552 case TargetCXXABI::GenericAArch64:
12553 case TargetCXXABI::GenericItanium:
12554 case TargetCXXABI::GenericARM:
12555 case TargetCXXABI::GenericMIPS:
12556 case TargetCXXABI::iOS:
12557 case TargetCXXABI::WebAssembly:
12558 case TargetCXXABI::WatchOS:
12559 case TargetCXXABI::XL:
12561 *this, getDiagnostics(),
12562 [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> {
12563 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
12564 return RD->getDeviceLambdaManglingNumber();
12565 return std::nullopt;
12566 },
12567 /*IsAux=*/true);
12568 case TargetCXXABI::Microsoft:
12570 /*IsAux=*/true);
12571 }
12572 llvm_unreachable("Unsupported ABI");
12573}
12574
12575CXXABI::~CXXABI() = default;
12576
12578 return ASTRecordLayouts.getMemorySize() +
12579 llvm::capacity_in_bytes(ObjCLayouts) +
12580 llvm::capacity_in_bytes(KeyFunctions) +
12581 llvm::capacity_in_bytes(ObjCImpls) +
12582 llvm::capacity_in_bytes(BlockVarCopyInits) +
12583 llvm::capacity_in_bytes(DeclAttrs) +
12584 llvm::capacity_in_bytes(TemplateOrInstantiation) +
12585 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
12586 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
12587 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
12588 llvm::capacity_in_bytes(OverriddenMethods) +
12589 llvm::capacity_in_bytes(Types) +
12590 llvm::capacity_in_bytes(VariableArrayTypes);
12591}
12592
12593/// getIntTypeForBitwidth -
12594/// sets integer QualTy according to specified details:
12595/// bitwidth, signed/unsigned.
12596/// Returns empty type if there is no appropriate target types.
12598 unsigned Signed) const {
12600 CanQualType QualTy = getFromTargetType(Ty);
12601 if (!QualTy && DestWidth == 128)
12602 return Signed ? Int128Ty : UnsignedInt128Ty;
12603 return QualTy;
12604}
12605
12606/// getRealTypeForBitwidth -
12607/// sets floating point QualTy according to specified bitwidth.
12608/// Returns empty type if there is no appropriate target types.
12610 FloatModeKind ExplicitType) const {
12611 FloatModeKind Ty =
12612 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
12613 switch (Ty) {
12615 return HalfTy;
12617 return FloatTy;
12619 return DoubleTy;
12621 return LongDoubleTy;
12623 return Float128Ty;
12625 return Ibm128Ty;
12627 return {};
12628 }
12629
12630 llvm_unreachable("Unhandled TargetInfo::RealType value");
12631}
12632
12633void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
12634 if (Number <= 1)
12635 return;
12636
12637 MangleNumbers[ND] = Number;
12638
12639 if (Listener)
12640 Listener->AddedManglingNumber(ND, Number);
12641}
12642
12644 bool ForAuxTarget) const {
12645 auto I = MangleNumbers.find(ND);
12646 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
12647 // CUDA/HIP host compilation encodes host and device mangling numbers
12648 // as lower and upper half of 32 bit integer.
12649 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
12650 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
12651 } else {
12652 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
12653 "number for aux target");
12654 }
12655 return Res > 1 ? Res : 1;
12656}
12657
12658void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
12659 if (Number <= 1)
12660 return;
12661
12662 StaticLocalNumbers[VD] = Number;
12663
12664 if (Listener)
12665 Listener->AddedStaticLocalNumbers(VD, Number);
12666}
12667
12669 auto I = StaticLocalNumbers.find(VD);
12670 return I != StaticLocalNumbers.end() ? I->second : 1;
12671}
12672
12675 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12676 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
12677 if (!MCtx)
12679 return *MCtx;
12680}
12681
12684 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12685 std::unique_ptr<MangleNumberingContext> &MCtx =
12686 ExtraMangleNumberingContexts[D];
12687 if (!MCtx)
12689 return *MCtx;
12690}
12691
12692std::unique_ptr<MangleNumberingContext>
12694 return ABI->createMangleNumberingContext();
12695}
12696
12697const CXXConstructorDecl *
12699 return ABI->getCopyConstructorForExceptionObject(
12700 cast<CXXRecordDecl>(RD->getFirstDecl()));
12701}
12702
12704 CXXConstructorDecl *CD) {
12705 return ABI->addCopyConstructorForExceptionObject(
12706 cast<CXXRecordDecl>(RD->getFirstDecl()),
12707 cast<CXXConstructorDecl>(CD->getFirstDecl()));
12708}
12709
12711 TypedefNameDecl *DD) {
12712 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
12713}
12714
12717 return ABI->getTypedefNameForUnnamedTagDecl(TD);
12718}
12719
12721 DeclaratorDecl *DD) {
12722 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
12723}
12724
12726 return ABI->getDeclaratorForUnnamedTagDecl(TD);
12727}
12728
12729void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
12730 ParamIndices[D] = index;
12731}
12732
12734 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
12735 assert(I != ParamIndices.end() &&
12736 "ParmIndices lacks entry set by ParmVarDecl");
12737 return I->second;
12738}
12739
12741 unsigned Length) const {
12742 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
12743 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
12744 EltTy = EltTy.withConst();
12745
12746 EltTy = adjustStringLiteralBaseType(EltTy);
12747
12748 // Get an array type for the string, according to C99 6.4.5. This includes
12749 // the null terminator character.
12750 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
12751 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
12752}
12753
12756 StringLiteral *&Result = StringLiteralCache[Key];
12757 if (!Result)
12759 *this, Key, StringLiteralKind::Ordinary,
12760 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
12761 SourceLocation());
12762 return Result;
12763}
12764
12765MSGuidDecl *
12767 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
12768
12769 llvm::FoldingSetNodeID ID;
12770 MSGuidDecl::Profile(ID, Parts);
12771
12772 void *InsertPos;
12773 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
12774 return Existing;
12775
12776 QualType GUIDType = getMSGuidType().withConst();
12777 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
12778 MSGuidDecls.InsertNode(New, InsertPos);
12779 return New;
12780}
12781
12784 const APValue &APVal) const {
12785 llvm::FoldingSetNodeID ID;
12787
12788 void *InsertPos;
12789 if (UnnamedGlobalConstantDecl *Existing =
12790 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
12791 return Existing;
12792
12794 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
12795 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
12796 return New;
12797}
12798
12801 assert(T->isRecordType() && "template param object of unexpected type");
12802
12803 // C++ [temp.param]p8:
12804 // [...] a static storage duration object of type 'const T' [...]
12805 T.addConst();
12806
12807 llvm::FoldingSetNodeID ID;
12809
12810 void *InsertPos;
12811 if (TemplateParamObjectDecl *Existing =
12812 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
12813 return Existing;
12814
12815 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
12816 TemplateParamObjectDecls.InsertNode(New, InsertPos);
12817 return New;
12818}
12819
12821 const llvm::Triple &T = getTargetInfo().getTriple();
12822 if (!T.isOSDarwin())
12823 return false;
12824
12825 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
12826 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
12827 return false;
12828
12829 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
12830 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
12831 uint64_t Size = sizeChars.getQuantity();
12832 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
12833 unsigned Align = alignChars.getQuantity();
12834 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
12835 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
12836}
12837
12838bool
12840 const ObjCMethodDecl *MethodImpl) {
12841 // No point trying to match an unavailable/deprecated mothod.
12842 if (MethodDecl->hasAttr<UnavailableAttr>()
12843 || MethodDecl->hasAttr<DeprecatedAttr>())
12844 return false;
12845 if (MethodDecl->getObjCDeclQualifier() !=
12846 MethodImpl->getObjCDeclQualifier())
12847 return false;
12848 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
12849 return false;
12850
12851 if (MethodDecl->param_size() != MethodImpl->param_size())
12852 return false;
12853
12854 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
12855 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
12856 EF = MethodDecl->param_end();
12857 IM != EM && IF != EF; ++IM, ++IF) {
12858 const ParmVarDecl *DeclVar = (*IF);
12859 const ParmVarDecl *ImplVar = (*IM);
12860 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
12861 return false;
12862 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
12863 return false;
12864 }
12865
12866 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
12867}
12868
12870 LangAS AS;
12872 AS = LangAS::Default;
12873 else
12874 AS = QT->getPointeeType().getAddressSpace();
12875
12877}
12878
12881}
12882
12883bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
12884 if (X == Y)
12885 return true;
12886 if (!X || !Y)
12887 return false;
12888 llvm::FoldingSetNodeID IDX, IDY;
12889 X->Profile(IDX, *this, /*Canonical=*/true);
12890 Y->Profile(IDY, *this, /*Canonical=*/true);
12891 return IDX == IDY;
12892}
12893
12894// The getCommon* helpers return, for given 'same' X and Y entities given as
12895// inputs, another entity which is also the 'same' as the inputs, but which
12896// is closer to the canonical form of the inputs, each according to a given
12897// criteria.
12898// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
12899// the regular ones.
12900
12902 if (!declaresSameEntity(X, Y))
12903 return nullptr;
12904 for (const Decl *DX : X->redecls()) {
12905 // If we reach Y before reaching the first decl, that means X is older.
12906 if (DX == Y)
12907 return X;
12908 // If we reach the first decl, then Y is older.
12909 if (DX->isFirstDecl())
12910 return Y;
12911 }
12912 llvm_unreachable("Corrupt redecls chain");
12913}
12914
12915template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
12916static T *getCommonDecl(T *X, T *Y) {
12917 return cast_or_null<T>(
12918 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
12919 const_cast<Decl *>(cast_or_null<Decl>(Y))));
12920}
12921
12922template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
12923static T *getCommonDeclChecked(T *X, T *Y) {
12924 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
12925 const_cast<Decl *>(cast<Decl>(Y))));
12926}
12927
12929 TemplateName Y) {
12930 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
12931 return X;
12932 // FIXME: There are cases here where we could find a common template name
12933 // with more sugar. For example one could be a SubstTemplateTemplate*
12934 // replacing the other.
12936 if (CX.getAsVoidPointer() !=
12938 return TemplateName();
12939 return CX;
12940}
12941
12942static TemplateName
12945 assert(R.getAsVoidPointer() != nullptr);
12946 return R;
12947}
12948
12950 ArrayRef<QualType> Ys, bool Unqualified = false) {
12951 assert(Xs.size() == Ys.size());
12952 SmallVector<QualType, 8> Rs(Xs.size());
12953 for (size_t I = 0; I < Rs.size(); ++I)
12954 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
12955 return Rs;
12956}
12957
12958template <class T>
12959static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
12960 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
12961 : SourceLocation();
12962}
12963
12965 const TemplateArgument &X,
12966 const TemplateArgument &Y) {
12967 if (X.getKind() != Y.getKind())
12968 return TemplateArgument();
12969
12970 switch (X.getKind()) {
12972 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
12973 return TemplateArgument();
12974 return TemplateArgument(
12975 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
12977 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
12978 return TemplateArgument();
12979 return TemplateArgument(
12980 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
12981 /*Unqualified=*/true);
12983 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
12984 return TemplateArgument();
12985 // FIXME: Try to keep the common sugar.
12986 return X;
12988 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
12989 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
12990 if (!CTN.getAsVoidPointer())
12991 return TemplateArgument();
12992 return TemplateArgument(CTN);
12993 }
12995 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
12997 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
12998 if (!CTN.getAsVoidPointer())
12999 return TemplateName();
13000 auto NExpX = X.getNumTemplateExpansions();
13001 assert(NExpX == Y.getNumTemplateExpansions());
13002 return TemplateArgument(CTN, NExpX);
13003 }
13004 default:
13005 // FIXME: Handle the other argument kinds.
13006 return X;
13007 }
13008}
13009
13014 if (Xs.size() != Ys.size())
13015 return true;
13016 R.resize(Xs.size());
13017 for (size_t I = 0; I < R.size(); ++I) {
13018 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13019 if (R[I].isNull())
13020 return true;
13021 }
13022 return false;
13023}
13024
13029 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13030 assert(!Different);
13031 (void)Different;
13032 return R;
13033}
13034
13035template <class T>
13037 return X->getKeyword() == Y->getKeyword() ? X->getKeyword()
13039}
13040
13041template <class T>
13043 const T *Y) {
13044 // FIXME: Try to keep the common NNS sugar.
13045 return X->getQualifier() == Y->getQualifier()
13046 ? X->getQualifier()
13047 : Ctx.getCanonicalNestedNameSpecifier(X->getQualifier());
13048}
13049
13050template <class T>
13051static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y) {
13052 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13053}
13054
13055template <class T>
13057 Qualifiers &QX, const T *Y,
13058 Qualifiers &QY) {
13059 QualType EX = X->getElementType(), EY = Y->getElementType();
13060 QualType R = Ctx.getCommonSugaredType(EX, EY,
13061 /*Unqualified=*/true);
13062 Qualifiers RQ = R.getQualifiers();
13063 QX += EX.getQualifiers() - RQ;
13064 QY += EY.getQualifiers() - RQ;
13065 return R;
13066}
13067
13068template <class T>
13069static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y) {
13070 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13071}
13072
13073template <class T> static auto *getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y) {
13074 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13075 return X->getSizeExpr();
13076}
13077
13078static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13079 assert(X->getSizeModifier() == Y->getSizeModifier());
13080 return X->getSizeModifier();
13081}
13082
13084 const ArrayType *Y) {
13085 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13086 return X->getIndexTypeCVRQualifiers();
13087}
13088
13089// Merges two type lists such that the resulting vector will contain
13090// each type (in a canonical sense) only once, in the order they appear
13091// from X to Y. If they occur in both X and Y, the result will contain
13092// the common sugared type between them.
13095 llvm::DenseMap<QualType, unsigned> Found;
13096 for (auto Ts : {X, Y}) {
13097 for (QualType T : Ts) {
13098 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13099 if (!Res.second) {
13100 QualType &U = Out[Res.first->second];
13101 U = Ctx.getCommonSugaredType(U, T);
13102 } else {
13103 Out.emplace_back(T);
13104 }
13105 }
13106 }
13107}
13108
13112 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13113 bool AcceptDependent) {
13114 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13115
13116 // If either of them can throw anything, that is the result.
13117 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13118 if (EST1 == I)
13119 return ESI1;
13120 if (EST2 == I)
13121 return ESI2;
13122 }
13123
13124 // If either of them is non-throwing, the result is the other.
13125 for (auto I :
13127 if (EST1 == I)
13128 return ESI2;
13129 if (EST2 == I)
13130 return ESI1;
13131 }
13132
13133 // If we're left with value-dependent computed noexcept expressions, we're
13134 // stuck. Before C++17, we can just drop the exception specification entirely,
13135 // since it's not actually part of the canonical type. And this should never
13136 // happen in C++17, because it would mean we were computing the composite
13137 // pointer type of dependent types, which should never happen.
13138 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13139 assert(AcceptDependent &&
13140 "computing composite pointer type of dependent types");
13142 }
13143
13144 // Switch over the possibilities so that people adding new values know to
13145 // update this function.
13146 switch (EST1) {
13147 case EST_None:
13148 case EST_DynamicNone:
13149 case EST_MSAny:
13150 case EST_BasicNoexcept:
13152 case EST_NoexceptFalse:
13153 case EST_NoexceptTrue:
13154 case EST_NoThrow:
13155 llvm_unreachable("These ESTs should be handled above");
13156
13157 case EST_Dynamic: {
13158 // This is the fun case: both exception specifications are dynamic. Form
13159 // the union of the two lists.
13160 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13161 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13162 ESI2.Exceptions);
13164 Result.Exceptions = ExceptionTypeStorage;
13165 return Result;
13166 }
13167
13168 case EST_Unevaluated:
13169 case EST_Uninstantiated:
13170 case EST_Unparsed:
13171 llvm_unreachable("shouldn't see unresolved exception specifications here");
13172 }
13173
13174 llvm_unreachable("invalid ExceptionSpecificationType");
13175}
13176
13178 Qualifiers &QX, const Type *Y,
13179 Qualifiers &QY) {
13180 Type::TypeClass TC = X->getTypeClass();
13181 assert(TC == Y->getTypeClass());
13182 switch (TC) {
13183#define UNEXPECTED_TYPE(Class, Kind) \
13184 case Type::Class: \
13185 llvm_unreachable("Unexpected " Kind ": " #Class);
13186
13187#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13188#define TYPE(Class, Base)
13189#include "clang/AST/TypeNodes.inc"
13190
13191#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13192 SUGAR_FREE_TYPE(Builtin)
13193 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13194 SUGAR_FREE_TYPE(DependentBitInt)
13197 SUGAR_FREE_TYPE(ObjCInterface)
13199 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
13200 SUGAR_FREE_TYPE(UnresolvedUsing)
13201#undef SUGAR_FREE_TYPE
13202#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
13203 NON_UNIQUE_TYPE(TypeOfExpr)
13204 NON_UNIQUE_TYPE(VariableArray)
13205#undef NON_UNIQUE_TYPE
13206
13207 UNEXPECTED_TYPE(TypeOf, "sugar")
13208
13209#undef UNEXPECTED_TYPE
13210
13211 case Type::Auto: {
13212 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13213 assert(AX->getDeducedType().isNull());
13214 assert(AY->getDeducedType().isNull());
13215 assert(AX->getKeyword() == AY->getKeyword());
13216 assert(AX->isInstantiationDependentType() ==
13217 AY->isInstantiationDependentType());
13218 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
13219 AY->getTypeConstraintArguments());
13220 return Ctx.getAutoType(QualType(), AX->getKeyword(),
13222 AX->containsUnexpandedParameterPack(),
13223 getCommonDeclChecked(AX->getTypeConstraintConcept(),
13224 AY->getTypeConstraintConcept()),
13225 As);
13226 }
13227 case Type::IncompleteArray: {
13228 const auto *AX = cast<IncompleteArrayType>(X),
13229 *AY = cast<IncompleteArrayType>(Y);
13230 return Ctx.getIncompleteArrayType(
13231 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13233 }
13234 case Type::DependentSizedArray: {
13235 const auto *AX = cast<DependentSizedArrayType>(X),
13236 *AY = cast<DependentSizedArrayType>(Y);
13237 return Ctx.getDependentSizedArrayType(
13238 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13239 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
13241 AX->getBracketsRange() == AY->getBracketsRange()
13242 ? AX->getBracketsRange()
13243 : SourceRange());
13244 }
13245 case Type::ConstantArray: {
13246 const auto *AX = cast<ConstantArrayType>(X),
13247 *AY = cast<ConstantArrayType>(Y);
13248 assert(AX->getSize() == AY->getSize());
13249 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13250 ? AX->getSizeExpr()
13251 : nullptr;
13252 return Ctx.getConstantArrayType(
13253 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13255 }
13256 case Type::ArrayParameter: {
13257 const auto *AX = cast<ArrayParameterType>(X),
13258 *AY = cast<ArrayParameterType>(Y);
13259 assert(AX->getSize() == AY->getSize());
13260 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13261 ? AX->getSizeExpr()
13262 : nullptr;
13263 auto ArrayTy = Ctx.getConstantArrayType(
13264 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13266 return Ctx.getArrayParameterType(ArrayTy);
13267 }
13268 case Type::Atomic: {
13269 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
13270 return Ctx.getAtomicType(
13271 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
13272 }
13273 case Type::Complex: {
13274 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
13275 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
13276 }
13277 case Type::Pointer: {
13278 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
13279 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
13280 }
13281 case Type::BlockPointer: {
13282 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
13283 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
13284 }
13285 case Type::ObjCObjectPointer: {
13286 const auto *PX = cast<ObjCObjectPointerType>(X),
13287 *PY = cast<ObjCObjectPointerType>(Y);
13288 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
13289 }
13290 case Type::MemberPointer: {
13291 const auto *PX = cast<MemberPointerType>(X),
13292 *PY = cast<MemberPointerType>(Y);
13293 return Ctx.getMemberPointerType(
13294 getCommonPointeeType(Ctx, PX, PY),
13295 Ctx.getCommonSugaredType(QualType(PX->getClass(), 0),
13296 QualType(PY->getClass(), 0))
13297 .getTypePtr());
13298 }
13299 case Type::LValueReference: {
13300 const auto *PX = cast<LValueReferenceType>(X),
13301 *PY = cast<LValueReferenceType>(Y);
13302 // FIXME: Preserve PointeeTypeAsWritten.
13303 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
13304 PX->isSpelledAsLValue() ||
13305 PY->isSpelledAsLValue());
13306 }
13307 case Type::RValueReference: {
13308 const auto *PX = cast<RValueReferenceType>(X),
13309 *PY = cast<RValueReferenceType>(Y);
13310 // FIXME: Preserve PointeeTypeAsWritten.
13311 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
13312 }
13313 case Type::DependentAddressSpace: {
13314 const auto *PX = cast<DependentAddressSpaceType>(X),
13315 *PY = cast<DependentAddressSpaceType>(Y);
13316 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
13317 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
13318 PX->getAddrSpaceExpr(),
13319 getCommonAttrLoc(PX, PY));
13320 }
13321 case Type::FunctionNoProto: {
13322 const auto *FX = cast<FunctionNoProtoType>(X),
13323 *FY = cast<FunctionNoProtoType>(Y);
13324 assert(FX->getExtInfo() == FY->getExtInfo());
13325 return Ctx.getFunctionNoProtoType(
13326 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
13327 FX->getExtInfo());
13328 }
13329 case Type::FunctionProto: {
13330 const auto *FX = cast<FunctionProtoType>(X),
13331 *FY = cast<FunctionProtoType>(Y);
13332 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
13333 EPIY = FY->getExtProtoInfo();
13334 assert(EPIX.ExtInfo == EPIY.ExtInfo);
13335 assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos);
13336 assert(EPIX.RefQualifier == EPIY.RefQualifier);
13337 assert(EPIX.TypeQuals == EPIY.TypeQuals);
13338 assert(EPIX.Variadic == EPIY.Variadic);
13339
13340 // FIXME: Can we handle an empty EllipsisLoc?
13341 // Use emtpy EllipsisLoc if X and Y differ.
13342
13343 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
13344
13345 QualType R =
13346 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
13347 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
13348 /*Unqualified=*/true);
13349
13350 SmallVector<QualType, 8> Exceptions;
13352 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
13353 return Ctx.getFunctionType(R, P, EPIX);
13354 }
13355 case Type::ObjCObject: {
13356 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
13357 assert(
13358 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
13359 OY->getProtocols().begin(), OY->getProtocols().end(),
13360 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
13361 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
13362 }) &&
13363 "protocol lists must be the same");
13364 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
13365 OY->getTypeArgsAsWritten());
13366 return Ctx.getObjCObjectType(
13367 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
13368 OX->getProtocols(),
13369 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
13370 }
13371 case Type::ConstantMatrix: {
13372 const auto *MX = cast<ConstantMatrixType>(X),
13373 *MY = cast<ConstantMatrixType>(Y);
13374 assert(MX->getNumRows() == MY->getNumRows());
13375 assert(MX->getNumColumns() == MY->getNumColumns());
13376 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
13377 MX->getNumRows(), MX->getNumColumns());
13378 }
13379 case Type::DependentSizedMatrix: {
13380 const auto *MX = cast<DependentSizedMatrixType>(X),
13381 *MY = cast<DependentSizedMatrixType>(Y);
13382 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
13383 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
13384 return Ctx.getDependentSizedMatrixType(
13385 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
13386 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
13387 }
13388 case Type::Vector: {
13389 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
13390 assert(VX->getNumElements() == VY->getNumElements());
13391 assert(VX->getVectorKind() == VY->getVectorKind());
13392 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
13393 VX->getNumElements(), VX->getVectorKind());
13394 }
13395 case Type::ExtVector: {
13396 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
13397 assert(VX->getNumElements() == VY->getNumElements());
13398 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
13399 VX->getNumElements());
13400 }
13401 case Type::DependentSizedExtVector: {
13402 const auto *VX = cast<DependentSizedExtVectorType>(X),
13403 *VY = cast<DependentSizedExtVectorType>(Y);
13405 getCommonSizeExpr(Ctx, VX, VY),
13406 getCommonAttrLoc(VX, VY));
13407 }
13408 case Type::DependentVector: {
13409 const auto *VX = cast<DependentVectorType>(X),
13410 *VY = cast<DependentVectorType>(Y);
13411 assert(VX->getVectorKind() == VY->getVectorKind());
13412 return Ctx.getDependentVectorType(
13413 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
13414 getCommonAttrLoc(VX, VY), VX->getVectorKind());
13415 }
13416 case Type::InjectedClassName: {
13417 const auto *IX = cast<InjectedClassNameType>(X),
13418 *IY = cast<InjectedClassNameType>(Y);
13419 return Ctx.getInjectedClassNameType(
13420 getCommonDeclChecked(IX->getDecl(), IY->getDecl()),
13421 Ctx.getCommonSugaredType(IX->getInjectedSpecializationType(),
13422 IY->getInjectedSpecializationType()));
13423 }
13424 case Type::TemplateSpecialization: {
13425 const auto *TX = cast<TemplateSpecializationType>(X),
13426 *TY = cast<TemplateSpecializationType>(Y);
13427 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13428 TY->template_arguments());
13430 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
13431 TY->getTemplateName()),
13432 As, X->getCanonicalTypeInternal());
13433 }
13434 case Type::Decltype: {
13435 const auto *DX = cast<DecltypeType>(X);
13436 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
13437 assert(DX->isDependentType());
13438 assert(DY->isDependentType());
13439 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
13440 // As Decltype is not uniqued, building a common type would be wasteful.
13441 return QualType(DX, 0);
13442 }
13443 case Type::PackIndexing: {
13444 const auto *DX = cast<PackIndexingType>(X);
13445 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
13446 assert(DX->isDependentType());
13447 assert(DY->isDependentType());
13448 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
13449 return QualType(DX, 0);
13450 }
13451 case Type::DependentName: {
13452 const auto *NX = cast<DependentNameType>(X),
13453 *NY = cast<DependentNameType>(Y);
13454 assert(NX->getIdentifier() == NY->getIdentifier());
13455 return Ctx.getDependentNameType(
13456 getCommonTypeKeyword(NX, NY), getCommonNNS(Ctx, NX, NY),
13457 NX->getIdentifier(), NX->getCanonicalTypeInternal());
13458 }
13459 case Type::DependentTemplateSpecialization: {
13460 const auto *TX = cast<DependentTemplateSpecializationType>(X),
13461 *TY = cast<DependentTemplateSpecializationType>(Y);
13462 assert(TX->getIdentifier() == TY->getIdentifier());
13463 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13464 TY->template_arguments());
13466 getCommonTypeKeyword(TX, TY), getCommonNNS(Ctx, TX, TY),
13467 TX->getIdentifier(), As);
13468 }
13469 case Type::UnaryTransform: {
13470 const auto *TX = cast<UnaryTransformType>(X),
13471 *TY = cast<UnaryTransformType>(Y);
13472 assert(TX->getUTTKind() == TY->getUTTKind());
13473 return Ctx.getUnaryTransformType(
13474 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
13475 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
13476 TY->getUnderlyingType()),
13477 TX->getUTTKind());
13478 }
13479 case Type::PackExpansion: {
13480 const auto *PX = cast<PackExpansionType>(X),
13481 *PY = cast<PackExpansionType>(Y);
13482 assert(PX->getNumExpansions() == PY->getNumExpansions());
13483 return Ctx.getPackExpansionType(
13484 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
13485 PX->getNumExpansions(), false);
13486 }
13487 case Type::Pipe: {
13488 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
13489 assert(PX->isReadOnly() == PY->isReadOnly());
13490 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
13492 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
13493 }
13494 case Type::TemplateTypeParm: {
13495 const auto *TX = cast<TemplateTypeParmType>(X),
13496 *TY = cast<TemplateTypeParmType>(Y);
13497 assert(TX->getDepth() == TY->getDepth());
13498 assert(TX->getIndex() == TY->getIndex());
13499 assert(TX->isParameterPack() == TY->isParameterPack());
13500 return Ctx.getTemplateTypeParmType(
13501 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
13502 getCommonDecl(TX->getDecl(), TY->getDecl()));
13503 }
13504 }
13505 llvm_unreachable("Unknown Type Class");
13506}
13507
13509 const Type *Y,
13510 SplitQualType Underlying) {
13511 Type::TypeClass TC = X->getTypeClass();
13512 if (TC != Y->getTypeClass())
13513 return QualType();
13514 switch (TC) {
13515#define UNEXPECTED_TYPE(Class, Kind) \
13516 case Type::Class: \
13517 llvm_unreachable("Unexpected " Kind ": " #Class);
13518#define TYPE(Class, Base)
13519#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
13520#include "clang/AST/TypeNodes.inc"
13521
13522#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
13525 CANONICAL_TYPE(BlockPointer)
13526 CANONICAL_TYPE(Builtin)
13528 CANONICAL_TYPE(ConstantArray)
13529 CANONICAL_TYPE(ArrayParameter)
13530 CANONICAL_TYPE(ConstantMatrix)
13532 CANONICAL_TYPE(ExtVector)
13533 CANONICAL_TYPE(FunctionNoProto)
13534 CANONICAL_TYPE(FunctionProto)
13535 CANONICAL_TYPE(IncompleteArray)
13536 CANONICAL_TYPE(LValueReference)
13537 CANONICAL_TYPE(MemberPointer)
13538 CANONICAL_TYPE(ObjCInterface)
13539 CANONICAL_TYPE(ObjCObject)
13540 CANONICAL_TYPE(ObjCObjectPointer)
13544 CANONICAL_TYPE(RValueReference)
13545 CANONICAL_TYPE(VariableArray)
13547#undef CANONICAL_TYPE
13548
13549#undef UNEXPECTED_TYPE
13550
13551 case Type::Adjusted: {
13552 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
13553 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
13554 if (!Ctx.hasSameType(OX, OY))
13555 return QualType();
13556 // FIXME: It's inefficient to have to unify the original types.
13557 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
13558 Ctx.getQualifiedType(Underlying));
13559 }
13560 case Type::Decayed: {
13561 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
13562 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
13563 if (!Ctx.hasSameType(OX, OY))
13564 return QualType();
13565 // FIXME: It's inefficient to have to unify the original types.
13566 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
13567 Ctx.getQualifiedType(Underlying));
13568 }
13569 case Type::Attributed: {
13570 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
13571 AttributedType::Kind Kind = AX->getAttrKind();
13572 if (Kind != AY->getAttrKind())
13573 return QualType();
13574 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
13575 if (!Ctx.hasSameType(MX, MY))
13576 return QualType();
13577 // FIXME: It's inefficient to have to unify the modified types.
13578 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
13579 Ctx.getQualifiedType(Underlying));
13580 }
13581 case Type::BTFTagAttributed: {
13582 const auto *BX = cast<BTFTagAttributedType>(X);
13583 const BTFTypeTagAttr *AX = BX->getAttr();
13584 // The attribute is not uniqued, so just compare the tag.
13585 if (AX->getBTFTypeTag() !=
13586 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
13587 return QualType();
13588 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
13589 }
13590 case Type::Auto: {
13591 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13592
13593 AutoTypeKeyword KW = AX->getKeyword();
13594 if (KW != AY->getKeyword())
13595 return QualType();
13596
13597 ConceptDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
13598 AY->getTypeConstraintConcept());
13600 if (CD &&
13601 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
13602 AY->getTypeConstraintArguments())) {
13603 CD = nullptr; // The arguments differ, so make it unconstrained.
13604 As.clear();
13605 }
13606
13607 // Both auto types can't be dependent, otherwise they wouldn't have been
13608 // sugar. This implies they can't contain unexpanded packs either.
13609 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
13610 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
13611 }
13612 case Type::PackIndexing:
13613 case Type::Decltype:
13614 return QualType();
13615 case Type::DeducedTemplateSpecialization:
13616 // FIXME: Try to merge these.
13617 return QualType();
13618
13619 case Type::Elaborated: {
13620 const auto *EX = cast<ElaboratedType>(X), *EY = cast<ElaboratedType>(Y);
13621 return Ctx.getElaboratedType(
13622 ::getCommonTypeKeyword(EX, EY), ::getCommonNNS(Ctx, EX, EY),
13623 Ctx.getQualifiedType(Underlying),
13624 ::getCommonDecl(EX->getOwnedTagDecl(), EY->getOwnedTagDecl()));
13625 }
13626 case Type::MacroQualified: {
13627 const auto *MX = cast<MacroQualifiedType>(X),
13628 *MY = cast<MacroQualifiedType>(Y);
13629 const IdentifierInfo *IX = MX->getMacroIdentifier();
13630 if (IX != MY->getMacroIdentifier())
13631 return QualType();
13632 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
13633 }
13634 case Type::SubstTemplateTypeParm: {
13635 const auto *SX = cast<SubstTemplateTypeParmType>(X),
13636 *SY = cast<SubstTemplateTypeParmType>(Y);
13637 Decl *CD =
13638 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
13639 if (!CD)
13640 return QualType();
13641 unsigned Index = SX->getIndex();
13642 if (Index != SY->getIndex())
13643 return QualType();
13644 auto PackIndex = SX->getPackIndex();
13645 if (PackIndex != SY->getPackIndex())
13646 return QualType();
13647 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
13648 CD, Index, PackIndex);
13649 }
13650 case Type::ObjCTypeParam:
13651 // FIXME: Try to merge these.
13652 return QualType();
13653 case Type::Paren:
13654 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
13655
13656 case Type::TemplateSpecialization: {
13657 const auto *TX = cast<TemplateSpecializationType>(X),
13658 *TY = cast<TemplateSpecializationType>(Y);
13659 TemplateName CTN = ::getCommonTemplateName(Ctx, TX->getTemplateName(),
13660 TY->getTemplateName());
13661 if (!CTN.getAsVoidPointer())
13662 return QualType();
13664 if (getCommonTemplateArguments(Ctx, Args, TX->template_arguments(),
13665 TY->template_arguments()))
13666 return QualType();
13667 return Ctx.getTemplateSpecializationType(CTN, Args,
13668 Ctx.getQualifiedType(Underlying));
13669 }
13670 case Type::Typedef: {
13671 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
13672 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
13673 if (!CD)
13674 return QualType();
13675 return Ctx.getTypedefType(CD, Ctx.getQualifiedType(Underlying));
13676 }
13677 case Type::TypeOf: {
13678 // The common sugar between two typeof expressions, where one is
13679 // potentially a typeof_unqual and the other is not, we unify to the
13680 // qualified type as that retains the most information along with the type.
13681 // We only return a typeof_unqual type when both types are unqual types.
13683 if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
13684 cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
13686 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
13687 }
13688 case Type::TypeOfExpr:
13689 return QualType();
13690
13691 case Type::UnaryTransform: {
13692 const auto *UX = cast<UnaryTransformType>(X),
13693 *UY = cast<UnaryTransformType>(Y);
13694 UnaryTransformType::UTTKind KX = UX->getUTTKind();
13695 if (KX != UY->getUTTKind())
13696 return QualType();
13697 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
13698 if (!Ctx.hasSameType(BX, BY))
13699 return QualType();
13700 // FIXME: It's inefficient to have to unify the base types.
13701 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
13702 Ctx.getQualifiedType(Underlying), KX);
13703 }
13704 case Type::Using: {
13705 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
13706 const UsingShadowDecl *CD =
13707 ::getCommonDecl(UX->getFoundDecl(), UY->getFoundDecl());
13708 if (!CD)
13709 return QualType();
13710 return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying));
13711 }
13712 case Type::CountAttributed: {
13713 const auto *DX = cast<CountAttributedType>(X),
13714 *DY = cast<CountAttributedType>(Y);
13715 if (DX->isCountInBytes() != DY->isCountInBytes())
13716 return QualType();
13717 if (DX->isOrNull() != DY->isOrNull())
13718 return QualType();
13719 Expr *CEX = DX->getCountExpr();
13720 Expr *CEY = DY->getCountExpr();
13721 llvm::ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
13722 if (Ctx.hasSameExpr(CEX, CEY))
13723 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
13724 DX->isCountInBytes(), DX->isOrNull(),
13725 CDX);
13726 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
13727 return QualType();
13728 // Two declarations with the same integer constant may still differ in their
13729 // expression pointers, so we need to evaluate them.
13730 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
13731 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
13732 if (VX != VY)
13733 return QualType();
13734 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
13735 DX->isCountInBytes(), DX->isOrNull(),
13736 CDX);
13737 }
13738 }
13739 llvm_unreachable("Unhandled Type Class");
13740}
13741
13742static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
13744 while (true) {
13745 QTotal.addConsistentQualifiers(T.Quals);
13747 if (NT == QualType(T.Ty, 0))
13748 break;
13749 R.push_back(T);
13750 T = NT.split();
13751 }
13752 return R;
13753}
13754
13756 bool Unqualified) {
13757 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
13758 if (X == Y)
13759 return X;
13760 if (!Unqualified) {
13761 if (X.isCanonical())
13762 return X;
13763 if (Y.isCanonical())
13764 return Y;
13765 }
13766
13767 SplitQualType SX = X.split(), SY = Y.split();
13768 Qualifiers QX, QY;
13769 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
13770 // until we reach their underlying "canonical nodes". Note these are not
13771 // necessarily canonical types, as they may still have sugared properties.
13772 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
13773 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
13774 if (SX.Ty != SY.Ty) {
13775 // The canonical nodes differ. Build a common canonical node out of the two,
13776 // unifying their sugar. This may recurse back here.
13777 SX.Ty =
13778 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
13779 } else {
13780 // The canonical nodes were identical: We may have desugared too much.
13781 // Add any common sugar back in.
13782 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
13783 QX -= SX.Quals;
13784 QY -= SY.Quals;
13785 SX = Xs.pop_back_val();
13786 SY = Ys.pop_back_val();
13787 }
13788 }
13789 if (Unqualified)
13791 else
13792 assert(QX == QY);
13793
13794 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
13795 // related. Walk up these nodes, unifying them and adding the result.
13796 while (!Xs.empty() && !Ys.empty()) {
13797 auto Underlying = SplitQualType(
13798 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
13799 SX = Xs.pop_back_val();
13800 SY = Ys.pop_back_val();
13801 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
13803 // Stop at the first pair which is unrelated.
13804 if (!SX.Ty) {
13805 SX.Ty = Underlying.Ty;
13806 break;
13807 }
13808 QX -= Underlying.Quals;
13809 };
13810
13811 // Add back the missing accumulated qualifiers, which were stripped off
13812 // with the sugar nodes we could not unify.
13813 QualType R = getQualifiedType(SX.Ty, QX);
13814 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
13815 return R;
13816}
13817
13819 assert(Ty->isFixedPointType());
13820
13822 return Ty;
13823
13824 switch (Ty->castAs<BuiltinType>()->getKind()) {
13825 default:
13826 llvm_unreachable("Not a saturated fixed point type!");
13827 case BuiltinType::SatShortAccum:
13828 return ShortAccumTy;
13829 case BuiltinType::SatAccum:
13830 return AccumTy;
13831 case BuiltinType::SatLongAccum:
13832 return LongAccumTy;
13833 case BuiltinType::SatUShortAccum:
13834 return UnsignedShortAccumTy;
13835 case BuiltinType::SatUAccum:
13836 return UnsignedAccumTy;
13837 case BuiltinType::SatULongAccum:
13838 return UnsignedLongAccumTy;
13839 case BuiltinType::SatShortFract:
13840 return ShortFractTy;
13841 case BuiltinType::SatFract:
13842 return FractTy;
13843 case BuiltinType::SatLongFract:
13844 return LongFractTy;
13845 case BuiltinType::SatUShortFract:
13846 return UnsignedShortFractTy;
13847 case BuiltinType::SatUFract:
13848 return UnsignedFractTy;
13849 case BuiltinType::SatULongFract:
13850 return UnsignedLongFractTy;
13851 }
13852}
13853
13855 assert(Ty->isFixedPointType());
13856
13857 if (Ty->isSaturatedFixedPointType()) return Ty;
13858
13859 switch (Ty->castAs<BuiltinType>()->getKind()) {
13860 default:
13861 llvm_unreachable("Not a fixed point type!");
13862 case BuiltinType::ShortAccum:
13863 return SatShortAccumTy;
13864 case BuiltinType::Accum:
13865 return SatAccumTy;
13866 case BuiltinType::LongAccum:
13867 return SatLongAccumTy;
13868 case BuiltinType::UShortAccum:
13870 case BuiltinType::UAccum:
13871 return SatUnsignedAccumTy;
13872 case BuiltinType::ULongAccum:
13874 case BuiltinType::ShortFract:
13875 return SatShortFractTy;
13876 case BuiltinType::Fract:
13877 return SatFractTy;
13878 case BuiltinType::LongFract:
13879 return SatLongFractTy;
13880 case BuiltinType::UShortFract:
13882 case BuiltinType::UFract:
13883 return SatUnsignedFractTy;
13884 case BuiltinType::ULongFract:
13886 }
13887}
13888
13890 if (LangOpts.OpenCL)
13892
13893 if (LangOpts.CUDA)
13895
13896 return getLangASFromTargetAS(AS);
13897}
13898
13899// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
13900// doesn't include ASTContext.h
13901template
13903 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
13905 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
13906 const clang::ASTContext &Ctx, Decl *Value);
13907
13909 assert(Ty->isFixedPointType());
13910
13911 const TargetInfo &Target = getTargetInfo();
13912 switch (Ty->castAs<BuiltinType>()->getKind()) {
13913 default:
13914 llvm_unreachable("Not a fixed point type!");
13915 case BuiltinType::ShortAccum:
13916 case BuiltinType::SatShortAccum:
13917 return Target.getShortAccumScale();
13918 case BuiltinType::Accum:
13919 case BuiltinType::SatAccum:
13920 return Target.getAccumScale();
13921 case BuiltinType::LongAccum:
13922 case BuiltinType::SatLongAccum:
13923 return Target.getLongAccumScale();
13924 case BuiltinType::UShortAccum:
13925 case BuiltinType::SatUShortAccum:
13926 return Target.getUnsignedShortAccumScale();
13927 case BuiltinType::UAccum:
13928 case BuiltinType::SatUAccum:
13929 return Target.getUnsignedAccumScale();
13930 case BuiltinType::ULongAccum:
13931 case BuiltinType::SatULongAccum:
13932 return Target.getUnsignedLongAccumScale();
13933 case BuiltinType::ShortFract:
13934 case BuiltinType::SatShortFract:
13935 return Target.getShortFractScale();
13936 case BuiltinType::Fract:
13937 case BuiltinType::SatFract:
13938 return Target.getFractScale();
13939 case BuiltinType::LongFract:
13940 case BuiltinType::SatLongFract:
13941 return Target.getLongFractScale();
13942 case BuiltinType::UShortFract:
13943 case BuiltinType::SatUShortFract:
13944 return Target.getUnsignedShortFractScale();
13945 case BuiltinType::UFract:
13946 case BuiltinType::SatUFract:
13947 return Target.getUnsignedFractScale();
13948 case BuiltinType::ULongFract:
13949 case BuiltinType::SatULongFract:
13950 return Target.getUnsignedLongFractScale();
13951 }
13952}
13953
13955 assert(Ty->isFixedPointType());
13956
13957 const TargetInfo &Target = getTargetInfo();
13958 switch (Ty->castAs<BuiltinType>()->getKind()) {
13959 default:
13960 llvm_unreachable("Not a fixed point type!");
13961 case BuiltinType::ShortAccum:
13962 case BuiltinType::SatShortAccum:
13963 return Target.getShortAccumIBits();
13964 case BuiltinType::Accum:
13965 case BuiltinType::SatAccum:
13966 return Target.getAccumIBits();
13967 case BuiltinType::LongAccum:
13968 case BuiltinType::SatLongAccum:
13969 return Target.getLongAccumIBits();
13970 case BuiltinType::UShortAccum:
13971 case BuiltinType::SatUShortAccum:
13972 return Target.getUnsignedShortAccumIBits();
13973 case BuiltinType::UAccum:
13974 case BuiltinType::SatUAccum:
13975 return Target.getUnsignedAccumIBits();
13976 case BuiltinType::ULongAccum:
13977 case BuiltinType::SatULongAccum:
13978 return Target.getUnsignedLongAccumIBits();
13979 case BuiltinType::ShortFract:
13980 case BuiltinType::SatShortFract:
13981 case BuiltinType::Fract:
13982 case BuiltinType::SatFract:
13983 case BuiltinType::LongFract:
13984 case BuiltinType::SatLongFract:
13985 case BuiltinType::UShortFract:
13986 case BuiltinType::SatUShortFract:
13987 case BuiltinType::UFract:
13988 case BuiltinType::SatUFract:
13989 case BuiltinType::ULongFract:
13990 case BuiltinType::SatULongFract:
13991 return 0;
13992 }
13993}
13994
13995llvm::FixedPointSemantics
13997 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
13998 "Can only get the fixed point semantics for a "
13999 "fixed point or integer type.");
14000 if (Ty->isIntegerType())
14001 return llvm::FixedPointSemantics::GetIntegerSemantics(
14002 getIntWidth(Ty), Ty->isSignedIntegerType());
14003
14004 bool isSigned = Ty->isSignedFixedPointType();
14005 return llvm::FixedPointSemantics(
14006 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14008 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14009}
14010
14011llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14012 assert(Ty->isFixedPointType());
14013 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14014}
14015
14016llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14017 assert(Ty->isFixedPointType());
14018 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14019}
14020
14022 assert(Ty->isUnsignedFixedPointType() &&
14023 "Expected unsigned fixed point type");
14024
14025 switch (Ty->castAs<BuiltinType>()->getKind()) {
14026 case BuiltinType::UShortAccum:
14027 return ShortAccumTy;
14028 case BuiltinType::UAccum:
14029 return AccumTy;
14030 case BuiltinType::ULongAccum:
14031 return LongAccumTy;
14032 case BuiltinType::SatUShortAccum:
14033 return SatShortAccumTy;
14034 case BuiltinType::SatUAccum:
14035 return SatAccumTy;
14036 case BuiltinType::SatULongAccum:
14037 return SatLongAccumTy;
14038 case BuiltinType::UShortFract:
14039 return ShortFractTy;
14040 case BuiltinType::UFract:
14041 return FractTy;
14042 case BuiltinType::ULongFract:
14043 return LongFractTy;
14044 case BuiltinType::SatUShortFract:
14045 return SatShortFractTy;
14046 case BuiltinType::SatUFract:
14047 return SatFractTy;
14048 case BuiltinType::SatULongFract:
14049 return SatLongFractTy;
14050 default:
14051 llvm_unreachable("Unexpected unsigned fixed point type");
14052 }
14053}
14054
14055// Given a list of FMV features, return a concatenated list of the
14056// corresponding backend features (which may contain duplicates).
14057static std::vector<std::string> getFMVBackendFeaturesFor(
14058 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14059 std::vector<std::string> BackendFeats;
14060 for (StringRef F : FMVFeatStrings)
14061 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14062 for (StringRef F : FMVExt->getImpliedFeatures())
14063 BackendFeats.push_back(F.str());
14064 return BackendFeats;
14065}
14066
14068ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14069 assert(TD != nullptr);
14070 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14071
14072 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14073 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14074 });
14075 return ParsedAttr;
14076}
14077
14078void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14079 const FunctionDecl *FD) const {
14080 if (FD)
14081 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14082 else
14083 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14084 Target->getTargetOpts().CPU,
14085 Target->getTargetOpts().Features);
14086}
14087
14088// Fills in the supplied string map with the set of target features for the
14089// passed in function.
14090void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14091 GlobalDecl GD) const {
14092 StringRef TargetCPU = Target->getTargetOpts().CPU;
14093 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14094 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14096
14097 // Make a copy of the features as passed on the command line into the
14098 // beginning of the additional features from the function to override.
14099 // AArch64 handles command line option features in parseTargetAttr().
14100 if (!Target->getTriple().isAArch64())
14101 ParsedAttr.Features.insert(
14102 ParsedAttr.Features.begin(),
14103 Target->getTargetOpts().FeaturesAsWritten.begin(),
14104 Target->getTargetOpts().FeaturesAsWritten.end());
14105
14106 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14107 TargetCPU = ParsedAttr.CPU;
14108
14109 // Now populate the feature map, first with the TargetCPU which is either
14110 // the default or a new one from the target attribute string. Then we'll use
14111 // the passed in features (FeaturesAsWritten) along with the new ones from
14112 // the attribute.
14113 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14114 ParsedAttr.Features);
14115 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14117 Target->getCPUSpecificCPUDispatchFeatures(
14118 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14119 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14120 Features.insert(Features.begin(),
14121 Target->getTargetOpts().FeaturesAsWritten.begin(),
14122 Target->getTargetOpts().FeaturesAsWritten.end());
14123 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14124 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14125 if (Target->getTriple().isAArch64()) {
14127 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14128 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14129 Features.insert(Features.begin(),
14130 Target->getTargetOpts().FeaturesAsWritten.begin(),
14131 Target->getTargetOpts().FeaturesAsWritten.end());
14132 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14133 } else {
14134 std::vector<std::string> Features;
14135 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14136 if (VersionStr.starts_with("arch="))
14137 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14138 else if (VersionStr != "default")
14139 Features.push_back((StringRef{"+"} + VersionStr).str());
14140 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14141 }
14142 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14144 TV->getFeatures(Feats);
14145 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14146 Features.insert(Features.begin(),
14147 Target->getTargetOpts().FeaturesAsWritten.begin(),
14148 Target->getTargetOpts().FeaturesAsWritten.end());
14149 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14150 } else {
14151 FeatureMap = Target->getTargetOpts().FeatureMap;
14152 }
14153}
14154
14156 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
14157 return *OMPTraitInfoVector.back();
14158}
14159
14162 const ASTContext::SectionInfo &Section) {
14163 if (Section.Decl)
14164 return DB << Section.Decl;
14165 return DB << "a prior #pragma section";
14166}
14167
14169 bool IsInternalVar =
14170 isa<VarDecl>(D) &&
14171 basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal;
14172 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
14173 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
14174 (D->hasAttr<CUDAConstantAttr>() &&
14175 !D->getAttr<CUDAConstantAttr>()->isImplicit());
14176 // CUDA/HIP: managed variables need to be externalized since it is
14177 // a declaration in IR, therefore cannot have internal linkage. Kernels in
14178 // anonymous name space needs to be externalized to avoid duplicate symbols.
14179 return (IsInternalVar &&
14180 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
14181 (D->hasAttr<CUDAGlobalAttr>() &&
14182 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
14183 GVA_Internal);
14184}
14185
14187 return mayExternalize(D) &&
14188 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
14189 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
14190}
14191
14192StringRef ASTContext::getCUIDHash() const {
14193 if (!CUIDHash.empty())
14194 return CUIDHash;
14195 if (LangOpts.CUID.empty())
14196 return StringRef();
14197 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
14198 return CUIDHash;
14199}
14200
14201const CXXRecordDecl *
14203 assert(ThisClass);
14204 assert(ThisClass->isPolymorphic());
14205 const CXXRecordDecl *PrimaryBase = ThisClass;
14206 while (1) {
14207 assert(PrimaryBase);
14208 assert(PrimaryBase->isPolymorphic());
14209 auto &Layout = getASTRecordLayout(PrimaryBase);
14210 auto Base = Layout.getPrimaryBase();
14211 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
14212 break;
14213 PrimaryBase = Base;
14214 }
14215 return PrimaryBase;
14216}
14217
14219 StringRef MangledName) {
14220 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
14221 assert(Method->isVirtual());
14222 bool DefaultIncludesPointerAuth =
14223 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
14224
14225 if (!DefaultIncludesPointerAuth)
14226 return true;
14227
14228 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
14229 if (Existing != ThunksToBeAbbreviated.end())
14230 return Existing->second.contains(MangledName.str());
14231
14232 std::unique_ptr<MangleContext> Mangler(createMangleContext());
14233 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
14234 auto VtableContext = getVTableContext();
14235 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
14236 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
14237 for (const auto &Thunk : *ThunkInfos) {
14238 SmallString<256> ElidedName;
14239 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
14240 if (Destructor)
14241 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14242 Thunk, /* elideOverrideInfo */ true,
14243 ElidedNameStream);
14244 else
14245 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
14246 ElidedNameStream);
14247 SmallString<256> MangledName;
14248 llvm::raw_svector_ostream mangledNameStream(MangledName);
14249 if (Destructor)
14250 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14251 Thunk, /* elideOverrideInfo */ false,
14252 mangledNameStream);
14253 else
14254 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
14255 mangledNameStream);
14256
14257 if (Thunks.find(ElidedName) == Thunks.end())
14258 Thunks[ElidedName] = {};
14259 Thunks[ElidedName].push_back(std::string(MangledName));
14260 }
14261 }
14262 llvm::StringSet<> SimplifiedThunkNames;
14263 for (auto &ThunkList : Thunks) {
14264 llvm::sort(ThunkList.second);
14265 SimplifiedThunkNames.insert(ThunkList.second[0]);
14266 }
14267 bool Result = SimplifiedThunkNames.contains(MangledName);
14268 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
14269 return Result;
14270}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCommonTypes(ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool NeedsInjectedClassNameType(const RecordDecl *D)
#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static NamespaceDecl * getNamespace(const NestedNameSpecifier *X)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static NestedNameSpecifier * getCommonNNS(ASTContext &Ctx, const T *X, const T *Y)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty)
getSVETypeSize - Return SVE vector or predicate register size.
#define SUGAR_FREE_TYPE(Class)
static bool getCommonTemplateArguments(ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static TemplateName getCommonTemplateNameChecked(ASTContext &Ctx, TemplateName X, TemplateName Y)
static const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
Definition: ASTContext.cpp:337
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TemplateName getCommonTemplateName(ASTContext &Ctx, TemplateName X, TemplateName Y)
static bool hasSameOverloadableAttrs(const FunctionDecl *A, const FunctionDecl *B)
Determine whether the attributes we can overload on are identical for A and B.
static T * getCommonDeclChecked(T *X, T *Y)
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static TypedefDecl * CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
Definition: ASTContext.cpp:859
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
Definition: ASTContext.cpp:107
@ FloatRank
Definition: ASTContext.cpp:111
@ LongDoubleRank
Definition: ASTContext.cpp:113
@ Float16Rank
Definition: ASTContext.cpp:109
@ Ibm128Rank
Definition: ASTContext.cpp:115
@ Float128Rank
Definition: ASTContext.cpp:114
@ BFloat16Rank
Definition: ASTContext.cpp:108
@ HalfRank
Definition: ASTContext.cpp:110
@ DoubleRank
Definition: ASTContext.cpp:112
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static void mergeTypeLists(ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl * > Protocols)
static TypeInfoChars getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
static TemplateArgument getCommonTemplateArgument(ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static auto * getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y)
static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET)
static QualType getCommonArrayElementType(ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static QualType getCommonNonSugarTypeNode(ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType getCommonSugarTypeNode(ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static bool isSameQualifier(const NestedNameSpecifier *X, const NestedNameSpecifier *Y)
static std::string charUnitsToString(const CharUnits &CU)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
Definition: ASTContext.cpp:481
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
Definition: ASTContext.cpp:121
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y)
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3338
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
#define SM(sm)
Definition: Cuda.cpp:83
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition: CFG.cpp:2679
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1152
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines Expressions and AST nodes for C++2a concepts.
StringRef Text
Definition: Format.cpp:2990
unsigned Iter
Definition: HTMLLogger.cpp:154
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition: Value.h:143
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition: MachO.h:51
llvm::MachO::Record Record
Definition: MachO.h:31
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition: Module.cpp:100
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
uint32_t Id
Definition: SemaARM.cpp:1143
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
This file defines OpenACC AST classes for statement-level contructs.
static QualType getPointeeType(const MemRegion *R)
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
SourceLocation Begin
__device__ __2f16 float c
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition: APValue.cpp:1064
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1057
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:1071
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
CanQualType AccumTy
Definition: ASTContext.h:1131
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1150
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1100
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2822
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition: ASTContext.h:488
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
Definition: ASTContext.cpp:853
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1149
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition: ASTContext.h:855
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
Definition: ASTContext.h:1127
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true)
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped)
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
Definition: ASTContext.h:1123
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1127
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1140
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
ExternCContextDecl * getExternCContextDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, ConceptDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
Definition: ASTContext.h:1133
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2169
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:663
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
Definition: ASTContext.cpp:560
TemplateName getCanonicalTemplateName(const TemplateName &Name) const
Retrieves the "canonical" template name that refers to a given template.
QualType getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
Definition: ASTContext.h:1136
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:2043
QualType getRecordType(const RecordDecl *Decl) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1131
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1239
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3288
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
Definition: ASTContext.h:2430
unsigned char getFixedPointIBits(QualType Ty) const
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1130
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true)
Form a pack expansion type with the given pattern.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2625
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3302
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2641
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
Definition: ASTContext.h:1130
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
Definition: ASTContext.h:1136
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:2007
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
Definition: ASTContext.h:2482
void getInjectedTemplateArgs(const TemplateParameterList *Params, SmallVectorImpl< TemplateArgument > &Args)
Get a template argument list with one argument per template parameter in a template parameter list,...
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
Definition: ASTContext.h:1130
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1159
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
Definition: ASTContext.cpp:872
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
Definition: ASTContext.h:1125
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
Definition: ASTContext.cpp:328
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as 'l...
bool isSameTypeConstraint(const TypeConstraint *XTC, const TypeConstraint *YTC) const
Determine whether two type contraint are similar enough that they could used in declarations of the s...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
Definition: ASTContext.h:2191
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
const ASTRecordLayout & getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const
Get or compute information about the layout of the specified Objective-C implementation.
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1135
QualType getEnumType(const EnumDecl *Decl) const
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
Definition: ASTContext.h:1145
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1146
IdentifierInfo * getMakeIntegerSeqName() const
Definition: ASTContext.h:1981
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
void addLazyModuleInitializers(Module *M, ArrayRef< GlobalDeclID > IDs)
bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
IdentifierInfo * getTypePackElementName() const
Definition: ASTContext.h:1987
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
Definition: ASTContext.h:1145
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1634
CanQualType WideCharTy
Definition: ASTContext.h:1122
CanQualType OMPIteratorTy
Definition: ASTContext.h:1159
IdentifierTable & Idents
Definition: ASTContext.h:659
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:661
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:796
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl)
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
Definition: ASTContext.h:1022
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignement as specified by the target.
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:826
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
Definition: ASTContext.h:1139
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
bool canBindObjCObjectType(QualType To, QualType From)
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
Definition: ASTContext.h:1130
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1137
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
Definition: ASTContext.h:1158
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1150
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
QualType AutoDeductTy
Definition: ASTContext.h:1178
CanQualType BoolTy
Definition: ASTContext.h:1119
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
Definition: ASTContext.cpp:472
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:498
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field)
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2124
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
CanQualType UnsignedFractTy
Definition: ASTContext.h:1135
QualType getjmp_bufType() const
Retrieve the C jmp_buf type.
Definition: ASTContext.h:2019
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
QualType getsigjmp_bufType() const
Retrieve the C sigjmp_buf type.
Definition: ASTContext.h:2031
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
CanQualType Float128Ty
Definition: ASTContext.h:1130
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1150
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3267
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1146
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1128
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const
Determine whether the given template names refer to the same template.
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1133
QualType AutoRRefDeductTy
Definition: ASTContext.h:1179
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
Definition: ASTContext.h:1134
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
Retrieve a.
CanQualType BoundMemberTy
Definition: ASTContext.h:1146
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1140
CanQualType CharTy
Definition: ASTContext.h:1120
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition: ASTContext.h:829
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3281
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3274
CanQualType IntTy
Definition: ASTContext.h:1127
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1192
CanQualType PseudoObjectTy
Definition: ASTContext.h:1149
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
Definition: ASTContext.cpp:939
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters,...
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
void PrintStats() const
Definition: ASTContext.cpp:953
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:575
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3298
CanQualType Float16Ty
Definition: ASTContext.h:1144
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2207
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
Definition: ASTContext.h:1186
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CanQualType SignedCharTy
Definition: ASTContext.h:1127
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition: ASTContext.h:665
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1151
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
CanQualType OverloadTy
Definition: ASTContext.h:1146
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
CanQualType OCLClkEventTy
Definition: ASTContext.h:1155
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:712
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCImplementationDecl *ID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
CanQualType SatUnsignedShortAccumTy
Definition: ASTContext.h:1137
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
Definition: ASTContext.cpp:404
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
const ObjCMethodDecl * getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const
Get the duplicate declaration of a ObjCMethod in the same interface, or null if none exists.
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2371
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2114
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2672
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:580
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent)
unsigned getTargetDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass)
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2391
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1129
CanQualType BuiltinFnTy
Definition: ASTContext.h:1148
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3263
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3295
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition: ASTContext.h:835
CanQualType OCLSamplerTy
Definition: ASTContext.h:1155
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1118
CanQualType UnsignedCharTy
Definition: ASTContext.h:1128
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1135
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:733
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
Definition: ASTContext.h:1128
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply.
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3277
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1331
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
Definition: ASTContext.h:1147
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1129
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1156
bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two template parameters are similar enough that they may be used in declarations of...
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
Definition: ASTContext.h:1128
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1612
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1141
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, int Index=-1) const
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache.
Definition: ASTContext.cpp:295
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2825
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
Definition: ASTContext.cpp:949
const ObjCInterfaceDecl * getObjContainingInterface(const NamedDecl *ND) const
Returns the Objective-C interface that ND belongs to if it is an Objective-C method/property/ivar etc...
CanQualType ShortTy
Definition: ASTContext.h:1127
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true)
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Definition: ASTContext.h:1134
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
CanQualType LongAccumTy
Definition: ASTContext.h:1132
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
Definition: ASTContext.cpp:846
CanQualType Char32Ty
Definition: ASTContext.h:1126
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
Definition: ASTContext.h:1139
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl * > &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
CanQualType SatLongFractTy
Definition: ASTContext.h:1139
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:778
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
Definition: ASTContext.h:1156
CanQualType LongFractTy
Definition: ASTContext.h:1134
CanQualType SatShortAccumTy
Definition: ASTContext.h:1136
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1143
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3270
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1157
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
Definition: ASTContext.cpp:820
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1224
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
BuiltinTemplateDecl * getTypePackElementDecl() const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1138
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
Definition: ASTContext.h:1127
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
Definition: ASTContext.h:851
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1844
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
void addTranslationUnitDecl()
Definition: ASTContext.h:1103
CanQualType WCharTy
Definition: ASTContext.h:1121
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3284
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
Definition: ASTContext.h:842
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Retrieve a substitution-result type.
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers in instanc...
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
Definition: ASTContext.h:2293
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2299
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2296
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2305
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2302
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
Definition: ASTContext.h:1124
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
Definition: ASTContext.h:1142
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1133
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
bool isInSameModule(const Module *M1, const Module *M2)
If the two module M1 and M2 are in the same module.
void setCFConstantStringType(QualType T)
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
CanQualType OCLEventTy
Definition: ASTContext.h:1155
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
Definition: ASTContext.cpp:944
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
Definition: ASTContext.h:1012
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
Definition: ASTContext.cpp:217
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2422
QualType mergeTransparentUnionType(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeTransparentUnionType - if T is a transparent union type and a member of T is compatible with Sub...
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
CanQualType getNSUIntegerType() const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2395
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3291
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void AddedStaticLocalNumbers(const Decl *D, unsigned Number)
An static local number was added to a Decl.
virtual void RedefinedHiddenDefinition(const NamedDecl *D, Module *M)
A definition has been made visible by being redefined locally.
virtual void AddedManglingNumber(const Decl *D, unsigned Number)
An mangling number was added to a Decl.
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
Definition: RecordLayout.h:182
const CXXRecordDecl * getBaseSharingVBPtr() const
Definition: RecordLayout.h:329
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:193
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
Definition: RecordLayout.h:206
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:259
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:210
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustement.
Definition: RecordLayout.h:190
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3320
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3339
Represents a loop initializing the elements of an array.
Definition: Expr.h:5693
llvm::APInt getArraySize() const
Definition: Expr.h:5715
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition: Expr.h:5713
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3710
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3540
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3554
Qualifiers getIndexTypeQualifiers() const
Definition: Type.h:3558
QualType getElementType() const
Definition: Type.h:3552
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:3562
A structure for storing the information associated with a name that has been assumed to be a template...
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6619
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7573
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7578
Attr - This represents one attribute.
Definition: Attr.h:42
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:5991
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:6046
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6074
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6368
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:5094
bool isConstrained() const
Definition: Type.h:6387
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6109
A fixed int type of a specified bitwidth.
Definition: Type.h:7626
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:7643
unsigned getNumBits() const
Definition: Type.h:7638
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4467
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6355
Pointer to a block type.
Definition: Type.h:3371
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3388
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
static BuiltinTemplateDecl * Create(const ASTContext &C, DeclContext *DC, DeclarationName Name, BuiltinTemplateKind BTK)
This class is used for builtin types like 'int'.
Definition: Type.h:3000
Kind getKind() const
Definition: Type.h:3045
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3280
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
const char * getTypeString(unsigned ID) const
Get the type descriptor string for the specified builtin.
Definition: Builtins.h:106
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:196
bool canBeRedeclared(unsigned ID) const
Returns true if this is a builtin that can be redeclared.
Definition: Builtins.cpp:239
bool isNoReturn(unsigned ID) const
Return true if we know this builtin never returns.
Definition: Builtins.h:132
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:127
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:29
virtual ~CXXABI()
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2156
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1215
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
bool isDynamicClass() const
Definition: DeclCXX.h:585
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1190
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
bool isNull() const
Definition: CanonicalType.h:97
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Declaration of a class template.
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3108
QualType getElementType() const
Definition: Type.h:3118
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3123
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition: ASTConcept.h:210
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ASTConcept.h:204
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3578
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3674
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3634
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:3693
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3654
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4189
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4210
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4227
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4207
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:4218
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: Type.h:3269
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3305
Represents a pointer type decayed from an array or function type.
Definition: Type.h:3354
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1425
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2079
bool isFileContext() const
Definition: DeclBase.h:2150
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1309
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2095
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1828
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1964
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1742
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1040
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition: DeclBase.cpp:317
T * getAttr() const
Definition: DeclBase.h:579
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
void addAttr(Attr *A)
Definition: DeclBase.cpp:1014
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:537
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1042
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:963
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:249
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition: DeclBase.h:198
@ OBJC_TQ_Byref
Definition: DeclBase.h:204
@ OBJC_TQ_Oneway
Definition: DeclBase.h:205
@ OBJC_TQ_Bycopy
Definition: DeclBase.h:203
@ OBJC_TQ_None
Definition: DeclBase.h:199
@ OBJC_TQ_Inout
Definition: DeclBase.h:201
bool isInvalidDecl() const
Definition: DeclBase.h:594
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
SourceLocation getLocation() const
Definition: DeclBase.h:445
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:232
void setImplicit(bool I=true)
Definition: DeclBase.h:600
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1028
DeclContext * getDeclContext()
Definition: DeclBase.h:454
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:358
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:897
bool hasAttr() const
Definition: DeclBase.h:583
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:957
Kind getKind() const
Definition: DeclBase.h:448
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
DeclarationName getIdentifier(const IdentifierInfo *ID)
Create a declaration name that is a simple identifier.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:731
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:760
Represents the type decltype(expr) (C++11).
Definition: Type.h:5745
Represents a C++17 deduced template specialization type.
Definition: Type.h:6416
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:6437
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6334
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3881
Expr * getAddrSpaceExpr() const
Definition: Type.h:3892
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3903
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:7671
Internal representation of canonical, dependent decltype(expr) types.
Definition: Type.h:5773
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5777
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:6836
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6868
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3823
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3860
Expr * getSizeExpr() const
Definition: Type.h:3843
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3921
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3946
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4248
Expr * getRowExpr() const
Definition: Type.h:4260
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4268
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:491
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:563
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:550
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:553
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:569
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:6888
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:6915
Internal representation of canonical, dependent typeof(expr) types.
Definition: Type.h:5702
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5707
Internal representation of canonical, dependent __underlying_type(type) types.
Definition: Type.h:5896
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5901
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4043
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4068
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:873
Wrap a function effect's condition expression in another struct so that FunctionProtoType's TrailingO...
Definition: Type.h:4774
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6755
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6808
Represents an enum.
Definition: Decl.h:3840
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4045
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4059
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4000
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4926
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5962
EnumDecl * getDecl() const
Definition: Type.h:5969
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3075
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4102
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3050
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3941
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition: Type.h:1713
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:1760
ExtVectorType - Extended vector type.
Definition: Type.h:4083
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:222
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition: Decl.cpp:5320
Abstract interface for external sources of AST nodes.
virtual ExtKind hasExternalDefinitions(const Decl *D)
virtual void ReadComments()
Loads comment ranges.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
virtual void PrintStats()
Print any statistics that have been gathered regarding the external AST source.
Represents a member of a struct/union/class.
Definition: Decl.h:3030
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3121
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4632
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4580
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3243
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4533
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Definition: Decl.h:1932
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2562
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3620
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2793
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition: Decl.cpp:3745
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4254
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2335
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4002
bool isInlineDefinitionExternallyVisible() const
For an inline function definition in C, or for a gnu_inline function in C++, determine whether the de...
Definition: Decl.cpp:3915
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition: Type.cpp:5242
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5280
Represents an abstract function effect, using just an enumeration describing its kind.
Definition: Type.h:4673
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4853
size_t size() const
Definition: Type.h:4884
ArrayRef< EffectConditionExpr > conditions() const
Definition: Type.h:4887
bool empty() const
Definition: Type.h:4883
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4638
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4654
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4973
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5439
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5253
unsigned getNumParams() const
Definition: Type.h:5226
QualType getParamType(unsigned i) const
Definition: Type.h:5228
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3815
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5259
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5350
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5237
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5233
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:5415
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5411
Declaration of a template function.
Definition: DeclTemplate.h:957
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4389
CallingConv getCC() const
Definition: Type.h:4451
bool getNoCfCheck() const
Definition: Type.h:4441
unsigned getRegParm() const
Definition: Type.h:4444
bool getNoCallerSavedRegs() const
Definition: Type.h:4440
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4463
bool getHasRegParm() const
Definition: Type.h:4442
bool getNoReturn() const
Definition: Type.h:4437
bool getProducesResult() const
Definition: Type.h:4438
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4304
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:4344
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4278
ExtInfo getExtInfo() const
Definition: Type.h:4612
QualType getReturnType() const
Definition: Type.h:4600
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
unsigned getMultiVersionIndex() const
Definition: GlobalDecl.h:122
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:110
const Decl * getDecl() const
Definition: GlobalDecl.h:103
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
StringRef getName() const
Return the actual identifier string.
Implements an efficient mapping from strings to IdentifierInfo nodes.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4779
Represents a C array with an unspecified size.
Definition: Type.h:3725
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3742
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6605
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
@ Relative
Components in the vtable are relative offsets between the vtable and the other structs/functions.
@ Pointer
Components in the vtable are pointers to other structs/functions.
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3446
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
Definition: LangOptions.h:549
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:496
CoreFoundationABI CFRuntime
Definition: LangOptions.h:498
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:525
std::string CUID
The user provided compilation unit ID, if non-empty.
Definition: LangOptions.h:545
A global _GUID constant.
Definition: DeclCXX.h:4289
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition: DeclCXX.h:4326
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:5636
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:45
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4167
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:4174
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3482
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3518
QualType getPointeeType() const
Definition: Type.h:3498
const Type * getClass() const
Definition: Type.h:3512
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:615
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition: Module.h:105
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:185
This represents a decl that may have a name.
Definition: Decl.h:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:292
bool isExternallyVisible() const
Definition: Decl.h:408
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition: DeclCXX.h:3192
Represent a C++ namespace.
Definition: Decl.h:547
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:2977
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2326
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2542
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2594
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition: DeclObjC.cpp:322
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
Definition: DeclObjC.cpp:1542
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1527
ivar_range ivars() const
Definition: DeclObjC.h:1450
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
Definition: DeclObjC.cpp:1788
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
Definition: DeclObjC.cpp:1613
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1629
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1913
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:352
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition: DeclObjC.h:1808
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1760
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7336
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:903
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1985
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: DeclObjC.h:246
unsigned param_size() const
Definition: DeclObjC.h:347
param_const_iterator param_end() const
Definition: DeclObjC.h:358
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
bool isVariadic() const
Definition: DeclObjC.h:431
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
QualType getReturnType() const
Definition: DeclObjC.h:329
Represents a pointer to an Objective C object.
Definition: Type.h:7392
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition: Type.h:7473
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition: Type.cpp:910
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:7467
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7549
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7429
bool qual_empty() const
Definition: Type.h:7521
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7450
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7404
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7444
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1799
qual_range quals() const
Definition: Type.h:7511
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7456
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: Type.h:7289
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4379
Represents a class type in Objective C.
Definition: Type.h:7138
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:7253
bool isSpecialized() const
Determine whether this object type is "specialized", meaning that it has type arguments.
Definition: Type.cpp:832
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: Type.h:7248
bool isObjCQualifiedClass() const
Definition: Type.h:7220
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:7200
bool isObjCClass() const
Definition: Type.h:7206
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:868
bool isObjCQualifiedId() const
Definition: Type.h:7219
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:850
bool isObjCUnqualifiedId() const
Definition: Type.h:7210
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:7371
QualType getSuperClassType() const
Retrieve the type of the superclass of this object type.
Definition: Type.h:7264
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:837
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:179
bool isOptional() const
Definition: DeclObjC.h:915
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition: DeclObjC.h:872
Selector getSetterName() const
Definition: DeclObjC.h:892
QualType getType() const
Definition: DeclObjC.h:803
Selector getGetterName() const
Definition: DeclObjC.h:884
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:814
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2802
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2876
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2082
protocol_range protocols() const
Definition: DeclObjC.h:2158
unsigned getNumProtocols() const
Return the number of qualifying protocols in this type, or 0 if there are none.
Definition: Type.h:7044
qual_iterator qual_end() const
Definition: Type.h:7038
qual_iterator qual_begin() const
Definition: Type.h:7037
qual_range quals() const
Definition: Type.h:7036
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Definition: ObjCRuntime.h:127
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:578
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition: DeclObjC.h:623
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:659
Represents a type parameter type in Objective C.
Definition: Type.h:7064
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4396
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:108
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4178
Represents a pack expansion of types.
Definition: Type.h:6953
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6987
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5832
Sugar for parentheses used when specifying types.
Definition: Type.h:3135
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3149
void clear()
Clear parent maps.
Represents a parameter to a function.
Definition: Decl.h:1722
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1786
QualType getOriginalType() const
Definition: Decl.cpp:2912
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
PipeType - OpenCL20.
Definition: Type.h:7592
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7609
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3161
QualType getPointeeType() const
Definition: Type.h:3171
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3176
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:137
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7827
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2748
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:7874
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7832
QualType withConst() const
Definition: Type.h:1166
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:1068
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7743
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7869
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7783
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
QualType getCanonicalType() const
Definition: Type.h:7795
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7837
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:7764
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7816
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1542
bool isCanonical() const
Definition: Type.h:7800
const Type * getTypePtrOrNull() const
Definition: Type.h:7747
PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition: Type.cpp:2885
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7775
Represents a template name as written in source code.
Definition: TemplateName.h:434
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:471
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7683
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7690
The collection of all-type qualifiers we support.
Definition: Type.h:319
unsigned getCVRQualifiers() const
Definition: Type.h:475
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:482
GC getObjCGCAttr() const
Definition: Type.h:506
void addAddressSpace(LangAS space)
Definition: Type.h:584
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition: Type.h:371
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:341
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:337
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:351
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:354
void removeObjCLifetime()
Definition: Type.h:538
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition: Type.h:625
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition: Type.h:676
void removeFastQualifiers(unsigned mask)
Definition: Type.h:611
bool hasUnaligned() const
Definition: Type.h:498
bool hasAddressSpace() const
Definition: Type.h:557
unsigned getFastQualifiers() const
Definition: Type.h:606
void removeAddressSpace()
Definition: Type.h:583
void setAddressSpace(LangAS space)
Definition: Type.h:578
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:695
bool hasObjCGCAttr() const
Definition: Type.h:505
uint64_t getAsOpaqueValue() const
Definition: Type.h:442
bool hasObjCLifetime() const
Definition: Type.h:531
ObjCLifetime getObjCLifetime() const
Definition: Type.h:532
bool empty() const
Definition: Type.h:634
void addObjCGCAttr(GC type)
Definition: Type.h:511
LangAS getAddressSpace() const
Definition: Type.h:558
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3464
unsigned getCommentBeginLine(RawComment *C, FileID File, unsigned Offset) const
const std::map< unsigned, RawComment * > * getCommentsInFile(FileID File) const
unsigned getCommentEndOffset(RawComment *C) const
void addComment(const RawComment &RC, const CommentOptions &CommentOpts, llvm::BumpPtrAllocator &Allocator)
bool isTrailingComment() const LLVM_READONLY
Returns true if it is a comment that should be put after a member:
SourceRange getSourceRange() const LLVM_READONLY
bool isDocumentation() const LLVM_READONLY
Returns true if this comment any kind of a documentation comment.
comments::FullComment * parse(const ASTContext &Context, const Preprocessor *PP, const Decl *D) const
Parse the comment, assuming it is attached to decl D.
Represents a struct/union/class.
Definition: Decl.h:4141
bool hasFlexibleArrayMember() const
Definition: Decl.h:4174
field_range fields() const
Definition: Decl.h:4347
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5003
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5069
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4332
bool field_empty() const
Definition: Decl.h:4355
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5936
RecordDecl * getDecl() const
Definition: Type.h:5946
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3402
QualType getPointeeType() const
Definition: Type.h:3420
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3428
This table allows us to fully hide how we implement multi-keyword caching.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
DiagnosticsEngine & getDiagnostics() const
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
Definition: Diagnostic.h:1115
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1191
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:141
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: TemplateName.h:156
A structure for storing the information associated with a substituted template template parameter.
Definition: TemplateName.h:375
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6276
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4241
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6206
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6245
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3557
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3785
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4725
bool isUnion() const
Definition: Decl.h:3763
TagDecl * getDecl() const
Definition: Type.cpp:4069
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Kind
The basic C++ ABI kind.
Definition: TargetCXXABI.h:31
static Kind getKind(StringRef Name)
Definition: TargetCXXABI.h:59
Exposes information about the current target.
Definition: TargetInfo.h:218
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:312
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
IntType getInt64Type() const
Definition: TargetInfo.h:405
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition: TargetInfo.h:834
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1639
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1633
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition: TargetInfo.h:727
unsigned getBFloat16Width() const
getBFloat16Width/Align/Format - Return the size/align/format of '__bf16'.
Definition: TargetInfo.h:772
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition: TargetInfo.h:319
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition: TargetInfo.h:328
@ PNaClABIBuiltinVaList
__builtin_va_list as defined by the PNaCl ABI: http://www.chromium.org/nativeclient/pnacl/bitcode-abi...
Definition: TargetInfo.h:332
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition: TargetInfo.h:337
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition: TargetInfo.h:346
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:321
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition: TargetInfo.h:324
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition: TargetInfo.h:341
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition: TargetInfo.h:488
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:472
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
Definition: TargetInfo.cpp:370
unsigned getHalfAlign() const
Definition: TargetInfo.h:763
unsigned getBFloat16Align() const
Definition: TargetInfo.h:773
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
Definition: TargetInfo.cpp:316
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
Definition: TargetInfo.cpp:286
unsigned getHalfWidth() const
getHalfWidth/Align/Format - Return the size/align/format of 'half'.
Definition: TargetInfo.h:762
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition: TargetInfo.h:947
virtual unsigned getMinGlobalAlign(uint64_t Size, bool HasNonWeakDef) const
getMinGlobalAlign - Return the minimum alignment of a global variable, unless its alignment is explic...
Definition: TargetInfo.h:735
unsigned getTargetAddressSpace(LangAS AS) const
Definition: TargetInfo.h:1620
unsigned getFloat128Width() const
getFloat128Width/Align/Format - Return the size/align/format of '__float128'.
Definition: TargetInfo.h:791
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:785
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
bool hasAArch64SVETypes() const
Returns whether or not the AArch64 SVE built-in types are available on this target.
Definition: TargetInfo.h:1040
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
Definition: TargetInfo.h:998
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:514
unsigned getFloat128Align() const
Definition: TargetInfo.h:792
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:699
const llvm::fltSemantics & getFloat128Format() const
Definition: TargetInfo.h:793
unsigned getLongDoubleWidth() const
getLongDoubleWidth/Align/Format - Return the size/align/format of 'long double'.
Definition: TargetInfo.h:783
unsigned getLongDoubleAlign() const
Definition: TargetInfo.h:784
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts) const
Returns target-specific min and max values VScale_Range.
Definition: TargetInfo.h:1017
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
Definition: TargetOptions.h:62
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:648
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:647
A template argument list.
Definition: DeclTemplate.h:244
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
std::optional< unsigned > getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:377
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
Definition: TemplateBase.h:393
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:432
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:355
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:248
@ OverloadedTemplate
A set of overloaded template declarations.
Definition: TemplateName.h:223
@ Template
A single template declaration.
Definition: TemplateName.h:220
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:235
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:239
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
Definition: TemplateName.h:244
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
Definition: TemplateName.h:231
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
Definition: TemplateName.h:227
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:129
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1687
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1663
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1704
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1671
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1679
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6473
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:4331
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, bool Typename, TemplateParameterList *Params)
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6178
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:228
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:251
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:243
ConceptReference * getConceptReference() const
Definition: ASTConcept.h:247
Represents a declaration of a type.
Definition: Decl.h:3363
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3388
const Type * getTypeForDecl() const
Definition: Decl.h:3387
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
static unsigned getFullDataSizeForType(QualType Ty)
Returns the size of type source info data block for the given type.
Definition: TypeLoc.cpp:94
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition: TypeLoc.h:200
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5668
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5718
A container of type source information.
Definition: Type.h:7714
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
The base class of the type hierarchy.
Definition: Type.h:1829
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isBlockPointerType() const
Definition: Type.h:8006
bool isVoidType() const
Definition: Type.h:8295
bool isBooleanType() const
Definition: Type.h:8423
bool isFunctionReferenceType() const
Definition: Type.h:8039
bool isObjCBuiltinType() const
Definition: Type.h:8185
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition: Type.cpp:2576
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isIncompleteArrayType() const
Definition: Type.h:8072
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:8271
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2146
bool isConstantArrayType() const
Definition: Type.h:8068
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:2021
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2352
bool isArrayType() const
Definition: Type.h:8064
bool isCharType() const
Definition: Type.cpp:2089
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition: Type.cpp:476
bool isFunctionPointerType() const
Definition: Type.h:8032
bool isPointerType() const
Definition: Type.h:7996
bool isArrayParameterType() const
Definition: Type.h:8080
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8335
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8583
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:8284
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8376
bool isEnumeralType() const
Definition: Type.h:8096
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2507
bool isObjCQualifiedIdType() const
Definition: Type.h:8155
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8410
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2236
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2545
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2777
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2680
bool isBitIntType() const
Definition: Type.h:8230
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8264
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8088
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2672
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8348
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8364
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2336
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2186
QualType getCanonicalTypeInternal() const
Definition: Type.h:2955
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8466
bool isMemberPointerType() const
Definition: Type.h:8046
bool isObjCIdType() const
Definition: Type.h:8167
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8372
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8569
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isFunctionType() const
Definition: Type.h:7992
bool isObjCObjectPointerType() const
Definition: Type.h:8134
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8390
bool isVectorType() const
Definition: Type.h:8104
bool isObjCClassType() const
Definition: Type.h:8173
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition: Type.cpp:2558
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2494
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2196
bool isAnyPointerType() const
Definition: Type.h:8000
TypeClass getTypeClass() const
Definition: Type.h:2316
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2342
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8516
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:605
bool isNullPtrType() const
Definition: Type.h:8328
bool isRecordType() const
Definition: Type.h:8092
bool isObjCRetainableType() const
Definition: Type.cpp:4941
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4686
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3507
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5491
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3405
QualType getUnderlyingType() const
Definition: Decl.h:3460
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3467
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5621
A unary type transform, which is a type constructed from another.
Definition: Type.h:5853
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4346
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition: DeclCXX.h:4374
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:5538
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3959
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3713
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3320
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5589
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
void setType(QualType newType)
Definition: Decl.h:679
QualType getType() const
Definition: Decl.h:678
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5353
void clear()
Definition: Value.cpp:218
Represents a variable declaration or definition.
Definition: Decl.h:879
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2775
bool hasInit() const
Definition: Decl.cpp:2380
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2426
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1231
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1156
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2737
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1492
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1243
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2357
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2744
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3769
Expr * getSizeExpr() const
Definition: Type.h:3788
Represents a GCC generic vector type.
Definition: Type.h:3991
unsigned getNumElements() const
Definition: Type.h:4006
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4015
VectorKind getVectorKind() const
Definition: Type.h:4011
QualType getElementType() const
Definition: Type.h:4005
A full comment attached to a declaration, contains block content.
Definition: Comment.h:1083
ArrayRef< BlockContentComment * > getBlocks() const
Definition: Comment.h:1121
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition: Comment.h:1115
const Decl * getDecl() const LLVM_READONLY
Definition: Comment.h:1111
Holds all information required to evaluate constexpr code in a module.
Definition: Context.h:40
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
const AstTypeMatcher< TagType > tagType
Matches tag types (record and enum types).
The JSON file list parser is used to communicate input to InstallAPI.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OpenCL
Definition: LangStandard.h:66
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition: Linkage.h:72
@ GVA_StrongODR
Definition: Linkage.h:77
@ GVA_StrongExternal
Definition: Linkage.h:76
@ GVA_AvailableExternally
Definition: Linkage.h:74
@ GVA_DiscardableODR
Definition: Linkage.h:75
@ GVA_Internal
Definition: Linkage.h:73
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition: Type.h:1788
OpenCLTypeKind
OpenCL type kinds.
Definition: TargetInfo.h:204
@ OCLTK_ReserveID
Definition: TargetInfo.h:211
@ OCLTK_Sampler
Definition: TargetInfo.h:212
@ OCLTK_Pipe
Definition: TargetInfo.h:209
@ OCLTK_ClkEvent
Definition: TargetInfo.h:206
@ OCLTK_Event
Definition: TargetInfo.h:207
@ OCLTK_Default
Definition: TargetInfo.h:205
@ OCLTK_Queue
Definition: TargetInfo.h:210
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition: Type.h:7896
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:269
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
TypeOfKind
The kind of 'typeof' expression we're after.
Definition: Type.h:922
@ SC_Register
Definition: Specifiers.h:254
@ SC_Static
Definition: Specifiers.h:249
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
@ TypeAlignment
Definition: Type.h:73
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Result
The result type of a method or function.
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: Type.h:3537
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
TagTypeKind
The kind of a tag type.
Definition: Type.h:6683
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition: Builtins.h:307
@ BTK__type_pack_element
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:312
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:309
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:1037
FloatModeKind
Definition: TargetInfo.h:72
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1264
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_C
Definition: Specifiers.h:276
@ CC_M68kRTD
Definition: Specifiers.h:297
@ CC_X86RegCall
Definition: Specifiers.h:284
@ CC_X86VectorCall
Definition: Specifiers.h:280
@ CC_X86StdCall
Definition: Specifiers.h:277
@ CC_X86FastCall
Definition: Specifiers.h:278
@ Invariant
The parameter is invariant: must match exactly.
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
VectorKind
Definition: Type.h:3954
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:86
AlignRequirementKind
Definition: ASTContext.h:142
@ None
The alignment was not explicit in code.
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6658
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
@ AS_public
Definition: Specifiers.h:121
unsigned long uint64_t
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:694
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition: Expr.h:6401
Expr * getCopyExpr() const
Definition: Expr.h:6408
bool ParseAllComments
Treat ordinary comments as documentation comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
Holds information about the various types of exception specification.
Definition: Type.h:5030
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5032
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5035
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:5038
Extra information about a function prototype.
Definition: Type.h:5058
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5065
bool requiresFunctionProtoTypeArmAttributes() const
Definition: Type.h:5090
FunctionEffectsRef FunctionEffects
Definition: Type.h:5068
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5066
bool requiresFunctionProtoTypeExtraBitfields() const
Definition: Type.h:5084
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5059
A simple holder for a QualType representing a type in an exception specification.
Definition: Type.h:4516
A holder for Arm type attributes as described in the Arm C/C++ Language extensions which are not part...
Definition: Type.h:4577
A simple holder for various uncommon bits which do not fit in FunctionTypeBitfields.
Definition: Type.h:4521
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4264
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:57
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:874
const Type * Ty
The locally-unqualified type.
Definition: Type.h:876
Qualifiers Quals
The local qualifiers.
Definition: Type.h:879
A this pointer adjustment.
Definition: Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition: TargetInfo.h:142
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:173
bool isAlignRequired()
Definition: ASTContext.h:165
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:159
uint64_t Width
Definition: ASTContext.h:157
unsigned Align
Definition: ASTContext.h:158
Information about the declaration, useful to clients of FullComment.
Definition: Comment.h:962
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition: Comment.h:988
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition: Comment.h:965